我想在Spring中使用hibernate并使用HSQL DB。我无法将我的对象持久化到数据库,因为Hibernate不从对象获取值,而是在生成的插入语句中使用空值。我现在试图调试这个问题一段时间,并且已经用完了想法。任何有关这个问题的帮助,我们都非常感谢Hibernate在与Spring一起使用时将空值插入到表中
这是我的代码片段。
应用程序上下文(applicationContext.xml):我在上下文中配置我的数据源,会话工厂,DAO和事务管理器。
<context:component-scan base-package="com.wb.services.fileservice" />
<tx:annotation-driven />
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/wb/services/testdb/schema.sql" />
<jdbc:script location="classpath:com/wb/services/testdb/test-data.sql" />
</jdbc:embedded-database>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>/com/wb/services/fileservice/file.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="fileServiceDAO" class="com.wb.services.fileservice.FileServiceDAO">
<constructor-arg ref="sessionFactory" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
我的Hibernate映射文件(file.hbm.xml):
<class name="com.wb.services.fileservicemodel.FilePrintHibernate" table="T_FILES">
<id name="fileID" column="File_ID" type="int">
<generator class="native"/>
</id>
<property name="name" column="Name"/>
<property name="text" column="Text"/>
</class>
是需要保留的瞬态类(FilePrintHibernate):
public class FilePrintHibernate implements Serializable {
private int fileID;
private String name;
private String text;
// Skipping getters and setters for the above.
}
DAO类将持久对象到数据库表。
@Repository
@Transactional
public class FileServiceDAO {
private SessionFactory sessionFactory;
public FileServiceDAO() {
}
public FileServiceDAO(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
@Transactional(readOnly = false, propagation=Propagation.REQUIRED)
public void findByCreditCard(String filename) {
FilePrintHibernate filePrintHibernate = new FilePrintHibernate();
filePrintHibernate.setFileID(2);
filePrintHibernate.setName("Manual");
filePrintHibernate.setText("Hibernate Test Example");
getCurrentSession().save(filePrintHibernate);
getCurrentSession().flush();
}
}
当应用程序运行和DAO类(上面的代码文件4)尝试坚持的FilePrintHibernate对象,我收到的INSERT语句:insert into T_FILES (File_ID, Name, Text) values (null, ?, ?)
。请注意它试图插入的值。而不是我设置的值(2,“Manual”,“Hibernate Test Example”)。
您能否让我知道我在做什么以上错误。上述任何帮助真的很感激。
问候,
虚无
谢谢你的回复Bozho。我已经想出了这个问题。看来由HSQL创建的表没有声明主键。该列被创建为唯一但不是主键。昨天我病了,无法更新这个帖子。我会将其更新为已关闭。 – user727833 2011-04-29 14:11:34