Home > Enterprise >  Column 'SINGER_ID' cannot be null in OneToMany relationship using Hibernate when trying to
Column 'SINGER_ID' cannot be null in OneToMany relationship using Hibernate when trying to

Time:10-31

I'm new with hibernate and i'm trying to insert a singer with his album but found that album entity does not see the singer id related to singer ..

Here are my entites:

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
@EntityListeners(SingerListener.class)
@Entity
@Table(name = "singer")
public class Singer  implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", nullable = false)
    Long id;

    @Column(name = "FIRST_NAME", nullable = false)
    private String firstName;

    @Column(name = "LAST_NAME", nullable = false)
    private String lastName;


    @Temporal(TemporalType.DATE)
    @Column(name = "BIRTH_DATE")
    Date birthDate;

    @Column(name = "VERSION")
    int version;

    @OneToMany(cascade = CascadeType.ALL,mappedBy = "singer")
    Set<Album> albums;



   /// setters and getters 
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
@EntityListeners(AlbumListener.class)
@Entity
@Table(name="album")
public class Album implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ID",nullable = false)
    Long id;

    @Column(name="TITLE")
    String title;

    @Override
    public String toString() {
        return "Album{"  
                "id="   id  
                ", title='"   title   '\''  
                ", realseDate="   realseDate  
                ", version="   version  
                ", singer="   singer  
                '}';
    }

    @Column(name="RELEASE_DATE")
    Date realseDate;

    @Column(name="VERSION")
    int version;

    @ManyToOne
    @JoinColumn(name="SINGER_ID")
    Singer singer;
    
    /// setters and getters 
    
}

My JSON request is :

{
    "firstName": "Sherif",
    "lastName":"Hawary",
    "birthDate":"1998-11-20",
    "version":0,
    "albums":
    [
        {
            "title":"Maa Aad Saghiran",
            "releaseDate":"2021-09-06",
            "version":0
        }
    ]

}

I think that i'm making a wrong JSON body but i'm not sure of that and i've read about CascadeType but i couldn't found a solution to help

CodePudding user response:

Add to Singer.java:

@PrePersist
public void assignAlbums() {
 for(var album : albums) {
   album.setSinger(this);
 }
}

I am facing the same issue and I think that you explicitely have to set the "mappedBy" property value on the linked entity (Album)

  • Related