【问题标题】:@Constructorresult with self join class mapping@Constructorresult 与自联接类映射
【发布时间】:2026-01-15 18:25:01
【问题描述】:

谁能解释一下如何为使用自联接类的场景编写注释。

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

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

【问题讨论】:

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


    【解决方案1】:

    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...
    }
    

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

    @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 而不是ComplexObject

    【讨论】:

    • 感谢您的示例,但我正在寻找 ComplexObject 包含 ComplexObject 类型的属性的场景
    • 只要它在您的数据库中有一个表示,您拥有什么样的对象没有任何区别。如果您的ComplexObject 包含ComplexObject,您将只能检索其ID,因为您要使用ConstructorResultNamedNativeQuery