我有以下完美運(yùn)行的 MS SQL 查詢。select u.id, u.username, r2.authority, em.hrt02_first_name, em.hrt02_last_name from users as u inner join group_members gm on u.id = gm.user_id inner join groups g on gm.group_id = g.id inner join group_authorities ga on ga.group_id = g.id inner join roles r2 on ga.role_id = r2.id inner join hrt02_employee_name em on em.id = u.idwhere u.username = 'john'輸出如下+----+----------+------------+------------------+-----------------+| id | username | authority | hrt02_first_name | hrt02_last_name |+----+----------+------------+------------------+-----------------+| 1 | john | ROLE_ADMIN | fname | lname |+----+----------+------------+------------------+-----------------+| 1 | john | ROLE_USER | fname | lname |+----+----------+------------+------------------+-----------------+但是當(dāng)我試圖將它轉(zhuǎn)換為 Hibernate Query 或 `@Query(..., nativeQuery=true) 時(shí),它會(huì)拋出異常。(未能進(jìn)行延遲初始化和加入所需的路徑)。這是我的模式設(shè)計(jì)@Entitypublic class Users { // id, username omitted @ManyToMany @JoinTable(name="group_members", joinColumns=@JoinColumn(name="user_id", referencedColumnName="id"), inverseJoinColumns=@JoinColumn(name="group_id", referencedColumnName="id")) private List<Groups> groups;}@Entitypublic class Groups { // id omitted @ManyToMany @JoinTable(name="group_authorities", joinColumns=@JoinColumn(name="group_id", referencedColumnName="id"), inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id")) private List<Roles> roles;}@Entitypublic class Roles { // id omitted, authority}@Entitypublic class Hrt02EmployeeName { // id, firstname, lastname omitted}
1 回答

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
由于您想將其轉(zhuǎn)換為User,因此您必須構(gòu)建它,而不是u.username, r2.authority. 其次,您需要獲取您正在使用的內(nèi)容以避免LazyInitializationException:
@Query("select distinct u from Users u " +
" left join fetch u.groups g "
" left join fetch g.roles r " +
" ... "
" where u.username = :username")
public Users findRoleByUsername(@Param("username") String username);
這是開始,因?yàn)槟膶?shí)體Role沒有映射。您將不得不以與點(diǎn)所在的其他實(shí)體相同的方式編寫。
添加回答
舉報(bào)
0/150
提交
取消