2

Well, I am new to Hibernate and the question I have is quite trivial. I found few answers explaining it but may be I am not getting it exactly and I am still stuck.

I found that to map a foreign key I need to map an entity, like below

// this is GroupEntity
// mapping bond_id from Bond table
   @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name ="bond_id")
    private BondEntity bondEntity;

I believe this maps bond_id column from BondEntity's table to bond_id of present table.

Now how do I set this bond_id to DB while persisting the entity of this table. Unlike other columns this field now takes an object.

I tried setting only the bond_id, like

BondEntity bondEntity = new BondEntity();
bondEntity.setBondId(1234); //remaining field of bondEntity not set
groupEntity.setBondEntity(bondEntity);

If I go ahead and try persisting this entity, I get detached entity passed to persist in hibernate.

Whats the correct way of doing it. May be I am not getting it correctly.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82
  • Please share the code for both entities you are trying to map together. Annotation `@JoinColumn` is not used with `@OneToMany`. See [JPA JoinColumn vs mappedBy](https://stackoverflow.com/questions/11938253/jpa-joincolumn-vs-mappedby) – pirho Dec 04 '17 at 18:43
  • 1
    You do not specify `@OneToMany` on a single-valued entity field! That would be `@OneToOne` (or `@ManyToOne`). –  Dec 04 '17 at 18:48
  • @pirho `@JoinColumn` is used with `@OneToMany` in Hibernate. – v.ladynev Dec 04 '17 at 19:35
  • @v.ladynev Thanks for correcting. Then it is not `JPA`. – pirho Dec 04 '17 at 19:37

2 Answers2

1

This is incorrect

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name ="bond_id")
private BondEntity bondEntity;

Perhaps you want to use

@ManyToOne
@JoinColumn(name ="bond_id")
private BondEntity bondEntity;

Please, read this

what is @JoinColumn and how it is used in Hibernate

This should work. Maybe you are using it in the incorrect place

BondEntity bondEntity = new BondEntity();
bondEntity.setBondId(1234); //remaining field of bondEntity not set
groupEntity.setBondEntity(bondEntity);

You can try to use session.load() in place of above.

v.ladynev
  • 19,275
  • 8
  • 46
  • 67
1

Scenario1:

In case your bond Id already exists in the session,you need to fetch the persisted object from the session such as BondEntity bondEntity = session.get(BondEntity.class,1234);

Now you can pass this persisted object to groupEntity.setBondEntity(bondEntity);

Scenario 2:

In case you need to save new bond id and create corresponding entry in group table.

Create an instance of BondEntity ,set the required fields and call save or saveOrUpdate to persist the entity in session,then set the value in group entity,hibernate would take care of the rest based on the relationship between both the tables.

Ramandeep Kaur
  • 111
  • 1
  • 9