gschambial
gschambial

Reputation: 1391

PersistenceException while trying to cascade persist child entity

I have 2 entities:

Master:

@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "seq")
    private Integer seq;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "seq", referencedColumnName = "seq")
    private SubMaster subMaster;


    ...................

}

Sub Master:

@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {

    @Id
    @Column(name = "seq")
    private Integer seq;

    private String subName;


    ...................

}

When, I am trying to persist Master entity by setting the SubMaster entity, I am getting following exception:

javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save(): SubMaster

Whereas, I am expecting that Hibernate it will automatically persist child entity whenever parent entity is persisted.

Upvotes: 1

Views: 162

Answers (2)

Zeromus
Zeromus

Reputation: 4542

First of all you inverted the owner of the association as i believe subMaster should have the @JoinColumn annotation.

now for the solution

Depends on JPA version:

-2.0 you can define @Id annotation on relation annotation so you could have something like

@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "seq")
    private Integer seq;

    @OneToOne(mappedBy = "master", cascade = CascadeType.ALL)
    private SubMaster subMaster;

}

@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {

    @Id
    @JoinColumn(name = "seq", referencedColumnName = "seq")
    @OneToOne
    private Master master;

    private String subName;

}

where you tell your child entity to take the id of the parent

master.setSubMaster(subMaster);
subMaster.setMaster(master)

-1.0 you are pretty much stuck as you are forced to place @Id on a basic annotation so you need to have an id and a relation column separated, the problem is that with @GeneratedValue you are forced to first save the parent and then manually set the id to the child before saving

ref: https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships

Upvotes: 2

alexay68
alexay68

Reputation: 172

add @GeneratedValue(strategy = IDENTITY) for SubMaster as well, seems like it's SubMaster's id that generated the exception

Upvotes: 2

Related Questions