Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Something 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?

like image 622
Dongin Min Avatar asked Aug 26 '15 07:08

Dongin Min


People also ask

What is many-to-one relationship in hibernate?

A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example, the same address object can be associated with multiple employee objects.

What is join column in hibernate?

Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

How do I persist foreign key in JPA?

Use the getReference call of the entityManager to load customer object using the id and then set that onto the customer history. In most cases this call would return a proxy with just the id embedded, the customer attributes will not be loaded unless some other method of the customer is invoked.


2 Answers

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

like image 158
Dragan Bozanovic Avatar answered Sep 28 '22 08:09

Dragan Bozanovic


You can define two fields in B, one representing the relationship, and the other just the column:

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

  @Column(name="b_id", updatable=false,insertable=false) //Or correct column
  private int a_id;

This way you can access entity A or just A's id from entity B.

like image 41
Fran Montero Avatar answered Sep 28 '22 07:09

Fran Montero