我是hibernate框架的新手。我正在使用hibernate 4.3.6。我的模型类是
public class UserDetails{
@Id
private int userId;
private String Name;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
以下是我的hibernate配置
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/GHAC</property>
<property name="connection.username">root</property>
<property name="connection.password"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="org.ghac.uday.UserDetails"/>
</session-factory>
</hibernate-configuration>
我正在尝试使用以下代码在hibernate中存储记录
UserDetails user = new UserDetails();
user.setUserId(1);
user.setName("Uday Kiran");
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Transaction tx = session.getTransaction();
session.save(user);
tx.commit();
session.close();
但我总是收到以下错误。请说明我做错了什么?
Sep 04, 2014 9:32:11 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
Sep 04, 2014 9:32:11 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Exception in thread "main" org.hibernate.TransactionException: Transaction not successfully started
at
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:172)
at org.ghac.uday.example.HibernateTest.main(HibernateTest.java:28)
答案 0 :(得分:1)
您忘了开始交易:
Transaction tx = session.getTransaction();
tx.begin(); // Add this line
答案 1 :(得分:0)
你忘了为休眠启动Transaction。试试这个:
Session session = SessionFactory.openSession();
Transaction trans = session.beginTransaction();
顺便说一句,我建议你不要在标签session-factory中写下所有的hibernate配置文件。编写hibernate配置文件包括:dialect,show_sql甚至hbm2dll在一个单独的文件中:例如hibernate.properties。它成为一个专业的愿景!祝你好运