`

spring整合hibernate

    博客分类:
  • j2ee
 
阅读更多

1. Spring 整合 Hibernate 整合什么 ?
1). 有 IOC 容器来管理 Hibernate 的 SessionFactory
2). 让 Hibernate 使用上 Spring 的声明式事务


2. 整合步骤:

1). 加入 hibernate
①. jar 包
②. 编写PO对象,用hibernate注解创建表


2). 加入 Spring
①. jar 包
②. 加入 Spring 的配置文件
3). 整合.

3. 编写代码

 

 

 

1.写Bean包里面的Po包里的Po对象,并用hibernate注解创建表。

po

 

package com.sysmaster.po;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name="T_People")
public class PeoplePO {
	private int pid;
	private String name;
	private Date birthday;
	
	@Id
	@GeneratedValue
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	@Column(length=10)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Temporal(TemporalType.DATE)
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}



2.编写Dao层和Impl

dao

 

package com.sysmaster.dao;

import java.io.Serializable;
import java.util.List;

public interface IGenericDAO<Obj,Id extends Serializable>{
	public boolean addObj(Obj obj);
	public boolean uptObj(Obj obj);
	public boolean delObj(Obj obj);
	public Obj getObj(Id id);
	public List<Obj> getObjs(String hql);
}


impl

 

package com.sysmaster.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.sysmaster.dao.IGenericDAO;

@Repository
public abstract class GenericDAOImpl<Obj,Id extends Serializable> implements IGenericDAO<Obj,Id>{
	
	@Resource
	private SessionFactory sessionFactory;
	
	private Class<Obj> clzz;

	@SuppressWarnings("unchecked")
	public GenericDAOImpl(){
		clzz=(Class<Obj>)((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public boolean addObj(Obj obj) {
		boolean flag = false;
		try{
		//	Session session = sessionFactory.openSession();
			Session session = sessionFactory.getCurrentSession();
		//	session.beginTransaction();
			session.persist(obj);
		//	session.getTransaction().commit();
		//	session.close();
			flag = true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		return flag;
	}

	public boolean uptObj(Obj obj) {
		boolean flag = false;
		try{
			Session session = sessionFactory.getCurrentSession();
		//	Session session = sessionFactory.openSession();
		//	session.beginTransaction();
			session.update(obj);
		//	session.getTransaction().commit();
		//	session.close();
			flag = true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		return flag;
	}

	public boolean delObj(Obj obj) {
		boolean flag = false;
		try{
		//	Session session = sessionFactory.openSession();
			Session session = sessionFactory.getCurrentSession();
		//	session.beginTransaction();
			session.delete(obj);
		//	session.getTransaction().commit();
		//	session.close();
			flag = true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		return flag;
	}

	@SuppressWarnings("unchecked")
	public Obj getObj(Id id) {
		Obj obj = null;
		try{
	//		Session session = sessionFactory.openSession();
			Session session = sessionFactory.getCurrentSession();
	//		session.beginTransaction();
			obj = (Obj)session.get(clzz, id);
	//		session.getTransaction().commit();
	//		session.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		return obj;
	}

	@SuppressWarnings("unchecked")
	public List<Obj> getObjs(String hql) {
		List<Obj> objList = null;
		try{
			Session session = sessionFactory.getCurrentSession();
		//	session.beginTransaction();
			Query query = session.createQuery(hql);
			objList = query.list();
		//	session.getTransaction().commit();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

		return objList;
	}

}


2.bo

 

package com.sysmaster.bo;


public class PeopleBO {
	private int pid;
	private String name;
	private int age;
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}


4. service层

 

package com.sysmaster.service;

import com.sysmaster.bo.PeopleBO;

public interface IPeopleService {
	public boolean addPeople(PeopleBO people);
	public boolean uptPeople(PeopleBO people);
	public boolean delPeople(PeopleBO people);
	public PeopleBO getPeople(int pid);
}


4.ServiceImpl

 

package com.sysmaster.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sysmaster.bo.PeopleBO;
import com.sysmaster.dao.IPeopleDAO;
import com.sysmaster.po.PeoplePO;
import com.sysmaster.service.IPeopleService;

@Service("peopleService")
//事物的注解
@Transactional 
public class PeopleServiceImpl implements IPeopleService{

	@Resource
	private IPeopleDAO peopleDAO;
	
//	public PeopleServiceImpl()
//	{
//		peopleDAO = new PeopleDAOImpl();
//	}
	
	@SuppressWarnings("deprecation")
	public boolean addPeople(PeopleBO people) {
		PeoplePO peoplePO = new PeoplePO();
		
		BeanUtils.copyProperties(people, peoplePO);
		
		//计算出生日期
		Date date = new Date();
		date.setYear(date.getYear()-people.getAge());
		peoplePO.setBirthday(date);
		
		boolean flag = peopleDAO.addObj(peoplePO);
		return flag;
	}

	@SuppressWarnings("deprecation")
	public boolean uptPeople(PeopleBO people) {
		PeoplePO peoplePO = peopleDAO.getObj(people.getPid());
		BeanUtils.copyProperties(people, peoplePO,new String[]{"pid"});
		//计算出生日期
		Date date = new Date();
		date.setYear(date.getYear()-people.getAge());
		peoplePO.setBirthday(date);
		
		boolean flag = peopleDAO.uptObj(peoplePO);
		return flag;
	}

	public boolean delPeople(PeopleBO people) {
		boolean flag = false;
		PeoplePO peoplePO = peopleDAO.getObj(people.getPid());
		if(peoplePO!=null)
			flag = peopleDAO.delObj(peoplePO);
		return flag;
	}

	@SuppressWarnings("deprecation")
	public PeopleBO getPeople(int pid) {
		PeoplePO peoplePO = peopleDAO.getObj(pid);
		PeopleBO people = new PeopleBO();
		
		BeanUtils.copyProperties(peoplePO, people);
		
		people.setAge(new Date().getYear() - peoplePO.getBirthday().getYear());
		
		return people;
	}
	
}

 

5.配置Spring.xml

 

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/tx
			http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/aop
			http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
           
    <tx:annotation-driven transaction-manager="transactionManager"/>
	<!-- 配置自动扫描的包: 需要加入 aop 对应的包 -->
	<context:component-scan base-package="com.hmx"/>

	<!-- 导入配置文件  -->
	<context:property-placeholder location="classpath:config/database/mysql.properties"/>

	<!-- 配置c3p0  -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="${driverClass}"/>
		<property name="jdbcUrl" value="${jdbcUrl}"/>
		<property name="properties">
            <props>
                <prop key="c3p0.acquire_increment">${c3p0.acquire_increment}</prop>
                <prop key="c3p0.idle_test_period">${c3p0.idle_test_period}</prop>
                <prop key="c3p0.timeout">${c3p0.timeout}</prop>
                <prop key="c3p0.max_size">${c3p0.max_size}</prop>
                <prop key="c3p0.max_statements">${c3p0.max_statements}</prop>
                <prop key="c3p0.min_size">${c3p0.min_size}</prop>
                <prop key="user">${user}</prop> 
                <prop key="password">${password}</prop>
            </props>
		</property>
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 配置数据源  -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 配置hibernate原生属性  -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="current_session_context_class">${current_session_context_class}</prop>
			</props>
		</property>
		<!-- 扫描PO包里面的映射文件,只能扫描PO包,PO下面的子包不会扫描  -->
		<property name="packagesToScan" value="com.hmx.bean.po"/>
	</bean>
	
	<!-- 配置Spring的声明式事物 @Transactional注解要配置在ServiceImpl上 -->
	<!-- 1.配置事物管理器-->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        	<property name="sessionFactory" ref="sessionFactory" />
       </bean>
</beans>


6.数据库配置文件。c3p0

mysql

 

#数据库连接类
driverClass = com.mysql.jdbc.Driver
#连接资源
jdbcUrl = jdbc\:mysql\://127.0.0.1\:3306/hmx?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
#用户名
user = root
#密码
password = 123456
#当连接池里面的连接用完的时候,C3P0一下获取的新的连接数
c3p0.acquire_increment = 2
#每隔120秒检查连接池里的空闲连接,单位是秒
c3p0.idle_test_period = 120
#获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒
c3p0.timeout = 1000
#最大连接数
c3p0.max_size = 100
#最大的PreparedStatement的数量
c3p0.max_statements = 100
#最小连接数
c3p0.min_size = 20
#每次都验证连接是否可用
c3p0.validate = true

#数据库方言
hibernate.dialect = org.hibernate.dialect.MySQLDialect
#连接池大小
hibernate.connection.pool_size = 5
#是否自动生成表
hibernate.hbm2ddl.auto = update
#是否格式化SQL
hibernate.format_sql = true
#是否显示SQL
hibernate.show_sql = true
#设定会话的线程绑定
current_session_context_class = thread


oracle

。。。。。

 



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics