0

我有以下架构:

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”)。我应该如何更改上述条件,以便我可以加入表格并添加对国家代码的限制?

4

2 回答 2

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()
于 2013-08-30T15:38:50.583 回答
0

You can do in this way, simple add 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();
于 2013-08-30T15:53:25.697 回答