【问题标题】:Join two tables in Hibernate with Criteria API and Annotation在 Hibernate 中使用 Criteria API 和 Annotation 连接两个表
【发布时间】:2011-08-30 07:57:54
【问题描述】:

我想用 Hibernate Annotations 和 Criteria 在 MySQL 中加入 2 个表 比如:

我有 2 个表格,候选人和工作,每个有 2 列:

  • 候选人:candID & candName
  • 工作:工作 ID 和工作名称

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

我需要在hibernate的Criteria中创建一个查询:

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

什么将是标准查询,最重要的是我将在我的注释类中写什么(因为我正在使用 spring 注释),我需要在我的申请上下文中写任何东西.xml...

谢谢

如果你能帮我解决这个问题,我将非常感激,因为我在过去 3 天都在为此苦苦挣扎,但没有成功

谢谢

【问题讨论】:

    标签: hibernate annotations criteria


    【解决方案1】:

    假设每个类层次结构的表,其中候选人和工作对应于它们的数据库实体

    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/编译器内部,但它应该如下所示

    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);
    

    【讨论】:

    • 谢谢,这个候选人和工作具体是什么?
    • 感谢您的回复,这个候选人和职位到底是什么,我将在哪里申报?因为我们只能在这里写字符串.. createCriteria(Candidates.class,candidate); createCriteria(Jobs.class,jobs);当我使用这个 c1.setProjection(candidate.candName);它说candidate.candName必须是一个投影,那是一个字符串
    • @Narayan setProjection 方法接受Projections 类型参数,这里candidate.candNamejobs.jobName 是什么类型的变量?
    • @VisruthCV:candName 和 jobname 是属性/字段,chk 更新!
    • 我猜没有 addCriterion for criteria 的方法
    猜你喜欢
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2015-03-23
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2013-05-27
    相关资源
    最近更新 更多