简体   繁体   English

Java Hibernate标准多对一

[英]Java Hibernate Criteria Many-To-One

I am trying to use hibernate with a Many-to-one relationship, as shown below: 我正在尝试使用具有多对一关系的休眠,如下所示:

I have a service table and for each service, we have a programId. 我有一个服务表,每个服务都有一个programId。

public class Service {
   ...
   @ManyToOne
   @JoinColumn(name="PROGRAM_LV_ID", referencedColumnName = "ID")
   private Program program;
}

In the BD, I have the records: 在BD中,我有以下记录:

Service Table 服务表

id = 1, programid = 2 id = 1,programid = 2

id = 2, programid = 2 id = 2,programid = 2

id = 3, programid = 3 id = 3,programid = 3

Program Table 节目表

id = 2, name = "program2" id = 2,名称=“ program2”

id = 3, name = "program3" id = 3,名称=“ program3”

I am trying to do something like: 我正在尝试做类似的事情:

public List<Service> getServicesForProgram(long id) {
    Criteria criteria = getSession().createCriteria(Service.class, "s");
        criteria.createAlias("s.program", "p");
        criteria.add(Restrictions.eq("p.id", id));

        return (List<Service>)criteria.list();
}

When I pass 2 to the method, I get 4 records instead of 2. Somehow the results are duplicated and I get the services with ids 1 and 2 twice. 当我将2传递给该方法时,我得到4条记录而不是2条记录。以某种方式重复结果,并两次获得ID为1和2的服务。

Can someone help me with why the duplication is happening? 有人可以帮我解释为什么会发生重复吗?

All help is greatly appreciated. 非常感谢所有帮助。

Thanks. 谢谢。

尝试这个:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

Your query in plain SQL is actually something like: 您在普通SQL中的查询实际上是这样的:

    SELECT * from service p, program where s.id = 1;

It just combines both records from service and program with id = 1 in the service table. 它只是将服务表中id = 1的服务和程序的记录合并在一起。

And hence if there are 2 records in the program table(where primary key is 1 and 2), and 2 in the service(where the foreign key is 1), all it will do is fetch 4 rows[2 x 2]. 因此,如果程序表中有2条记录(主键是1和2),服务中有2条记录(外键是1),那么它要做的就是获取4行[2 x 2]。

To fetch the records, you can use the DISTINCT criteria as: 要获取记录,可以将DISTINCT条件用作:

   Criteria cr = getSession().createCriteria(Service.class);
   cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM