一般情况下不能保存数据的原因有:
1.没有开启事务,事务没有提交。
2.代码前后的事务不是同一个,这个是不太容易发现的问题,因为代码不会报错
3.主键生成配置有问题,不能生成主键,当然保存不了数据
二保存方法返回值
save方法返回的是Serializable接口,该结果的值就是你插入到数据库后新记录的主键值。如果你的主键是数值,可以按如下方法
Serializable result = this.getSession().save(t);
Integer integer = (Integer)result;
一些与版本有关的问题
session.createSQLQuery(sql).addEntity(Classclass);注意hibernate3.0.5不支持
hibernate的配置文件是有顺序要求的,比如下面的username与password是不能移动到mapping之后的
<?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="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<mapping class="entity.Book"/>
<mapping class="entity.People"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>