HQL多表查询
这里使用 多对多关系的用户表(user)和角色表(role)举例。
对应的实体类
User.java
public class User {
private int uid;
private String uname;
private int uage;
private String usex;
private Set<Role> roleSet=new HashSet<>();
public Set<Role> getRoleSet() {
return roleSet;
}
public void setRoleSet(Set<Role> roleSet) {
this.roleSet = roleSet;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUage() {
return uage;
}
public void setUage(int uage) {
this.uage = uage;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
}
Role.java
public class Role {
private int rid;
private String rname;
private int authority;
private Set<User> userSet=new HashSet<User>();
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public int getAuthority() {
return authority;
}
public void setAuthority(int authority) {
this.authority = authority;
}
public Set<User> getUserSet() {
return userSet;
}
public void setUserSet(Set<User> userSet) {
this.userSet = userSet;
}
}
内连接
Query query=session.createQuery(“from User u inner join u.role”);
List<User> list=query.list();
返回的结果是数组
迫切内连接
Query query=session.createQuery(“from User u inner join fetch u.role”);
List<User> list=query.list();
返回的结果是对象
左外连接
Query query=session.createQuery(“from User u left outer join u.role”);
List<User> list=query.list();