3

I'm trying to make a composite primary key mapping and doesn't work.

The requisites are:

  • The relation may be with @IdClass annotation
  • I need the relationship with person entity be @ManyToOne

My code:

@Entity
@IdClass(PhonePK.class)
public class Phone implements Serializable{
    @Id
    @Column(name = "codigo", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long code;

    @Id
    @ManyToOne
    @JoinColumn(name = "person", referencedColumnName = "code", nullable = false)
    private Person person;

    @Basic
    @Column(name = "number", nullable = false)
    private Integer number;

    //getters and setters
    //equals and hashcode
}

public class PhonePK implements Serializable {
    private Long code;
    private Long person;

    public PhonePK(){}

    public PhonePK(Long code, Long person) {
        this.code = code;
        this.person = person;
    }

    //getters and setters
    //equals and hashcode
}

public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "code", nullable = false)
    private Long code;

    //getters and setters
    //equals and hashcode
}

They way I'm trying to persist:

//a lot of code
//em = Entitymanager
em.persist(person);
phone.setPerson(person);
em.persist(phone);

The error that I'm receiving is:

Caused by: javax.persistence.PersistenceException: org.hibernate.HibernateException: No part of a composite identifier may be null

Lucas
  • 1,251
  • 4
  • 16
  • 34

2 Answers2

1

There is a high chance that the Person you are setting on the Phone entity doesn't have and ID yet. Persist doesn't garante and ID. It is recommended you also flush the transaction.

Related: ID not added on persis()

Community
  • 1
  • 1
alambrache
  • 108
  • 1
  • 9
  • I flushed and getting the error too.... I'm not setting the ID in phone cause is Generated... but can I use generated in composite? – Lucas Feb 21 '16 at 04:17
-2

I found an issue in hibernate.atlassian. I gave up the composite key and just put a foreign key from Person in Phone.

Lucas
  • 1,251
  • 4
  • 16
  • 34
  • 1
    I would have been helpful to show an example of how you did the mapping differently to solve this issue. – Melissa Jan 22 '20 at 07:21