在Hibernate中无需查询即可获取JoinColumn id值

时间:2015-04-20 17:45:59

标签: java mysql hibernate orm relationship

@Entity
@Table(name="A")
public class A {

    private int id;

    //REST OF FIELDS...

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "B_ID", nullable = true)
    private B b;

    //GETTERS AND SETTERS...
}

@Entity
@Table(name="B")
public class B {

    private int id;
    //REST OF FIELDS...
    //GETTERS AND SETTERS...
}

当我想获得与A类对象相关的B类对象的id

//...GETTING A OBJECT FROM DATABASE
B b = a.getB();
if(b != null) {
    int bId = b.getId();
}

Hibernate对数据库进行查询并获取整个B对象,但我只需要在A表中的B_ID列中的id。

有没有办法在不进行额外查询的情况下获取B_ID?

1 个答案:

答案 0 :(得分:-1)

如果你添加

@Column(name = "B_ID", insertable = false, updatable = false)
private int b_id;

和一个吸气剂

public int getBId(){
    return b_id;
}

类似的东西至少对我有用:)