下面用最简单的Role和User来展现一个简单的hibernate多对多查询:
User: public class User implements Serializable{ private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Role: public class Role implements Serializable{ private Long id; private String roleName; private String descri; public String getDescri() { return descri; } public void setDescri(String descri) { this.descri = descri; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
关系表: public class UserRoleTemp implements Serializable{ private Long id; private User user; private Role role; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
查询:
String hql = "select ut.role from UserRoleTemp ut where ut.user.id = 2"; Session session = this.getSession(); Query q = session.createQuery(hql); List<Role> list = q.list(); for(Role r :list){ System.out.println(r.getRoleName()); }
查询结果:
yang gao
说明:中间省略了hbm映射及向表中添加信息的代码:
主要是想记录一下“select ut.role from UserRoleTemp ut where ut.user.id = 2”这条查询语句。
通过中间表的user的id,查询出了对应的role中的信息!由此可见,通过这种映射关系,查询起相应的信息来还是很方便的!