@Entity
public class Room {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "Room", fetch = FetchType.EAGER)
private List<SponsorStart> sponsorsStart = new ArrayList<>();
//getters setters
@Entity
@Table(name = "sponsors_start")
public class SponsorStart {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String username;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "room_id")
private Room Room;
@Repository
public interface RoomRepository extends CrudRepository<Room, Long> {
}
From RoomServiceImpl save:
@Override
public Room saveRoom(Room Room) {
return roomRepository.save(Room);
}
我的行为顺序是什么?
1. List<SponsorStart> sponsorStarts = new ArrayList<>();
2. Room room = new Room();
3. giveRoom.setSponsorsStart(sponsorStarts); //set list of sponsors form p.1
4. giveRoomService.saveRoom(room); //save room
sponsors_start_db为空。我尝试先保存每个sposorStart从列表中,但他们在room_id列中保存null。对不起,我知道这应该是简单的,但在我的情况下,我做错了。谢谢!
- 您应该将
cascade=CascadeType.ALL
移动到您的协会的@OneToMany
一侧:
@OneToMany(mappedBy = "Room", fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private List<SponsorStart> sponsorsStart = new ArrayList<>();
- 你应该同步双向关联的两边:
List<SponsorStart> sponsorStarts = new ArrayList<>();
SponsorStart sponsorStart1 = new SponsorStart();
sponsorStarts.add(sponsorStart1);
// ...
Room room = new Room();
// sync both side of the association
sponsorStart1.setRoom(room);
room.setSponsorsStart(sponsorStarts); //set list of sponsors form p.1
room.saveRoom(room); //save room
请参阅hibernate文档的这一部分。