使用Spring Data JPA,您可以通过定义接口,面来避免Object[]以更优雅的格式返回数据,sql的返回值和接口的属性名一致。jap会根据sql返回值映射到接口对应属性。

发布时间 2023-11-03 17:46:49作者: sunny123456

使用Spring Data JPA,您可以通过定义接口,面来避免Object[]以更优雅的格式返回数据,sql的返回值和接口的属性名一致。jap会根据sql返回值映射到接口对应属性。

cas*_*lin 6

根据定义,JPA将返回Object[]查询返回带有投影的列表的列表,即来自实体(或多个实体)的一组字段.

使用Spring Data JPA,您可以通过定义如下界面来避免Object[]更优雅的格式返回数据:

public interface MainEntityProjection {
    String getStart();
    String getFinish();
    String getForename();
    String getSurname();
}
Run Code Online (Sandbox Code Playgroud)

并更改您的查询方法以返回上面定义的接口:

@Query("SELECT e.start, e.finish, e.forename, e.surname " +
       "FROM MainEntity e " +
       "WHERE e.volunteerId = :id AND e.areaId > 0 AND e.isAssignment = true " +
       "ORDER BY e.start")
List<MainEntityProjection> findAssignments(@Param("id") int volunteerId);
Run Code Online (Sandbox Code Playgroud)

Spring Data JPA文档中描述了这种方法.


除了Spring Data JPA之外,JPA本身SELECT NEW使用公共构造函数处理它.您可以将类定义如下:

public class MainEntityProjection {
    private String start;
    private String finish;
    private String forename;
    private String surname;
    public MainEntityProjection(String start, String finish,
                                String forename, String surname) {
        this.start = start;   
        this.finish = finish;
        this.forename = forename;
        this.surname = surname;
    }
    // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

然后你的查询将是:

SELECT NEW org.example.MainEntityProjection(e.start, e.finish, e.forename, e.surname)
FROM MainEntity e
WHERE e.volunteerId = :id AND e.areaId > 0 AND e.isAssignment = true
ORDER BY e.start
Run Code Online (Sandbox Code Playgroud)

上述查询也可以与Spring Data JPA一起使用(您的方法将返回一个列表MainEntityProjection).

检查JSR 338,定义JPA 2.1的文档,说明使用SELECT NEW和构造函数表达式:

4.8.2 SELECT子句中的构造函数表达式

可以在SELECT列表中使用构造函数来返回Java类的实例.指定的类不需要是实体或映射到数据库.构造函数名称必须是完全限定的.

如果在SELECT NEW子句中将实体类名指定为构造函数名称,则生成的实体实例将处于新状态或分离状态,具体取决于是否为构造对象检索主键.

如果作为构造函数参数的single_valued_pa​​th_expressionidentification_variable引用实体,则该single_valued_pa​​th_expressionidentification_variable引用的结果实体实例将处于托管状态.

例如,

SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count)
FROM Customer c JOIN c.orders o
WHERE o.count > 100
Run Code Online (Sandbox Code Playgroud)


原文链接:https://qa.1r1g.com/sf/ask/3033208321/