Hibernate中的内连接查询

时间:2015-01-27 18:21:32

标签: sql hibernate inner-join

我想用Hibernate运行一个查询,但是我不知道我错了什么,我得错了。

我试过了

public List<String> findCourseForStudent(String pnr) {
       factory = new Configuration().configure().buildSessionFactory();
       Session session = factory.openSession();
       Transaction tx = null;

       try {
           tx = session.beginTransaction();
           String sql = "select Course.name from Course inner join CourseMaterial "
                + "on CourseMaterial.course_id = Course.id inner join CourseParticipantship "
                + "on CourseMaterial.id = CourseParticipantship.courseMaterial_id inner join Student "
                + "on Student.id=CourseParticipantship.student_id where Student.personalNumber='" + pnr + "'";
           SQLQuery query = session.createSQLQuery(sql);
           query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
           query.setParameter("pnr", pnr);
           List data = query.list();
           tx.commit();
           return data;
       } catch(HibernateException e) {
           if(tx != null) tx.rollback();
           e.printStackTrace();
       } finally {
           session.close();
       }
       return null;
}

但是我收到以下错误:

net.sf.ehcache.CacheException: Another unnamed CacheManager already exists     in the same VM. Please provide unique names for each CacheManager in the config   or do one of following:
 1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
 2. Shutdown the earlier cacheManager before creating new one with same name.
 The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]

我已经搜索了错误并尝试了一些解决方案,但它们都没有为我工作,所以我尝试使用HQL而不是直接使用sql,但仍然没有成功:( 我实际上不知道如何在DetachedCriteria中使用INNER_JOIN,否则我认为使用DetachedCriteria我不会得到任何错误,因为我试图将它用于更简单的查询,它工作正常。

以下是一个工作正常的简单查询的示例,但我不知道如何为内部查询查询

public List<Student> findForCourse(Integer integer) {
    DetachedCriteria criteria = DetachedCriteria.forClass(Student.class);
    criteria.add(Restrictions.eq("course.id", integer));
    criteria.add(Restrictions.ne("active", Boolean.FALSE));
    return getHibernateTemplate().findByCriteria(criteria);
}

1 个答案:

答案 0 :(得分:0)

最后,我发现了如何在hibernate中编写查询

public List<String> findCourseForStudent(String pnr) {
    return jdbcTemplate.query(
            "select Course.name from Course inner join CourseMaterial "
                    + "on CourseMaterial.course_id = Course.id inner join CourseParticipantship "
                    + "on CourseMaterial.id = CourseParticipantship.courseMaterial_id inner join thd.dbo.Student "
                    + "on Student.id=CourseParticipantship.student_id where Student.personalNumber= ?", new Object[] { pnr }, new RowMapper() {
                public Object mapRow(ResultSet rs, int row) throws SQLException {
                    return rs;
                }

            });
}