我有以下架构:
TABLE EMPLOYEE TABLE COUNTRY
--------------- ---------------
id |------> id
name | country_name
country_id ------| country_code
如果我想要检索属于某个国家/地区的所有员工,请使用以下标准:
Criteria crit = getSession().createCriteria(Employee.class);
crit.add(Restrictions.eq("country.id", countryId));
List<Employee> employees = crit.list();
我的员工实体以这种方式引用国家:
@Entity
public class Employee {
private static final long serialVersionUID = 1L;
@Id
private Integer id;
@ManyToOne
@JoinColumn(name="country_id")
private Country country;
// Other stuff here
}
这里的一切都很好!
问题是如果我不知道countryId,但我改为使用country_code(例如“UK”)。我应该如何更改上面的条件,以便我可以加入表格并在国家/地区代码上添加限制?
答案 0 :(得分:0)
Criteria criteria = getSession().createCriteria(Employee.class,"e");
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.createAlias("e.country", "c");
Criterion codeId= Restrictions.eq("c.id", yourCountryId);
Criterion codeCriterion= Restrictions.eq("c.countryCode", yourCountryCode);
criteria.add(Restrictions.or(codeId, codeCriterion));
List<Employee> employees = criteria.list();
或强>
Criteria criteria = getSession().createCriteria(Employee.class);
Criterion codeId = Restrictions.eq("country.id", yourCountryId);
Criterion codeCriterion = Restrictions.eq("country.countryCode", yourCountryCode);
criteria.add(Restrictions.or(codeId, codeCriterion));
List<Employee> employees = crit.list()
答案 1 :(得分:0)
你可以这样做,简单地添加if else
Criteria crit = getSession().createCriteria(Employee.class);
if(StringUtils.isNotBlank(countryId))
crit.add(Restrictions.eq("country.id", countryId));
else
crit.add(Restrictions.eq("country.code", countryCode));
List<Employee> employees = crit.list();