1.前提:有两张表Contract 和 Customer
Contract 表中根据CUSTOMER_ID关联查询到Customer对象
@Entity
@Table(name = "CONTRACT")
public class Contract implements Serializable{
.............................
/**
* customer
*/
@ManyToOne
@JoinColumn(name = "CUSTOMER_ID")
private Customer customer;
.............................
}
@Entity
@Table(name = "CUSTOMER")
public class Customer implements Serializable {
.............................
/** birthplace */
@Column(name = "BIRTHPLACE")
private String birthplace;
/** status */
@Column(name = "STATUS")
private String status;
.............................
}
2.查询Contract的Dao
1)Criteria criteria = this.getSession().createCriteria(this.getPersistentClass());
2)传递参数
Map<String, Object> params = new HashMap<String,String>();
params.put("customer.status", "Y");
params.put("customer.birthplace", "BeiJing");
params.put("currentPage",2);//第几页
params.put("numberOfPerPage",20);//每页显示条数
3)解析参数构造criteria
Map<String, Criteria> aliasList = new HashMap<String, Criteria>();
for (String key : params.keySet()) {
Object value = params.get(key);
// Ignore case for String
if (value instanceof String) {
...................................................................
if (key.indexOf(".") > 0) {
String alias = key.substring(0, key.indexOf("."));
if (!aliasList.containsKey(alias)) {
aliasList.put(alias, criteria.createCriteria(alias));
}
String aliasKey = key.substring(key.indexOf(".") + 1, key.length());
aliasList.get(alias).add(Restrictions.eq(aliasKey, ((String) value).trim()).ignoreCase());
} else {
criteria.add(Restrictions.eq(key, ((String) value).trim()).ignoreCase());
}
...................................................................
}else{
criteria.add(Restrictions.eq(key, value));
}
}
4)分页构造 criteria
int startIndex = ((Integer)params.get("currentPage") - 1) * (Integer)params.get("numberOfPerPage");
criteria.setFirstResult(startIndex);
criteria.setMaxResults((Integer)params.get("numberOfPerPage"));