2013-11-26 7 views
0

Я пытаюсь использовать 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> 

и зимуют 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> 

я получаю ошибки (я могу опубликовать полный стек, если необходимо, bu t это очень длинный): Вызвано: 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 Обще аннотация 4.2.0 Java помочь 3.15 Все останавливается при SessionFactory = конфигурации .buildSessionFactory (serviceRegistry); эти записи в журналах несколько раз. Любые идеи, что может быть неправильным?

ответ

0

Я решаю свою проблему. Проблема была в неправильной конфигурации hbm Проблемные линии:

Смежные вопросы