【问题标题】:Hibernate need full path for mapped class in queryHibernate 需要查询中映射类的完整路径
【发布时间】:2014-09-10 13:44:35
【问题描述】:

我在路径上映射了类:com.me.model.User。和com.me.daoImpl.UserDaoImpl的用户DAO。

DAO 如下所示:

package com.me.daoImpl;

//other imports
import com.me.model.User;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    SessionFactory sessionFactory;

    //other methods...

    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {
        Session session = sessionFactory.openSession();
        try {
            return session.createQuery("from com.lime.model.User").list();
        } finally {
            session.close();
        }
    }

}

我的问题是如何让hibernate知道模型对象类?正如您在上面看到的,我有 User 的导入,但我必须在 createQuery() 方法中给出完整路径。

return session.createQuery("from User").list();

这显示错误:

cannot resolve symbol User 

【问题讨论】:

  • 你在spring配置文件中定义了bean吗?向我们展示错误堆栈跟踪。
  • 我没有得到异常,上面的代码可以工作,但只需要完整路径,而且总是写完整路径很烦人

标签: java spring hibernate annotations


【解决方案1】:

Hibernate 5 也有类似的问题,请确保使用正确的 JDK 版本。 我将我的从 8 更改为 11,它起作用了。

还必须在hibernate.cfg.xml 文件和中提琴中包含&lt;mapping class="com.example.ClassName" /&gt;,编译器不再要求提供完全限定名称..

【讨论】:

    【解决方案2】:

    你可以像在hibernate配置文件中映射类和包

    <hibernate-configuration>
        <session-factory>
            <mapping class="com.me.model.User" />
    

    要将此配置与 spring 一起使用,请将此属性添加到会话工厂 bean

    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    

    hibernate.cfg.xml 应该在类路径中。

    【讨论】:

    • 我已经有了映射,这是可行的,但它只需要查询中的完整路径(使用 com.me...)
    • 这是基于注释的打盹,你应该在类上使用注释,我不知道你使用的是哪个版本的休眠,因为它需要基于注释的配置。
    • 嗯...我已经通过spring作为属性annotatedClasses中的bean sessionFactory进行了映射,这就是它需要完整路径的原因,但是我添加了hibernate.cfg.xml,因为你很伤心,现在这就是我想要的,但现在有一个问题,会话工厂、spring 或 hibernate 使用什么 cfg?因为听说用spring配置比较好。
    • 如果你使用的是spring,你可以用它配置hibernate.cfg.xml
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多