Java 加入的条件很好。。。但是如果我想添加一个条件?
我有以下模式:Java 加入的条件很好。。。但是如果我想添加一个条件?,java,hibernate,Java,Hibernate,我有以下模式: TABLE EMPLOYEE TABLE COUNTRY --------------- --------------- id |------> id name | country_name country_id ------| country_code 如果我想检索属于某个国家的所有员工,我会使用如下标准: Criteria crit = g
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();
这里一切都很好
问题是如果我不知道countryId,但我有国家代码(例如“UK”)。我应该如何更改上述标准,以便加入表并添加对国家/地区代码的限制?criteria criteria=getSession().createCriteria(Employee.class,“e”);
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.setResultTransformer(criteria.DISTINCT\u ROOT\u实体);
标准。createAlias(“e.country”、“c”);
标准代码id=Restrictions.eq(“c.id”,yourCountryId);
Criteria codeCriterion=Restrictions.eq(“c.countryCode”,yourCountryCode);
添加(限制或(代码ID、代码标准));
List 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()
Criteria=getSession().createCriteria(Employee.class);
标准代码id=Restrictions.eq(“country.id”,yourCountryId);
Criteria codeCriterion=Restrictions.eq(“country.countryCode”,yourCountryCode);
添加(限制或(代码ID、代码标准));
List employees=crit.List()
您可以通过这种方式来完成,否则只需简单地添加即可
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();
Criteria crit=getSession().createCriteria(Employee.class);
if(StringUtils.isNotBlank(countryId))
标准添加(限制条件(country.id,countryId));
其他的
标准添加(限制条件(“国家代码”,国家代码));
List employees=crit.List();
您可以在值上使用if-else(即如果为空),并根据条件的结果在块中包含crit.add(Restrictions.eq(“country.id”,countryId))。
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();