xml映射类
目的是将对象的属性和数据库的 column 一一对应,<generator class="identity"/>对应自增id
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="com.goudai.domain.User" table="userinfo">
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="username" column="username"/>
<property name="password" column="password"/>
</class>
</hibernate-mapping>
session工厂配置
数据源,对象映射文件,属性配置
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:mappingLocations="user.hbm.xml">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
</props>
</property>
</bean>
HibernateTemplate
类映射文件配置正确,这个东西无脑调用增删查改方法,自定义查询可调用回调接口HibernateCalback<T>
注意事项
测试写入数据库时要注意配置事务管理,增加@Rollback(false)注解可已避免测试环境下事务回滚的情况。
参考代码:https://github.com/hegoudai/Learning-Spring/tree/master/hibernate