我有2张桌子
1.用户
2.公司
每个用户都有一个公司。对于每个公司,它可以有多个用户。
UserBean.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
@Table(name = "tab_user")
public class UserBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "user_id")
private int user_id;
@Column(name="user_login_pwd")
private String user_login_pwd;
@ManyToOne
@JoinColumn(name="comp_id")
private CompanyBean companyBean
我的CompanyBean是
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
@Table(name = "tab_company")
public class CompanyBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "comp_id")
private Integer comp_id;
@Column(name = "comp_code")
private String comp_code;
@OneToMany(mappedBy = "companyBean" , fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Fetch(value = FetchMode.SUBSELECT)
private List<UserBean> companyUserList;
这是我的CompanyBean映射类。
现在,我需要按“ comp_code”显示用户订单列表。我的DAO用户实现清单是
@SuppressWarnings("unchecked")
@Override
public List<UserBean> getUserList( String orderBy, String orderField) throws Exception{
List<UserBean> userList = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try{
Criteria crit = session.createCriteria(UserBean.class);
if(orderBy.equals("asc")){
crit.addOrder(Order.asc(orderField));
}else{
crit.addOrder(Order.desc(orderField));
}
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
userList = crit.list();
}finally{
session.close();
}
return userList;
}
那么如何在usersList中通过CompanyBean的comp_code获取订单?请帮忙。
最佳答案
没有Hibernate解决方案是创建自己的Comparator
并使用Collections.sort
进行订购。
休眠解决方案是使用@OrderBy
批注。
Using hibernate with annotations, i want a one-many relationship to be sorted
关于java - 通过Hibernate中的ManyToOne关系获取订单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20069173/