简介
在项目开发中,时常需要根据业务需求来映射VO/DTO对象(这两个概念理解感觉很模糊,本文将简单介绍以Spring Data JPA的方式处理实体类映射
public interface MusicTypeRepository extends JpaRepository<MusicType,Integer> {
@Query("select new cn.srblog.springbootcurd.vo.StudentTypeInfoVo(count(s.id),m.name) " +
"FROM MusicType m left JOIN Student s on s.musicTypeId = m.id group by m.id ")
List<StudentTypeInfoVo> getTypeInfo();
}
on s.musicTypeId = m.id
语句可以省略@Value
public class StudentTypeInfoVo {
private Long count;
private String name;
}
使用Lombok
的 @Value
注解
final
修饰,且只提供getter()方法public interface CoursePlanRepository extends JpaRepository<CoursePlan,Integer> {
@Query(nativeQuery = true,value = "SELECT " +
" c.id as id," +
"DAYOFWEEK(c.start_time) as week," +
"m.name as musicType," +
"t.name as teacherName," +
"c.start_time as startTime," +
"c.end_time as endTime " +
" FROM t_courseplan c,t_musictype m , t_teacher t " +
" WHERE DATE(c.start_time) < DATE_ADD(CURDATE(), INTERVAL 7 DAY ) AND CURDATE() <= DATE(c.start_time) " +
" and t.id=c.tea_id and c.music_type_id = m.id order by c.start_time ")
List<CoursePlanVos> getWeekList();
}
`
函数 | 说明 |
---|---|
DAYOFWEEK() | DAYOFWEEK函数返回日期的工作日索引值,即星期日为1,星期一为2,星期六为7。例:DAYOFWEEK('2019-05-09') 返回 5 |
DATE() | 提取日期或日期/时间表达式的日期部分,格式'YYYY-MM-DD'或者'YYYYMMDD' |
DATE_ADD(date,INTERVAL expr unit) | 给日期添加指定的时间间隔。date 参数是合法的日期表达式,expr 参数是您希望添加的时间间隔,type 参数可以是MySQL支持的时间日期相关类型值 |
CURDATE() | 返回当前日期 例:'2019-05-09' |
public interface CoursePlanVos{
Integer getId();
Integer getWeek();
String getMusicType();
String getTeacherName();
Date getStartTime() ;
Date getEndTime();
}
@Query(value = "select count(s.id) as count,m.name as name " +
" FROM t_musictype m left JOIN t_student s on s.music_type_id = m.id group by m.id ",nativeQuery = true)
List<Object[]> listType1();
对比第一种方法,使用原生SQL默认会返回Object数组