1
votes

Will my code work if I apply one-to-many relation in hibernate- only to entities side in Java and not to DB side (there will not be foreign key between tables and I don't want to modify tables) ?

Question edited below.

Here are my tables - One employee has many certificates

Emp table -->

   id (Primary key)

   first_name

   last_name

   salary

   emp_id

Certificates Table -->

   id (primary key)

   certificate_name 

   cert_id

Here , these tables data are related with emp_id and cert_id.(There is no relation in tables for this. But looking at data in existing system they are related)

As it is an existing DB , I don't want to change tables and add foreign key relation in DB. And I want to add relation from hibernate side only. Is it possible. ?

3
Please, add your entities.v.ladynev

3 Answers

0
votes

First, Hibernate does not need a ForeignKey relation on the Database side. If you have hbm2ddl turned off, hibernate will not create one.

Just declare it as a normal one-to-many relation and hibernate will make a collection of certs for an employee. Be sure to use Set or Bag not List since List needs an index column.

0
votes

Try referring to the id field only instead of the entity in your certificates entity. Your employee entity will remain the same but without the @OneToMany relation. In your certificate entity instead of doing:

@ManyToOne
@JoinColumn(name="EMPLOYEE_ID")
Employee employee

Do it like:

@Column(name="EMPLOYEE_ID")
Integer employeeId;
0
votes

If the primary keys are the same, this is officially and purely a one-to-one relation which can be mapped as such. There is nothing you need additionally in the database.