避免在@onetomany join中不必要的提取

时间:2013-12-10 11:12:30

标签: java spring hibernate postgresql

我有两个类映射到DB中的两个不同的表。 例如,

    @Entity
    @Table(schema = "schema", name = "tableA")
    public class ClassA{

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger id;

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

    @Column(name="first_name")
    private String firstName;

    @Column(name="middle_name")
    private String middleName;

    @Column(name="last_name")
    private String lastName;

        @Column(name ="updater")
        private BigInteger updaterId;

        @OneToOne(targetEntity=UserBean.class, fetch=FetchType.EAGER)
    @JoinColumn(name="updated_by",referencedColumnName="employee_number",insertable=false ,updatable=false)
    private User updatedDetails;  

 //getter setter
}

我有User类如下

@Entity
    @Table(schema = "schema", name = "User")
    public class User{

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger id;

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

    @Column(name="first_name")
    private String firstName;

    @Column(name="middle_name")
    private String middleName;

    @Column(name="last_name")
    private String lastName;

    //getter setters }

现在当我通过(“From ClassA”)获取ClassA对象时,我也得到了相应的User类对象。现在我的问题是如何忽略User类的不必要属性。

例如,我想忽略User类的middleName和lastName属性。我必须限制Hibernate在加入时读取这两列。我该怎么做?

我正在使用Spring + Hibernate。

1 个答案:

答案 0 :(得分:1)

只需将以下行改为懒惰加载实体

@OneToOne(targetEntity=UserBean.class, fetch=FetchType.EAGER)

@OneToOne(targetEntity=UserBean.class, fetch=FetchType.LAZY)

并阅读FetchType.EAGER VS FetchType.LAZY

如果你想加载一个实体Lazily的字段,你可以在你想要加载的字段上使用@Basic(fetch=FetchType.LAZY)注释。

 @Basic(fetch=FetchType.LAZY)
    @Column(name="first_name")
    private String firstName;