Hibernate,Criteria.list()返回我期望的更多行

时间:2014-08-27 20:07:15

标签: java hibernate

我的spring和hibernate项目有问题:

在我的数据库(mysql)中,我有这些表:

table Operator{
     idOperator int(12) primary key auto_increment,
     name varchar(20),
     surname varchar(20),
     username varchar(20),
     password varchar(20),
     type varchar(2)
     } engin=InnoDB;

 table Customer{
      idCustomer int primary key,
      name varchar(20),
      surname varchar(20),
      lastOrder date,
 } engine = InnoDB;

以及前两个表之间的多对多关系:

table portfolio{
    idOperator int,
    idCustomer int,
    foreign key(idOperator) references Operator(idOperator)on update cascade on delete cascade
    foreign key(idCustomer) references Customer(idCustomer) on update cascade on delete cascade
}engine = InnoDB;

在我的Operator的Entity类中,我以这种方式映射表:

@Id
@Column(name = "idOperator")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Column(name = "name")
private String name;

@Column(name = "surname")
private String surname;

@Column(name = "username")
private String username;

@Column(name = "password")
private String password;

@Column(name = "type")
private String type;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "portfolio", joinColumns = {
    @JoinColumn(name = "idOperator")}, inverseJoinColumns = {
    @JoinColumn(name = "idCustomer")
})
private List<Customer> customers = new ArrayList<Customer>();

当我用这段代码询问运算符列表时:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Operator.class);
    criteria.add(Restrictions.eq("type","ad"));
    return criteria.list();

结果包括每个运营商的时间等于运营商在关系&#39;投资组合中所占的次数。

有人可以帮帮我吗?感谢

1 个答案:

答案 0 :(得分:0)

尝试如下:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Operator.class);
    criteria.add(Restrictions.eq("type","ad"));
criteria.setProjection(Projections.distinct(Projections.property("id")))
    return criteria.list();