首页 > 代码库 > Hibernate与spring整合时的整合步骤

Hibernate与spring整合时的整合步骤

Hibernate与Spring整合步骤:

第一步:加入Hibernate和Spring的相关jar包


第二步:创建application.xml文件,配置dataSource和session,

第三步:将sessionFactory对象注入到Dao实现类中,并操作数据库

<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="userDao" class="com.hcj.dao.impl.UserDaoImpl">
		<!-- 将sessionFactory注入到Dao实现类中 -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="userServer" class="com.hcj.service.impl.UserServiceImpl">
		<!-- 动态添加userDao到UserServiceImpl对象中 -->
		<property name="userDao" ref="userDao"></property>
	</bean>

	<!-- 配置DataSource -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value=http://www.mamicode.com/"oracle.jdbc.driver.OracleDriver" />>
最后:附上dao实现类和userServerImle类的代码

UserServerImpl类

package com.hcj.service.impl;

import com.hcj.dao.UserDao;
import com.hcj.model.User;
import com.hcj.service.UserService;

public class UserServiceImpl implements UserService {
	private UserDao userDao; 
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void save(User user) {
		userDao.save(user);
	}
	
	public UserServiceImpl(){
		
	}
	
	public UserServiceImpl(UserDao userDao){
		this.userDao = userDao;
	}
	

}
dao实现类
package com.hcj.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import com.hcj.dao.UserDao;
import com.hcj.model.User;

public class UserDaoImpl implements UserDao {
	private SessionFactory sessionFactory;
	
	
 	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


	@Override
	public void save(User user){
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try {
			session.save(user);
			tx.commit();
		} catch (Exception e) {
			if(tx != null){
				tx.rollback();
			}
		}finally{
			session.close();
		}
	}

}


Hibernate与spring整合时的整合步骤