使用Hibernate 4.2.6和Spring 3.1.1
我有一个与此相似的课程
@Entity
@Table( name = "MY_TABLE" )
public class MyTable{ ... }
然后我在hibernate.cfg.xml文件中有以下内容
<mapping class="com.mycompany.myapp.persistence.domain.MyTable"/>
当我运行JUnit测试时,我得到一个Session并查询该表,我收到以下错误:
Initial SessionFactory creation failed.org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mycompany.myapp.persistence.domain.MyTable"/>
我不明白为什么根据我读过的内容,不推荐使用AnnotationConfiguration并将功能转移到Configuration中。
要获得会议,我正在做这个
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
但它无法获取会话并抛出此错误。
答案 0 :(得分:1)
似乎现在正在工作。解决方案有两个方面:
首先,此代码是正确的:
a)映射类保留在hibernate.cfg.xml
中b)创建一个HibernateUtil类
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
c)创建Model类
d)然后在测试中,在setup()中实例化sessionFactory,就像这样
sessionFactory = HibernateUtil.getSessionFactory();
e)然后像这样查询数据库
Session session = sessionFactory.openSession();
session.beginTransaction();
List<TableName> result = session.createQuery("from table").list();
session.getTransaction().commit();
session.close();
第二,在使用AnnotatedConfiguration类之前,我使用JBoss 4.2作为我的目标运行时,它使用的是Hibernate 3.4.2。不将JBoss定位为运行时导致使用Hibernate 4.2.6(通过Maven导入)并且不会导致此错误。因为Hibernate在设置时会打印出它的版本,所以应该给予更好的关注! : - )