一.
沒有基礎hibernate基礎的可以點擊這里 ---------->ORM----hibernate入門Demo(無敵詳細版)
這里我就不詳細介紹了..
二.
hibernat.cfg.xml文件是Hibernate中重要的配置文件,當Spring和Hibernate整合時,由於hibernate.cfg.xml文件中的配置信息可以教育Spring來管理,
所以可以選擇是否使用hibernate.cfg.xml文件.
這里將從使用hibernate.cfg.xml文件來講解Spring和Hibernate的整合
在講解Spring和Hibernate的整合前,首先需要了解三個重要的對象,具體如下:
1.HibernateTemplate:相當於Hibernate的session可以直接操作PO類,依賴於SessionFactory.
2.LocalSessionFactoryBean:獲取SessionFactory.
3.HibernateTransactionManager:Hibernate的事物管理器.
三.實現代碼:
整個項目所需jar包:

1.使用hibernate.cfg.xml文件整合Spring.
1).首先建立一張user表:

2).建立User類
public class User {
private Integer id; //用戶id
private String username; //用戶名稱
private String password; //用戶密碼
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
3).編寫對應的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>
<!-- name代表的是實體類名,table代表的是表名 -->
<class name="com.hck.entity.User" table="user">
<!-- name=id代表的是user類中屬性 column=id代表的是table表中的字段 -->
<id name="id" column="id">
<!-- 主鍵生成策略 -->
<generator class="native"/>
</id>
<!-- 其他屬性使用property標簽來映射 -->
<property name="username" column="username" type="string"/>
<property name="password" column="password" type="string"/>
</class>
</hibernate-mapping>
4).編寫UserDao接口
public interface UserDao {
public void save(User user); //添加用戶
public void update(User user); //更新用戶
public void delete(User user); //刪除用戶
public User findById(Integer id); //根據用戶id查找用戶數據
public List<User> findAll(); //返回所有用戶數據
}
5).編寫接口實現類:UserDaoImpl
//開啟注解模式,這句相當於在spring中
//<bean name="userDao" class="com.hck.dao.impl.UserDaoImpl"/>
@Repository("userDao")
public class UserDaoImpl implements UserDao {
//依賴注入
@Autowired
private HibernateTemplate hibernateTemplate;
//插入操作
public void save(User user) {
hibernateTemplate.save(user);
}
//更新操作
public void update(User user) {
hibernateTemplate.update(user);
}
//刪除操作
public void delete(User user) {
hibernateTemplate.delete(user);
}
//根據ID查找用戶
public User findById(Integer id) {
return hibernateTemplate.get(User.class, id);
}
//返回所有用戶數據
@SuppressWarnings("unchecked")
public List<User> findAll() {
return (List<User>) hibernateTemplate.find("from User");
}
}
6).編寫UserService接口
public interface UserService { public void save(User user); //添加用戶 public void update(User user); //更新用戶 public void delete(User user); //刪除用戶 public User findById(Integer id); //根據用戶id查找用戶數據 public List<User> findAll(); //返回所有用戶數據 }
7).編寫UserServiceImpl類
//開啟注解模式,這句相當於在spring中
//<bean name="userService" class="com.hck.service.impl.UserServiceImpl"/>
@Service("userService")
public class UserServiceImpl implements UserService {
//依賴注入
@Autowired
private UserDao userDao;
//插入數據
public void save(User user) {
userDao.save(user);
}
//更新數據
public void update(User user) {
userDao.update(user);
}
//刪除數據
public void delete(User user) {
userDao.delete(user);
}
//根據id查找用戶
public User findById(Integer id) {
return userDao.findById(id);
}
//返回所有用戶信息
public List<User> findAll() {
return userDao.findAll();
}
}
8).編寫核心配置文件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="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- 數據庫驅動 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 連接數據庫的url -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tb_test</property>
<!-- 數據庫用戶名 -->
<property name="hibernate.connection.username">root</property>
<!-- 數據庫密碼 -->
<property name="hibernate.connection.password">123456</property>
<!-- 其他配置 -->
<!-- 顯示sql語句 -->
<property name="show_sql">true</property>
<!-- 配置c3p0 -->
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<!-- 用來關聯hbm配置文件 -->
<!-- <mapping resource="com/hck/entity/Customer.hbm.xml"/> -->
<mapping resource="com/hck/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
9).編寫Spring的配置文件applicationContext.xml同樣放在src目錄下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 開啟注解 -->
<context:annotation-config/>
<!-- 1.配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 加載Hibernate核心配置文件 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
<!-- 2.配置Hibernate模版 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<!-- 通過工廠獲得Session,操作PO類 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 事務管理 -->
<!-- #1事務管理器,就是平台,Sprring工具產生,依賴於使用持久方案 -->
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- #2通知:增強事務 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*"/>
<tx:method name="update*"/>
<tx:method name="delete*"/>
<!-- 只讀 -->
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- #3 切面:將切入點與通知點關聯 -->
<aop:config>
<aop:pointcut expression="execution(* com.hck.service.*.*(..))" id="allDaoMethod" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethod"/>
</aop:config>
<!-- 包掃描 -->
<context:component-scan base-package="com.hck"/>
</beans>
10).編寫單元測試類:
public class SpringHibernateTest {
//定義變量
ApplicationContext ac; //讀取Spring配置文件,返回上下文對象
UserService userService; //用於接收一個UserServiceImpl實例
@Before
public void setUp(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
userService=(UserService) ac.getBean("userService");
}
@Test
public void insert()
{
User user=new User();
user.setUsername("張三");
user.setPassword("123456");
userService.save(user);
}
@Test
public void findById()
{
User user=userService.findById(1);
System.out.println(user);
}
//修改用戶名
@Test
public void update()
{
User user=new User();
user.setId(1);
user.setUsername("李四");
user.setPassword("123456");
userService.update(user);
}
//先查找再刪除
@Test
public void delete()
{
User user=userService.findById(1);
userService.delete(user);
}
//查找所有
@Test
public void findAll()
{
List<User> list =userService.findAll();
for(User user:list)
{
System.out.println(user);
}
}
}
11)測試結果:
A.插入操作:
控制台打印的sql語句,然后到mysql查看數據是否插入成功;這里我再插入兩條信息用戶分開顯示查詢所有用戶信息


B.查詢操作(查詢用戶id為1的信息):

C.更新操作,(將id=1的用戶名修改為李四)

D.刪除操作,(將id=1的用戶信息刪除)


E.查詢所有用戶信息

四.總結
以上是完整的帶hibernate.cfg.xml文件的Spring跟Hibernate的整合過程,如有疑問可以留言~
