javahibernateone-to-one

Hibernate 5: OneToOne without @Id


I have class Products which has:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "products_seq")
@SequenceGenerator(name = "products_seq", sequenceName = "products_seq", allocationSize = 1)
@Column(name = "PRODUCT_ID")
protected Integer productId;

it also has: private Attributes attributes; which should be joined @OneToOne to Attributes class;

Problem is that Attributes doesn't contain it's own id. It's table with two columns ATTRIBUTE_ID and DATE. Unfortunately ATTRIBUTE_ID is not generated id but just the same as product_id from Products class.

I tried to add in Products class:

@OneToOne(mappedBy = "product", cascade = CascadeType.PERSIST)
private Attributes attributes;

and in Attributes class:

@Id
@GeneratedValue(generator = "foreign")
@GenericGenerator(name = "foreign", strategy = "foreign", parameters = @Parameter(name = "property", value = "product"))
@Column(name = "ATTRIBUTE_ID")
private Integer attributeId;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "attribute_id")
private Product product;

but I don't think it's correct solution. I believe ATTRIBUTES table should have also id but it would be hard to achive this now. Is there a proper way to handle this strange situation?


Solution

  • I believe using primary key from parent in a one-to-one or one-to-zero is an often used approach.

    In your case, Attributes may look like this:

    @Entity
    public class Attributes {
    
        @Id
        @Column(name = "ATTRIBUTE_ID")
        private Long id;
    
        @OneToOne
        @MapsId // establish shared primary key relationship
        @JoinColumn(name = "ATTRIBUTE_ID")
        private Product product;