(三十三)利用MyEclipse整合spring与Hibernate

在整合操作之前,一定要保证如下环境的准备就绪:

        mysql数据环境正常;

        MyEclipse里面配置的Datavase可以正常使用;

1.首先为项目添加spring支持.(一定要先添加spring支持);

        在添加Spring支持的时候一定要选择好添加持久化开发包的支持;


            在配置的orm的开发包里面包含有Hiberante整合,JDO整合,Ibatis整合等操作.如果现在需要其他实体层开发框架,需要再额外配置新的开发包;

2.为项目添加Hiberante支持

        如果Hibernate由spring负责管理,那么不再需要HiberanteSessionFactory工具类生成

随后SessionFactory交给Spring进行管理,但是需要生成hiberante.cfg.xml文件,



3.修改hiberante.cfg.xml文件;

    在此文件里面重点配置的是要使用的方言以及相关的属性,比如显示sql,格式化sql,以及二级缓存的配置

<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>


<session-factory>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>


</session-factory>


</hibernate-configuration>

4.建立一个database.properties的文件,这个文件用于保存所有的数据库的连接信息;

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/aaa
db.user=root
db.password=123456
pool.max=1
pool.min=1
pool.init=10
pool.idle=20

5.配置applicationContext.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:p="http://www.springframework.org/schema/p"
	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-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	<!-- 配置annotation的操作 -->
		<context:annotation-config/>
		<context:component-scan base-package="cn.zwb"/>
		<!-- 配置数据连接操作 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="driverClass" value="${db.driver}"/><!-- 驱动程序 -->
			<property name="jdbcUrl" value="${db.url}"/>  <!-- 连接地址 -->
			<property name="user" value="${db.user}" />
			<property name="password" value="${db.password}" />
			<property name="maxPoolSize" value="${pool.max}" /><!-- 最大可用连接数 -->
			<property name="minPoolSize" value="${pool.min}" /><!-- 最小维持的连接数-->
			<property name="initialPoolSize" value="${pool.init}" /><!-- 初始化连接数-->
			<property name="maxIdleTime" value="${pool.idle}" />  <!--最大等待连接-->
	</bean>
		<!-- 配置Hiberante的相关开发环境 sessionFactory可以打开Session -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="configLocation"
			value="classpath:hibernate.cfg.xml">
		</property>
			<!-- 引用数据库 -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
		<!-- 配置事务处理,所有的事务都采用AOP的方式,本处只是声明SessionFactory要进行事务控制 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 进入到了事务的配置声明 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 定义一切与服务层有关的控制方法名称,只要是使用了特定的名称那么就会自动处理事务 -->
		<tx:attributes>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="edit*" propagation="REQUIRED"/>
			<tx:method name="change*" propagation="REQUIRED"/>
			<tx:method name="remove*" propagation="REQUIRED"/>
			<tx:method name="login*" propagation="REQUIRED"/>
			<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="list*" propagation="REQUIRED" read-only="true"/>
			<tx:method name="*" propagation="REQUIRED" read-only="true"/>
			
		</tx:attributes>
	</tx:advice>
	<!-- 定义事务的切入点 -->
	<aop:config expose-proxy="true">
		<aop:pointcut expression="execition(* cn.zwb..service.*.*(..))" id="pointcut"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
	</aop:config>
</beans>
        如果此时将Hiberante交给了Spring管理,那么所有的数据库关闭操作都spring负责

6.生成News.java文件的POJO类,利用Annotation注解方式完成;

package cn.zwb.pojo;

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;

/**
 * Newss entity. @author MyEclipse Persistence Tools
 */
@SuppressWarnings("serial")
@Entity
@Table(name = "newss", catalog = "aaa")

public class Newss implements java.io.Serializable {

	// Fields

	private Integer nid;
	private String title;
	private Date pubdate;
	private String content;

	// Constructors

	/** default constructor */
	public Newss() {
	}

	/** full constructor */
	public Newss(String title, Date pubdate, String content) {
		this.title = title;
		this.pubdate = pubdate;
		this.content = content;
	}

	// Property accessors
	@Id
	@GeneratedValue

	@Column(name = "nid", unique = true, nullable = false)

	public Integer getNid() {
		return this.nid;
	}

	public void setNid(Integer nid) {
		this.nid = nid;
	}

	@Column(name = "title", length = 50)

	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "pubdate", length = 10)

	public Date getPubdate() {
		return this.pubdate;
	}

	public void setPubdate(Date pubdate) {
		this.pubdate = pubdate;
	}

	@Column(name = "content", length = 65535)

	public String getContent() {
		return this.content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}

7.定义DAO层

package cn.zwb.dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import cn.zwb.dao.INewsDAO;
import cn.zwb.pojo.Newss;
@Component
public class NewsDAOimpl implements INewsDAO{
	//将applicationContext里面配置的文件注入到此属性;
	@Resource
	private SessionFactory sessionfactory;
	@Override
	public boolean doCreate(Newss vo) throws Exception {
		return this.sessionfactory.getCurrentSession().save(vo)!=null;
	}

