javaspringhibernateone-to-onemany-to-one

Change the relationship from @ManyToOne to @OneToOne


Is there a need to change the relationship from @ManyToOne to @OneToOne?

I mistakenly defined relation @ManyToOne instead of relation @OneToOne in my code

My classes in brief :

Class dev:

.
.
private long id;
private Com com;
.
.
@ManyToOne
@JoinColumn(name="S_COM_ID")
Public Com getCom(){
return com;}
.
.

class com:

private long id;
private String name;
.

After checking the database, I understood that the information is registered correctly. Do I need to change the relationship to @OneToOne or not?


Solution

  • Just looking at the Java code provides me with no information about how the Database is set up.

    Assuming the database is set up in the following way:

    Technically from a database standpoint multiple entries in Dev can reference a id in Com. Nothing in the database prevents them from doing so.

    If you expect this, then I would suggest not changing the ManyToOne annotation, because in code and database it can happen, that multiple instances of the java class dev will result in the same (read ==, not Object.equals) java com object.

    If you do not expect this, then I would suggest changing your database structure to make it impossible for multiple entries in the Dev table to reference a single Com entry. The only way I would know to achieve this is to just move the name column from the Com table into the Dev table.