Join two tables in Hibernate with Criteria API and Annotation

99封情书 提交于 2019-12-08 10:26:34

问题


I want to join 2 tables in MySQL with Hibernate Annotations and Criteria Like for example:

I have 2 tables, candidates and jobs, having 2 columns each:

  • candidates: candID & candName
  • jobs: jobID & jobName

                            candidates                     jobs       
                  candID    candName          jobID          jobName
                      1          abc                       1               job1
                      2          xyz                       2               job2
    

i need to create a query in Criteria in hibernate as:

 select candName  ,jobName    from candidates as c ,jobs as j  
 where c.candID = j.jobID where candName = abc and jobName=job1

what will be the criteria query for that and most importantly what will i write in my annotation class ( as i am using spring annotations) and do i need to write anything in my applicantioncontext.xml...

Thanks

I will be really greatful if you can help me with that as i am struggling for last 3 days for it with no success

thanks


回答1:


Assuming table per class Hierarchy, where Candidates and Jobs correspond to their database entities

public class Candidates{
//define Generative stretegy if this is primary key, and other JPA annotations, with cascade
  private Long CandId;
//getters and setters
//define other properties here

}
/*Like wise for Jobs class */

I donot check inside an IDE/Compiler but it should be somelike below

Criteria c1 = session.createCriteria(Candidates.class,candidate);
Criteria j1 = session.createCriteria(Jobs.class,jobs);
c1.setProjection(Property.forName(candName));
j1.setProjection(Property.forName(jobName));
c1.add(Restrictions.and(Property.eqName(candidate.candId,jobs.jobId)));
j1.add(Restrictions.and(jobs.jobName,"job1"));
c1.addCriterion(j1);


来源:https://stackoverflow.com/questions/6083660/join-two-tables-in-hibernate-with-criteria-api-and-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!