码迷,mamicode.com
首页 > 编程语言 > 详细

spring+hibernate注解配置实例

时间:2015-07-31 23:37:08      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

简单的spring3.2.9和hibernate3的集成配置,有demo供下载。shTest下载

第一步

jdbc.properties配置

driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/shtest
username=root
password=123456
prototypeCount=1
maxActive=100   
houseKeepingSleepTime=60000
minimumConnectionCount=2
maximumConnectionCount=8
simultaneousBuildThrottle=4
alias=springProxool

第二步

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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           ">
	<context:annotation-config/>  
	<context:component-scan base-package="com.cqut"/>  
	
    <!-- 指定数据库配置文件的位置 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
     <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
            <property name="driver" value="${driverClassName}"/>
            <property name="driverUrl" value="${url}"/>
            <property name="user" value="${username}"/>
            <property name="password" value="${password}"/>
            <!-- 测试的SQL执行语句 -->
           <property name="houseKeepingTestSql" value="select CURRENT_DATE"/>
            <!-- 最少保持的空闲连接数 (默认2个) -->
             <property name="prototypeCount" value="${prototypeCount}"/>
            <!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒) -->
            <property name="houseKeepingSleepTime" value="${houseKeepingSleepTime}"/>
            <!-- 最大活动时间(超过此时间线程将被kill,默认为5分钟) 
             <property name="maximumActiveTime" value="${maximumActiveTime}"/>-->
            <!-- 连接最长时间(默认为4个小时) 
            <property name="maximumConnectionLifetime" value="${maximumConnectionLifetime}"/>-->
            <!-- 最小连接数 (默认2个) -->
            <property name="minimumConnectionCount" value="${minimumConnectionCount}"/>
            <!-- 最大连接数 (默认5个) -->
            <property name="maximumConnectionCount" value="${maximumConnectionCount}"/>
            <!--统计
            <property name="statistics" value="${statistics}"/> -->
            <!-- 别名 -->
             <property name="alias" value="${alias}"/>
            <!--同时最大连接数 -->
            <property name="simultaneousBuildThrottle" value="${simultaneousBuildThrottle}"/>
     </bean>
     
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		
		<property name="packagesToScan">
		<list>
            <value>com.cqut.entity</value>
        </list>
		</property>
		
		
		<!--
		<property name="annotatedPackages">
			<list>
				<value>com.cqut.entity.Department</value>
				<value>com.cqut.entity.MyClass</value>
				<value>com.cqut.entity.Student</value>
			</list>
		</property>
		-->
		
		<property name="hibernateProperties">
           <props>
		    <!--  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  -->
		     <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> 
		     <prop key="hibernate.show_sql">true</prop>
			 <prop key="hiberante.format_sql">true</prop>
		     <prop key="hibernate.hbm2ddl.auto">update</prop>
           </props>
       </property>	
	</bean>
	
	<bean id="baseDao" class="com.cqut.dao.BaseDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
       <property name="sessionFactory"><ref local="sessionFactory" /></property>
    </bean>
    	<!--  通过注解的方式,进行实物管理  -->
   <tx:annotation-driven transaction-manager="transactionManager"/>
    
    
       
</beans>

第三步

新建实体,配置注解

package com.cqut.entity;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Student implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue
	private int stuId;
	
	@Column(length=20,nullable=false)
	private String name;
	@Column
	private int age;
	
	@ManyToOne(cascade=CascadeType.ALL)
	private MyClass myClass;

<span style="white-space:pre">	</span>//get set方法省略
	
}

第四步

配置basedao,直接继承hibernate的daosupport

package com.cqut.dao;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


public class BaseDao extends HibernateDaoSupport{

}

第五步

配置studentDao,及添加注解和配置事务

package com.cqut.dao;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.cqut.entity.Student;

@Transactional
@Component("studentDao")
public class StudentDao {
	@Resource
	private BaseDao baseDao;

	public BaseDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	} 
	@Transactional(rollbackFor={Exception.class})
	public void add(Student student) throws Exception{
		baseDao.getHibernateTemplate().save(student);
		throw new Exception("异常");
	}
	public List<Student> getStudents(String hql){
		
		return (List<Student>)baseDao.getHibernateTemplate().find(hql);
	}

}
注意:“异常”是为了测试事务的回滚

第六步

测试

package com.cqut.test;

import java.util.List;

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

import com.cqut.dao.StudentDao;
import com.cqut.entity.Student;

public class Test {

	public static void main(String[] args) {
		Student student = new Student();
		
		student.setName("张三");
		student.setAge(19);
		
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentDao studentDao = context.getBean(StudentDao.class);
		
		try {
			studentDao.add(student);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		List<Student> students = studentDao.getStudents("from Student");
		for (Student student2 : students) {
			System.out.println(student2.getName());
		}
		
	}

}

最后是web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SHTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  
  <!-- proxool数据库统计 -->
	<servlet>
		<servlet-name>Admin</servlet-name>
		<servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>Admin</servlet-name>
		<url-pattern>/adminProxool</url-pattern>
	</servlet-mapping>
	<!-- spring 启动 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- spring 字符过滤 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>



版权声明:本文为博主原创文章,未经博主允许不得转载。

spring+hibernate注解配置实例

标签:

原文地址:http://blog.csdn.net/w171203757/article/details/47176251

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!