无法创建hibernate会话

时间:2013-11-26 22:06:37

标签: hibernate session derby

我正在尝试将Hibernate与Derby一起使用,我在创建会话时遇到了问题。 我收到错误的类:

package pl.edu.calendar.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import pl.edu.calendar.XML.DObjectXML;
import pl.edu.calendar.box.MessageBox;
import pl.edu.calendar.configuration.DConfig;
import pl.edu.calendar.configuration.errors.ErrorHandler;
import pl.edu.calendar.helpers.FileManager;
import pl.edu.calendar.helpers.Message;
import pl.edu.calendar.model.events.PostLoad;

public class Derby extends DObjectXML {

    private String url = "";
    private Configuration config = null;
    protected DConfig cfg = DConfig.app();
    protected Session session = null;
    protected Transaction transaction = null;
    private ServiceRegistry serviceRegistry = null;
    private SessionFactory sessionFactory;

    public Derby() {
        this.url = "jdbc:derby:" + cfg.getConfigPath() + "data" + DConfig.DS + "db;create=true";
        String user = "admin";
        String pass = "admin";
        String schema = "ADMIN";
        config = new Configuration()
                .setProperty("hibernate.connection.url", this.url)
                .setProperty("hibernate.default_schema",schema)
                .setProperty("hibernate.connection.username",user)
                .setProperty("hibernate.connection.password",pass)
                .configure("/pl/edu/calendar/models/hibernate.derby.cfg.xml");
        config.setInterceptor(new PostLoad());
        serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        if (!FileManager.is(DConfig.getConfigPath() + "data")) {
            FileManager.mkDir(DConfig.getConfigPath() + "data");
        }
        checkAvailable();
    }

    public void connect() {
        serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        session = sessionFactory.openSession();
    }

    public void closeConnection() {
        if(session != null && session.isConnected())
            session.close();
    }

    /**
     * Method begin database transaction
     */
    public void startTransaction() {
        transaction = session.beginTransaction();
    }

    /**
     * Method commit database transaction
     */
    public void commitTransaction() {
        transaction.commit();
    }

    /**
     * Method rollback database transaction
     */
    public void rollbackTransaction(Exception e) {
        transaction.rollback();
        if (DConfig.app().isDebug()) {
            Message.print("Transaction roolback! In " + this.toString() + "becouse : " + e.getMessage());
            ErrorHandler.error(e);
        }
    }

    /**
     * Return model session
     *
     * @return Session
     */
    public Session getSession() {
        return session;
    }

    /**
     * Set session for transaction
     *
     * @param session Session
     */
    public void setSession(Session session) {
        this.session = session;
    }

    /**
     * Method check if database ia available
     */
    private void checkAvailable() {
        try {
            connect();
            startTransaction();
            closeConnection();
        } catch (GenericJDBCException ex) {
            MessageBox.error(Message._("program_initialized"));
            System.exit(1);
        }
    }
}

POJO:

package pl.edu.calendar.models.entity;

import pl.edu.calendar.model.LocalModel;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;

public class NotesEntity extends LocalModel {

    public NotesEntity() {
    }

    public NotesEntity(String title, String description, Date date, int user_id) {
        this.title = title;
        this.description = description;
        this.user_id = user_id;
    }

    public NotesEntity(int id, String title, String description, Date date, int user_id) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.user_id = user_id;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Override
    public int getId() {
        return id;
    }

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

    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    private int user_id;

    public int getUser_id() {
        return user_id;
    }

    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }

    private UserEntity userById;

    public UserEntity getUserById() {
        return userById;
    }

    public void setUserById(UserEntity userById) {
        this.userById = userById;
    }

    private Date date;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        NotesEntity that = (NotesEntity) o;

        if (user_id != that.user_id)
            return false;
        if (id != that.id)
            return false;
        if (description != null ? !description.equals(that.description) : that.description != null)
            return false;
        if (title != null ? !title.equals(that.title) : that.title != null)
            return false;

        return true;
    }

    @Override
    public String getModelName() {
        return "NOTES";
    }

}

映射文件:

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

    <class name="pl.edu.calendar.models.entity.NotesEntity" table="NOTES">
        <id name="id" column="id" type="long">
            <generator class="increment"></generator>
        </id>
        <property name="title" column="TITLE"/>
        <property name="description" column="DESCRIPTION"/>
        <property name="date" column="DATE"/>
        <property name="user_id" column="USER_ID"/>
        <many-to-one name="userById" insert="false" update="false" class="pl.edu.calendar.models.entity.UserEntity">
            <column name="USER_ID"/>
        </many-to-one>
    </class>
</hibernate-mapping>

和hibernate cfg

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
      <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="show_sql">false</property>
      <property name="hibernate.dialect">org.hibernate.dialect.DerbyTenSevenDialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <mapping resource="pl/edu/calendar/models/mapping/UserEntity.hbm.xml"/>
      <mapping resource="pl/edu/calendar/models/mapping/NotesEntity.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

我收到错误(如果需要,我可以发布完整的堆栈跟踪,但它很长): 引起:org.hibernate.MappingException:无法获取org.hibernate.persister.entity.SingleTableEntityPersister的构造函数 引起:org.hibernate.InstantiationException:无法实例化测试objectpl.edu.calendar.models.entity.NotesEntity 引起:java.lang.reflect.InvocationTargetException

Java版本1.7.0.45 Hibernate版本4.2.2 hibernate commons annotation 4.2.0 java协助3.15 一切都在sessionFactory = config.buildSessionFactory(serviceRegistry)停止; 日志中的条目很少次。什么想法可能是错的?

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。 问题在于hbm的配置错误 问题线: