Reputation: 1359
I’m using spring data and hibernate as JPA implementation with spring boot. I’m new to this. I have an entity where I’m maintaining the mapping between two entities which already exist and entries into this mapping only come in at the time of a specific update.
@Entity
@Table(name = "song_genres")
public class SongGenres {
public SongGenres(Song song, List<Genre> genres) {
this.genres = genres;
this.song = song;
}
public SongGenres() {
// Empty constructor as required by hibernate
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "song_id")
private Song song;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "genre_id")
private List<Genre> genres;
public List<Genre> getGenres() {
return genres;
}
}
I’m trying to insert all the genre values associated with a song at once, using
SongGenres songGenres = new SongGenres(song, genres);
songGenresRepository.save(songGenres);
but this is giving an error that
java.sql.SQLException: Field 'genre_id' doesn't have a default value
and the sql logs show a single row insert
Hibernate: insert into song_genres (song_id) values (?)
How is multiple row insert in one-to-many achieved without cascade?
Upvotes: 0
Views: 3088
Reputation: 7622
Just define CASCADE type for your List here "List genres" Add No of Items in list and persist main entity. You can read more about it here
Eg:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "visitId")
private Collection<SampleData> lstSampleData;
Upvotes: 0
Reputation: 1359
For now, I changed the entity definition since there isn't much difference between the two
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chapter_id")
private Chapter chapter;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "genre_id", nullable = false)
private Genre genre;
and the save operation becomes
List<ChapterGenre> chapterGenres = new ArrayList<>();
for (Genre genre : genres) {
chapterGenres.add(new ChapterGenre(chapter, genre));
}
chapterGenreRepository.save(chapterGenres);
From this one, concluded there isn't much of a difference from spring's implementation point of view.
Although this ain't best performance mysql-wise. Would be interesting if spring data comes up with a simple single insert API.
Upvotes: 0