我正在使用Hibernate 4.3.6。
org.hibernate.cfgConfiguration
的javadoc说:
This will be replaced by use of
org.hibernate.boot.registry.StandardServiceRegistryBuilder and
org.hibernate.metamodel.MetadataSources instead after the 4.0 release at
which point this class will become deprecated and scheduled for removal in 5.0.
所以我尝试使用MetadataSources
和StandardServiceRegistryBuilder
来构建我的sessionFactory,这是我的代码:
package com.lithops.ims;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.metamodel.MetadataSources;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
MetadataSources md = new MetadataSources(srb.configure().build());
return md.buildMetadata().buildSessionFactory();
}
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;
}
}
public class HelloWorld {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(new TradeHistory("123", new Date(), 1.2f, 100L));
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
}
TradeHistory.java :
package com.lithops.ims.domain;
import java.util.Date;
public class TradeHistory {
private Long id;
private String code;
private Date date;
private float price;
private long amount;
public TradeHistory() {}
public TradeHistory(String code, Date date, float price, long amount) {
this.code = code;
this.date = date;
this.price =price;
this.amount = amount;
}
/* setters and getters omitted */
}
TradeHistory.hbm.xml (与TradeHistory.java
在同一个包中):
<hibernate-mapping package="com.lithops.ims.domain">
<class name="TradeHistory" table="TRADE_HISTORY">
<id name="id" column="TRADE_ID">
<generator class="native" />
</id>
<property name="code" column="STACK_CODE"/>
<property name="date" type="timestamp" column="TRADE_TIME"/>
<property name="price" column="PRICE" />
<property name="amount" column="AMOUNT" />
</class>
</hibernate-mapping>
和 hibernate.cfg.xml 文件(在src/main/resources folder
中):
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- properties omitted -->
<mapping resource="com/lithops/ims/domain/TradeHistory.hbm.xml" />
</session-factory>
</hibernate-configuration>
但似乎hibernate.cfg.xml
中的映射没有被解析。执行我的应用程序时,org.hibernate.MappingException: Unknown entity...
发生了。
异常堆栈信息:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.lithops.ims.domain.TradeHistory
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
at com.sun.proxy.$Proxy20.save(Unknown Source)
at com.lithops.ims.HelloWorld.main(HelloWorld.java:31)
注意:使用Configuration
类时效果很好。
答案 0 :(得分:0)
如下所示
public void testConnection() throws Exception {
logger.info("Trying to create a test connection with the database.");
Configuration configuration = new Configuration();
configuration.configure("hibernate_sp.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
Session session = sessionFactory.openSession();
logger.info("Test connection with the database created successfuly.");
}
<强> HibernateUtil.java 强>
package your.package;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
// Configuration configuration = new Configuration();
Configuration configuration = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException he)
{
System.err.println("Error creating Session: " + he);
throw new ExceptionInInitializerError(he);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
来自博客
需要修改我的hibernate 3.2.6配置和映射文件以使用xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
和xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
,并删除dtd规范。