Home > database >  Composite Primary Key and @OneToOne JPA - Hibernate
Composite Primary Key and @OneToOne JPA - Hibernate

Time:08-09

My entities are as follows

Office

@Entity
public class Office {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private int latitude;
    private int longitude;
    private String buildingName;
    // getters and setters omitted for brevity
}

Point - which is an EmbeddedId

@Embeddable
public class Point implements Serializable {

    private int latitude;
    private int longitude;
    // getters and setters omitted for brevity
}

Location

@Entity
public class Location {

    @EmbeddedId
    private Point point;
    private String country;

    @OneToOne // How to add a OneToOne Mapping
    private Office office;
    // getters and setters omitted for brevity
}

Question: I want to add a one-to-one mapping between the Office and the Location entity.

What I've tried: I added the following annotations along with @OneToOne mapping in the Location entity

@JoinColumn(name = "latitude", referencedColumnName = "latitude")
@JoinColumn(name = "longitude", referencedColumnName = "longitude")

but I got the following error

Provided id of the wrong type for class com.example.demo.entity.employee.o2m_cpk.Office. Expected: class java.lang.Integer, got class com.example.demo.entity.employee.o2m_cpk.Point

CodePudding user response:

Use the following mappings:

@Entity
public class Office {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @OneToOne
    private Location location;
    private String buildingName;
}

@Embeddable
public class Point implements Serializable {

    private int latitude;
    private int longitude;
}

@Entity
public class Location {

    @EmbeddedId
    private Point point;
    private String country;

    @OneToOne(mappedBy = "location")
    private Office office;
}
  • Related