我需要配置hibernate会话管理器以正确插入带有自动增量ID的记录。我使用Java DB(Derby)并且可能在应用正确方言时遇到一些问题(hibernate使用last_insert_id()而不是IDENTITY_VAL_LOCAL()),但它的定义看起来没问题。或不?我对此还没有多少经验,所以感谢您的一点提示。
servlet-context.xml的相关部分:
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/sample"/>
<property name="username" value="app"/>
<property name="password" value="app"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
hibernate.cfg.xml中:
<?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>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="show_sql">true</property>
<mapping resource="net/codejava/spring/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml:
<?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="net.codejava.spring.model">
<class name="User" table="USERS">
<id name="id" column="USER_ID">
<generator class="native"/>
</id>
<property name="username" column="USERNAME" />
<property name="password" column="PASSWORD" />
<property name="email" column="EMAIL" />
</class>
</hibernate-mapping>
实施代码:
public void InsertUser(User user) {
Session session = sessionFactory.getCurrentSession();
session.save(user);
}
服务器日志:
Info: Hibernate: insert into USERS (USERNAME, PASSWORD, EMAIL) values (?, ?, ?)
Info: Hibernate: select last_insert_id()
WARN: SQL Error: 20000, SQLState: 42X01