0
我有用戶和userRole表與多對多的關係。我有以下Hibernate映射:休眠(使用Spring)查詢與多對多
<hibernate-mapping>
<class name="domain.User" schema="dbo" table="Users">
<id name="userId" type="int">
<column name="UserId"/>
<generator class="native"/>
</id>
<property name="username" type="string">
<column name="Username" not-null="true"/>
</property>
<property name="password" type="string">
<column name="Password" not-null="true"/>
</property>
<set cascade="all" inverse="true" name="userRole" table="UserRoleRelationships">
<key>
<column name="UserId"/>
</key>
<many-to-many class="domain.UserRole" column="RoleId" />
</set>
</class>
</hibernate-mapping>
和:
<hibernate-mapping>
<class name="domain.UserRole" schema="dbo" table="UserRoles">
<id name="roleId" type="int">
<column name="RoleId"/>
<generator class="native"/>
</id>
<property name="role" type="string">
<column name="Role" not-null="true"/>
</property>
</class>
</hibernate-mapping>
我的豆樣子:
public class User {
private Integer userId;
private String username;
private String password;
private Set<UserRole> userRole;
// getters and setters
}
public class UserRole {
private Integer roleId;
private String role;
private User user;
// getters and setters
}
供其用戶名選擇用戶的查詢看起來像:
public List<User> getWithUsername(String username){
return getHibernateTemplate().find("from User as u "
+ "inner join fetch u.userRole "
+ "where u.username = '" + username + "'");
}
問題是臨時當我嘗試噸至與下面的循環(一個或多個)打印出來:
for (User u : list){
System.out.println(u.getUsername());
for (UserRole ur : u.getUserRole()){
System.out.println(ur.getRole());
}
}
它打印出它加倍:
Username: jorgen
User role: User
User role: Admin
Username: jorgen
User role: User
User role: Admin
我在做什麼錯?請幫助:)
謝謝回答。你有代碼示例顯示如何使用DistinctRootEntityProjection執行此操作嗎? – jorgen