Search code examples
hibernatejpaspring-data-jpaentity-relationship

Sprind Data JPA OneToOne and ManyToOne Relations


I have 2 entity named Machine and MachineType. Machine can have only one MachineType but MachineType can have more than one or none Machine. I try tons of relation annotation but I miss something.

Machine

@Entity
public class Machine {

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "machine_id")
private Long machineId;

@OneToOne(???)
private MachineType machineType;

@Column(name = "machine_name")
private String MachineName;

//getters and setters
}

MachineType

@Entity
public class MachineType {

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long machineTypeId;

@ManyToOne(???)
private List<Machine> machines;

@Column(name = "machine_type_name")
private String machineTypeName;

//getters and setters
}

I dont understand mappedBy and @JoinColumn correctly and I stuck right now. When should I use them?


Solution

  • I dont understand mappedBy and @JoinColumn correctly and I stuck right now.

    mappedBy = relationship field or property of the entity that is the owner of the relationship. In this example, this is the field machineType annotated by @ManyToOne annotation.

    @JoinColumn = the name of the foreign key column in the database. This means when you define the tables, for example, MACHINE and MACHINE_TYPE, you add the primary key of the MACHINE_TYPE table into the MACHINE and thereby creating a relationship between the tables. This field is called foreign key, because it is pointing to another record in another table in the database. The name of this column is specified in through this annotation.

    Note: the mappedBy element is needed only if you want a bidirectional relationship. Otherwise, it is not required.

    @Entity
    public class Machine {
    
        @Id
        @GeneratedValue
        @Column(name = "machine_id")
        private Long machineId;
    
        @ManyToOne
        @JoinColumn(name="name_of_foreignkey")
        private MachineType machineType;
    
        @Column(name = "machine_name")
        private String MachineName;
    
       //getters and setters
    }
    
    @Entity
    public class MachineType {
    
        @Id
        @GeneratedValue
        private Long machineTypeId;
    
        @OneToMany(mappedBy="machineType")
        private List<Machine> machines;
    
        @Column(name = "machine_type_name")
        private String machineTypeName;
    
        //getters and setters
     }
    

    I removed strategy = GenerationType.TABLE from the GeneratedValue annotation because it will not work as you specified. If you want to use a table generator (which is the recommended way of generating primary key) you must do more than just specifying as you did.