java - 通过 Maven Tomcat 插件运行时,Hibernate 不解析映射文件

标签 java hibernate maven tomcat intellij-idea

这在使用 IntelliJ RESTFul 网络服务框架支持时有效。但是,我现在正尝试使用 Tomcat 插件通过 Maven 运行整个测试服务。

我有这个 Hibernate 配置文件:

org.hibernate.dialect.PostgreSQL82方言 org.postgresql.驱动程序 jdbc:postgresql://localhost:5432/microservicedb 后置数据库 我的密码

    <!--<property name="connection_pool_size">1</property>
    <property name="hbm2ddl.auto">create</property>
    <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="current_session_context_class">thread</property>-->

    <property name="hibernate.show_sql">false</property>

    <mapping resource="user.hbm.xml"></mapping>
</session-factory>

用户文件定义如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.pidac.myapp.testrestapi.User" table="Users">
        <meta attribute="class-description">
            This class contains the employee detail.
        </meta>
        <id name="id" type="int" column="id">
            <generator class="increment"/>
        </id>
        <property name="firstName" column="firstname" type="string"/>
        <property name="lastName" column="lastname" type="string"/>           
    </class>
</hibernate-mapping>

这两个文件都保存在 src/main/resources 下。

我的 HibernateUtils 相当标准:

public class HibernateUtils {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {

        if (sessionFactory == null) {
            // loads configuration and mappings
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry
                    = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            // builds a session factory from the service registry
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }

        return sessionFactory;
    }

    public static Session getSession() throws HibernateException {
        return getSessionFactory().openSession();
    }
}

我有一个 Jersey 资源示例,如下所示:

@Path("/user")
public class UserResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public User[] getAll(){

        Session session = HibernateUtils.getSession();
        session.beginTransaction();

        Query query=  session.createQuery("from User where  id > :id");

        query.setParameter("id", 0);

        Object[] users = query.list().toArray();

        User[] toReturn = new User[users.length];
        for (int i = 0; i < users.length; i++){
            toReturn[i] = (User)users[i];
        }

        session.close();
        return toReturn;
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public User[] createUsers(User[] users){

        Session session = HibernateUtils.getSession();
        session.beginTransaction();

        for (User user : users){
            System.out.println("Adding user to session " + user.toString());
            session.save(user);
        }

        session.getTransaction().commit();
        session.close();

      return users;
    }

用户类定义如下:

package com.pidac.myapp.testrestapi;

/**  * Created by Klaus on 31/08/2015.  */ public class User {
    private String _firstName;
    private String _lastName; 
    private int _id;

    public String getFirstName(){
        return _firstName;
    }
    public void setFirstName(String name){
        _firstName = name;
    }    

    public int getId() {
        return _id;
    }

    public void setId(int _id) {
        this._id = _id;
    }

    public String getLastName() {
        return _lastName;
    }

    public void setLastName(String _lastName) {
        this._lastName = _lastName;
    }

    @Override public String toString(){
        return String.format("%s Ss", _firstName, _age);
    } }

当我通过 Maven 在 Tomcat 中运行时,出现错误

 User is not mapped [from User where id > :id]

我可能遗漏了什么?

最佳答案

这是一个很奇怪的问题。我什至删除了所有 hibernate 映射文件并使用 IntelliJ Persistence Tools 窗口创建文件但遇到了同样的问题。

我最终只是在 User 类上使用了 hibernate 注释,如下所示:

import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Column;

@javax.persistence.Entity
@javax.persistence.Table( name = "users" )
public class User {

    @Column (name = "firstname")
    private String firstName;

    @Column (name = "lastname")
    private String lastName;

    public String getFirstName(){
        return firstName;
    }
    public void setFirstName(String firstName){ this.firstName = firstName;
    }

    @javax.persistence.Id
    @javax.persistence.GeneratedValue
    //@GenericGenerator(name="increment", strategy = "increment")
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override public String toString(){
        return String.format("%s %s", firstName, lastName);
    }
}

并稍微修改了我的 HibernateUtils 以识别带注释的类,如下所示:

public class HibernateUtils {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {

        if (sessionFactory == null) {

            // loads configuration and mappings
            Configuration configuration = new Configuration().configure().addAnnotatedClass(User.class);
            ServiceRegistry serviceRegistry
                    = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

            // builds a session factory from the service registry
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }

        return sessionFactory;
    }

    public static Session getSession() throws HibernateException {
        return getSessionFactory().openSession();
    }
}

当通过 Tomcat Maven 插件或 IntelliJ 的应用程序服务器工具窗口部署时,服务运行良好。

关于java - 通过 Maven Tomcat 插件运行时,Hibernate 不解析映射文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32344205/

相关文章:

java - 如何在 Spring 应用程序启动时调用自定义数据加载器

java - 尝试在Java中使用xlsx读取并返回字符串数组

java - 使用应用程序实现更改用户角色场景

java - hibernate 4 jta websphere

java - 如何在Java中将PostgreSQl View 与hibernate连接?

java - MAVEN 构建失败 - 无法解决项目 XYZ 的依赖关系

java - 在 IntelliJ 中更改 JDK 似乎不起作用

java - 如何为我的 android 应用程序制作推送通知服务器?

java - 使用 Camel 缓存时 Camel 路由已启动但未运行

java - 如何根据 Avro 模式验证 JSON