@MapsId Hibernate error: attempted to assign id from null one-to-one property

Viewed 100

I have some entities (i've left out getters/setters, and some other fields):

@Entity
public class Platform {

    @Id
    @GeneratedValue
    private UUID id;

    @OneToMany(mappedBy = "platform", cascade = CascadeType.ALL)
    List<PlatformDq> platformDqs = new ArrayList<PlatformDq>();
}

@Entity
public class PlatformDq {
    
    @EmbeddedId
    private PlatformDqId platformDqId;

    @ManyToOne
    @MapsId("platformId")
    @JoinColumn(name = "id")
    private Platform platform;

}

@Embeddable
public class PlatformDqId {
    
    @Column(name = "platform_id")
    private UUID platformId;
    
    @Column(name = "dq")
    private String dq;
}

This composite primary key is platform_id and dq columns. platform_id is also a foreign key.

I want the PlatformDq's platform_id to be generated the same time as the Platform's id. That is, when I create a new Platform with some PlatformDqs, the composite key platform_id should have the same id as id on Platform, and the dq field is set to some value.

When I try and do it this way, hibernate tells me:

attempted to assign id from null one-to-one property

1 Answers

Just looking at the error it seems that Platform entity part of PlatformDq is not initialized.

Try setting the following as that will explicitly tell jpa of the relationship and further what value to populate for the platform id.

Platform p = new Platform();
//Required Setters

//for each PlatformDq
PlatformDq dq = new Platform();
//Setters
dq.setPlatform(p); 
Related