Hibernate, Spring Data, insert id of table parent on table child

I'm trying insert the id of Person in child table 'Contact'. But the Hibernate stores the value null at fk column.

I perform the mapping of a DTO to the entity, where it already brings the person's data and contact. In the end I have to save the person entity.

There is a table inheritance!

Parent table:

@Entity
@Table
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, columnDefinition = "CHAR(2)", length = 2)
public abstract class Person implements Serializable {

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "person")
    @Cascade(value={org.hibernate.annotations.CascadeType.ALL})
    private @Getter @Setter Set<Contact> contacts;

}

Table Company extends of Person:

@Entity
@Table
@DiscriminatorValue(value="PJ")
public class Company extends Person implements Serializable {

    @Column(nullable = false, columnDefinition = "DATE")
    private @Getter @Setter LocalDate constitutionDate;

}

And where is the problem!

@Entity
@Table(name = "contact")
@EqualsAndHashCode
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private @Getter Integer id;

    @Column(columnDefinition = "VARCHAR(16)", length = 16, nullable = false)
    private @Getter @Setter String phoneNumber;

    @ManyToOne(fetch = FetchType.LAZY, optional = false,targetEntity=Person.class)
    @JoinColumn(name = "person_id", nullable = false, referencedColumnName="id")
    private @Getter @Setter Person person;

    public Contact() {}

    public Contact(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

What am I doing wrong? What's the best strategy?

Excuse me for my poor English!

1 answer

  • answered 2018-01-16 19:09 jfneis

    Can't find nothing obvious that's wrong but let me try some things:

    1. Your cascade annotation on Person class doesn't need the specific Hibernate enumeration You can use like :

    @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, mappedBy = "cliente")
    
    1. In your ManyToOne annotation on Contact class please try to add:

    @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    

    BTW, an inheritance relationship between Person and Company doesn't seem logic to me, but that has nothing to do with your stated problem for sure.