Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

java - Just getting id column value not using join in hibernate object one to many relation

I'm using hibernate 4+.

I have two sample tables.

Table A

public class A {
  @Id
  private int id;

  @OneToMany(fetch=LAZY)
  private List<B> list;

  // skip getter&setter
}

Table B

public class B {
  @Id
  private int id;

  @ManyToOne(fetch=LAZY)
  @JoinColumn(name="b_id")
  private A a;

  // skip getter&setter
}

Table A(1) - (n)Table B Relation

Can I just get A's id in object B not using join?

like int aid = b.getA().getId(); // b is instance of B;

Although I can use int value instead of A when I declare class B. But another service layer use A with join.

Can I just get id(fk) value?

please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, because proxies contain the id anyway. To get the id of an A proxy without initializing it, first declare the id to be accessed via property:

@Entity
public class A {
  @Id
  @Access(AccessType.PROPERTY)
  private int id;

  @OneToMany(fetch=LAZY)
  private List<B> list;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }
}

Then, just read the id:

b.getA().getId();

Changing access type for the id is necessary because if you use field access, Hibernate does not distinguish getId() method from other ordinary methods (which trigger proxy initialization when invoked).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...