我有一种情况,当我想要一对多时,懒惰加载没有发生。 显然,我是新手。当我调用s.getSongComposers()时,为什么不能获取SongComposers?
这是我的DAO课程:
public class SongDAOImpl implements SongDAO {
@PersistenceContext
private EntityManager em;
@Override
@SuppressWarnings(value = { "unchecked" })
public List<Song> getAllSongsOnAlbum(int albumID) {
Query q = em.createQuery("SELECT s FROM Song s WHERE s.album.albumID = :albumid ORDER BY s.songName");
q.setParameter("albumid", albumID);
List<Song> list = (List<Song>) q.getResultList();
for (Song s: list) {
s.getSongComposers();
}
return list;
}
}
这是我的歌曲实体:
@Entity
@Table(name="songs")
public class Song {
@Id
@GeneratedValue
@Column(name="SongID")
private int songID;
@Column(name="SongName")
private String songName;
@Column(name="Length")
private int length;
@ManyToOne
@JoinColumn(name="AlbumID", referencedColumnName="AlbumID")
private Album album;
@OneToMany(mappedBy="song")
private List<SongComposer> songComposers;
.... all getters/setters ......
}
这是我的SongComposer实体:
@Entity
@Table(name="song_composer")
public class SongComposer {
@Id
@GeneratedValue
@Column(name="SongComposerID")
private int songComposerID;
@ManyToOne
@JoinColumn(name="SongID", referencedColumnName="SongID")
private Song song;
@ManyToOne
@JoinColumn(name="ComposerID", referencedColumnName="ComposerID")
private Composer composer;
..... getters/setters .......
}
答案 0 :(得分:1)
你必须明确地这样做。试试这个问题:
SELECT DISTINCT s FROM Song s JOIN FETCH s.songComposers WHERE s.album.albumID = :albumid ORDER BY s.songName"