Spring Data JPA 映射VO/DTO对象方式

Spring Data JPA 映射VO/DTO对象

在项目开发中,时常需要根据业务需求来映射VO/DTO对象(这两个概念理解感觉很模糊- 。- ),本文将简单介绍以Spring Data JPA的方式处理实体类映射

HQL方式

public interface MusicTypeRepository extends JpaRepository {
     @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 getTypeInfo();
}
  • 填写实体类路径,构造参数顺序要一致,字段名一律为实体类中的属性
  • 如果配置了实体类属性的映射关系,则on s.musicTypeId = m.id语句可以省略

VO实体类

@Value
public class StudentTypeInfoVo  {
    private Long count;
    private String name;
}

使用Lombok的 @Value 注解

  • 默认生成带参构造方法
  • 默认为成员变量添加final修饰,且只提供getter()方法

原生SQL的形式

接口形式

public interface CoursePlanRepository extends JpaRepository {
       @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 getWeekList();
}
  • nativeQuery = true 表示开启原生SQL查询
  • 查询字段别名需要与实体类中字段一一对应
  • 该方法功能为查询一周后的数据
函数 说明
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'

VO实体类(接口形式)

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 listType1();

对比第一种方法,使用原生SQL默认会返回Object数组

Spring Data Jpa 自定义repository转DTO

近期项目中需要 关联 几张表再把字段转出来,在这里记录以下,我感觉网上写的都不太规范和清晰。

@Entity
@SqlResultSetMapping(
        name="TestMapping",
        entities = {
                @EntityResult(
                        entityClass = com.xxx.xx.data.model.TestEntity.class,
                        fields = {
                                @FieldResult(name="id",column="id"),
                                @FieldResult(name="localTime",column="time"),
                                @FieldResult(name="maximumAppointment",column="maxAppointment"),
                        }
                )
        }
)
@NamedNativeQuery(name="getTestQuery",
        query="select tableC.id as id,tableB.time,tableC.maximumAppointment as maxAppointment from tableB " +
                "                              inner join tableA on tableA.id = tableB.tableAId " +
                "                              inner join tableC on tableB.id = tableC.tableBId " +
                "                              inner join custom on custom.id = tableA.customId " +
                "where " +
                "   tableA.locationId = :locationId" +
                "   and custom.id = :customId" +
                "   and tableB.deleted = false ", resultSetMapping="TestMapping")
@Data
public class TestEntity {
    @Id
    private String id;
    private LocalTime localTime;
    private Integer maximumAppointment;
}

需要声明接口:

@Repository
public interface TestEntityRepository extends JpaRepository {
    @Query(name="getTestQuery")
    List getTestQuery(String locationId, String customId);
}

若不想声明接口,那可以用EntityManager 来实现。

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的