Search code examples
springhibernatejpa

Cannot insert NULL into a fields in OneTomany JPA entity


I have a OneToMany JPA entity association. My association in parent class is

@OneToMany(targetEntity = Extensions.class, cascade = CascadeType.ALL)
@JoinColumn(name = "EX_LOAN_ID",referencedColumnName = "LOAN_ID")
private List<Extensions> extensions;

Child Class
public class Extensions implements Serializable {
@Id
@Column(name = "EX_LOAN_ID")
private Long exLoanId;
@Id
@Column(name = "EX_NO")
private Long exNo;
@Column(name = "EX_EXTENSION_DAYS")
private Long exExtensionDays;

I am calling 
repository.saveAndFlush(next); 

The next object have all values but i am getting hibernate error message saying cannot insert null into EX_LOAN_ID


Solution

  • We do not recommend the use of unidirectional @OneToMany associations.

    I believe that if you change this to a regular bidirectional @ManyToOne/@OneToMany, this problem will be resolved.

    UPDATE

    For example, I believe the following mapping would work for you:

    @Entity
    static class Loan {
        @Id
        @Column(name = "LOAN_ID")
        private Long id;
    
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "loan")
        private List<Extension> extensions = new ArrayList<>();
    }
    
    @Entity
    static class Extension {
        @Id
        @Column(name = "EX_LOAN_ID")
        private Long exLoanId;
    
        @Id
        @Column(name = "EX_NO")
        private Long exNo;
    
        @Column(name = "EX_EXTENSION_DAYS")
        private Long exExtensionDays;
    
        @ManyToOne
        @JoinColumn(name = "EX_LOAN_ID", 
                    insertable = false, updatable = false)
        private Loan loan;
    }