使用 Criteria API 和 Annotation 在 Hibernate 中连接两个表 [英] Join two tables in Hibernate with Criteria API and Annotation
问题描述
我想用 Hibernate Annotations 和 Criteria 在 MySQL 中加入 2 个表例如:
I want to join 2 tables in MySQL with Hibernate Annotations and Criteria Like for example:
我有 2 个表,候选人和工作,每个表有 2 列:
I have 2 tables, candidates and jobs, having 2 columns each:
- 候选人:candID &名字
工作:jobID &工作名称
- candidates: candID & candName
jobs: jobID & jobName
candidates jobs
candID candName jobID jobName
1 abc 1 job1
2 xyz 2 job2
我需要在 Hibernate 的 Criteria 中创建一个查询:
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
对此的标准查询是什么,最重要的是我将在我的注释类中写什么(因为我使用的是 spring 注释),我是否需要在我的申请者上下文.xml 中写任何东西...
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...
谢谢
如果您能帮助我,我将非常感激,因为我在过去 3 天里一直在为它而苦苦挣扎,但没有成功
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
谢谢
推荐答案
假设每个类的层次结构表,其中 Candidates 和 Jobs 对应于他们的数据库实体
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 */
我不检查 IDE/编译器内部,但它应该类似于下面
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);
这篇关于使用 Criteria API 和 Annotation 在 Hibernate 中连接两个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!