	@Override
	public boolean doUpdate(Newss vo) throws Exception {
		String hql="UPDATE Newss SET title=?,pubdate?,content=?";
		org.hibernate.Query createQuery = this.sessionfactory.getCurrentSession().createQuery(hql);
		createQuery.setParameter(0, vo.getTitle());
		createQuery.setParameter(1, vo.getContent());
		createQuery.setParameter(2, vo.getPubdate());
		return createQuery.executeUpdate()>0;
	}

	@Override
	public boolean doRemoveBatch(Set<Integer> ids) throws Exception {
		StringBuffer buffer=new StringBuffer();
		buffer.append("DELETE FROM Newss WHERE NID IN(");
		Iterator<Integer> iter=ids.iterator();
		while(iter.hasNext()){
			buffer.append(iter.next()).append(",");
		}
		buffer.delete(buffer.length()-1, buffer.length()).append(")");
		return this.sessionfactory.getCurrentSession().createQuery(buffer.toString()).executeUpdate()>0; 
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Newss> findAll() throws Exception {
		
		Criteria criteria=this.sessionfactory.getCurrentSession().createCriteria(Newss.class);
		return criteria.list();
	}
	@Override
	public List<Newss> fandAllSplit(String column, String keyWord, Integer curremPage, Integer lineSize)
			throws Exception {
		String hql="FROM Newss AS n WHERE n."+column+ "LIKE ?";
		org.hibernate.Query createQuery = this.sessionfactory.getCurrentSession().createQuery(hql);
		createQuery.setParameter(0, "%"+keyWord+"%");
		createQuery.setFirstResult(curremPage-1*lineSize);
		createQuery.setMaxResults(lineSize);
		return createQuery.list();
	}

	@Override
	public Integer getAllCount(String column, String keyWord) throws Exception {
		String hql="SELECT COUNT(*) FROM NEWS n WHERE n."+column+"LIKE ?";
		org.hibernate.Query createQuery = this.sessionfactory.getCurrentSession().createQuery(hql);
		createQuery.setParameter(0, "%"+keyWord+"%");
		Long count=(Long)createQuery.uniqueResult();
		return count.intValue();
	}

}

8.定义业务层--INewsService

        所有的事务控制都在业务层上;切入点也是业务层切入点

package cn.zwb.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.zwb.dao.INewsDAO;
import cn.zwb.pojo.Newss;
import cn.zwb.service.INewService;
@Service
public class NewsServiceImpl implements INewService {
	@Resource
	private INewsDAO newDAO;
	@Override
	public boolean insert(Newss vo) throws Exception {
		return this.newDAO.doCreate(vo);
	}

	@Override
	public boolean update(Newss vo) throws Exception {

		return this.newDAO.doUpdate(vo);
	}

	@Override
	public boolean delete(Set<Integer> ids) throws Exception {
		if(ids.size()==0) return false;
		return this.newDAO.doRemoveBatch(ids);
	}

	@Override
	public List<Newss> list() throws Exception {
		// TODO Auto-generated method stub
		return this.newDAO.findAll();
	}

	@Override
	public Map<String, Object> list(String column, String keyWord, Integer curremPage, Integer lineSize) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("allNews",this.newDAO.fandAllSplit(column, keyWord, curremPage, lineSize)) ;
		map.put("newsCount", this.newDAO.getAllCount(column, keyWord));
		
		return map;
	}
	
}

9.使用junit测试程序  

package cn.zwb.test;




import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import cn.zwb.pojo.Newss;
import cn.zwb.service.INewsService;
import cn.zwb.service.impl.NewsServiceImpl;
import junit.framework.TestCase;


public class INewServiceTest {
	static ApplicationContext ctx;
	static{
		ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	@Test
	public void testInsert()  {
		INewsService service=ctx.getBean("newsServiceImpl",INewsService.class);
		Newss vo=new Newss();
		vo.setTitle("这是标题"+System.currentTimeMillis());
		vo.setPubdate(new Date());
		vo.setContent("内容!!!");
		try {
			TestCase.assertEquals(service.insert(vo), true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Test
	public void testUpdate() {
		INewsService service=ctx.getBean("newsServiceImpl",INewsService.class);
		Newss vo=new Newss();
		vo.setNid(6);
		vo.setTitle("lalalallalalaupdate"+System.currentTimeMillis());
		vo.setPubdate(new Date());
		vo.setContent("内容!!!");
		try {
			TestCase.assertEquals(service.update(vo), true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Test
	public void testDelete() {
		INewsService service=ctx.getBean("newsServiceImpl",INewsService.class);
		Set<Integer> set=new HashSet<Integer>();
		set.add(1);
		set.add(3);
		set.add(9);
		try {
			TestCase.assertEquals(service.delete(set), true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Test
	public void testList() {
		INewsService service=ctx.getBean("newsServiceImpl",INewsService.class);
		try {
			List<Newss> news=service.list();
			System.out.println(news);
			TestCase.assertTrue(news.size()>0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Test
	public void testListStringStringIntegerInteger() {
		INewsService service=ctx.getBean("newsServiceImpl",INewsService.class);
		try {
			
			Map<String,Object> news= service.list("title", "", 1,5);
			System.out.println(news);
			TestCase.assertTrue(news.size()==2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值