具有自连接类映射的@Constructorresult

时间:2018-06-25 15:38:10

标签: spring-boot jpa spring-data-jpa

有人可以解释一下在使用自连接类的情况下如何对注释进行编码。

在我的场景中,我使用的是本机查询,我需要传递一些输入。

对于SQL结果映射,我使用@constructorresult。但不确定如何根据特定列配置自类联接

1 个答案:

答案 0 :(得分:0)

具有ConstructorResult的示例

假设我们有一个非常复杂的实体ComplexObject,它与其他对象有许多关系。

@Entity
@Table(name = "complex_object")
public class ComplexObject {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_complex_object")
    private Integer id;

    @Column(name = "label")
    private String label;

    // More relations...

}

我希望查询仅检索该实体的ID和标签。

ComplexObject中,我定义了一个新的NamedNativeQuery,如下所示。

@NamedNativeQueries({
        @NamedNativeQuery(name = "ComplexObject.getIdAndLabel", query = "SELECT co.id_complex_object, co.label FROM complex_object", resultSetMapping = "SimpleObject")
})

NamedNativeQuery的重要部分是resultSetMapping = "SimpleObject"

然后,我可以定义一个非实体的SimpleObject并匹配我的查询,如下所示:

public class SimpleObject {

    private Integer id;
    private String label;

    /**
     * This constructor is very important !
     * Its signature has to match the SqlResultSetMapping defined in the entity class.
     * Otherwise, an exception will occur.
     */
    public SimpleObject(Integer id, String label) {
        this.id = id;
        this.label = label;
    }

    // Getters and setters...
}

然后我可以在SqlResultSetMapping中定义ComplexObject,如下所示:

@SqlResultSetMappings({
    @SqlResultSetMapping(name = "SimpleObject", classes = {
        @ConstructorResult(targetClass = SimpleObject.class, columns = {
            @ColumnResult(name = "id_complex_object", type = Integer.class),
            @ColumnResult(name = "label", type = String.class)
        })
    })
})

完成了。

NamedNativeQuery将使用SimpleObject SqlResultSetMapping来构造SimpleObject(贯穿构造函数),因此您的查询将返回SimpleObject而不是{{1} }。

相关问题