spring开发_spring+hibernate
本文内容纲要:
项目结构:
http://www.cnblogs.com/hongten/gallery/image/112469.html
使用的jar包:
hibernate核心安装包:
hibernate3.jar
lib\rquired\*.jar
lib\optional\encache-1.2.3.jar(二级缓存)
lib\test\slf4j-log4j12.jar(hibernate注解安装包)
如下图:
http://www.cnblogs.com/hongten/gallery/image/112470.html
spring安装包:
dist\spring.jar
dist\modules\spring-webmvc-struts.jar
lib\jakarta-commons\commons-loggng.jar
lib\jakarta-commons\commons-dbcp.jar
lib\jakarta-commons\commons-pool.jar
lib\cglib\cglib-nodep-2.1_3.jar
lib\j2ee\common-annotations.jar
lib\log4j-1.2.15.jar
如下图:
http://www.cnblogs.com/hongten/gallery/image/112471.html
/spring+hibernate/src/com/b510/domain/Person.java
1packagecom.b510.domain;
2
3/**
4*Person实体类
5*
6*@authorHongten
7*
8*/
9
10publicclassPersonimplementsjava.io.Serializable{
11
12//Fields
13
14/**
15*版本号
16*/
17privatestaticfinallongserialVersionUID=-47270870639923184L;
18/**
19*id号
20*/
21privateIntegerid;
22/**
23*姓名
24*/
25privateStringname;
26/**
27*年龄
28*/
29privateIntegerage;
30/**
31*性别
32*/
33privateStringsex;
34
35//Constructors
36
37/**defaultconstructor*/
38publicPerson(){
39}
40
41/**minimalconstructor*/
42publicPerson(Stringname){
43this.name=name;
44}
45
46/**fullconstructor*/
47publicPerson(Stringname,Integerage,Stringsex){
48this.name=name;
49this.age=age;
50this.sex=sex;
51}
52
53//Propertyaccessors
54
55publicIntegergetId(){
56returnthis.id;
57}
58
59publicvoidsetId(Integerid){
60this.id=id;
61}
62
63publicStringgetName(){
64returnthis.name;
65}
66
67publicvoidsetName(Stringname){
68this.name=name;
69}
70
71publicIntegergetAge(){
72returnthis.age;
73}
74
75publicvoidsetAge(Integerage){
76this.age=age;
77}
78
79publicStringgetSex(){
80returnthis.sex;
81}
82
83publicvoidsetSex(Stringsex){
84this.sex=sex;
85}
86
87}
/spring+hibernate/src/com/b510/domain/Person.hbm.xml
1<?xmlversion="1.0"encoding="utf-8"?>
2<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
3"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5<hibernate-mapping>
6<classname="com.b510.domain.Person"table="person"catalog="spring">
7<idname="id"type="java.lang.Integer">
8<columnname="id"/>
9<generatorclass="increment"/>
10</id>
11<propertyname="name"type="java.lang.String">
12<columnname="name"length="20"not-null="true"/>
13</property>
14<propertyname="age"type="java.lang.Integer">
15<columnname="age"/>
16</property>
17<propertyname="sex"type="java.lang.String">
18<columnname="sex"length="2"/>
19</property>
20</class>
21</hibernate-mapping>
/spring+hibernate/src/com/b510/service/PersonService.java
1packagecom.b510.service;
2
3importjava.util.List;
4
5importcom.b510.domain.Person;
6
7/**
8*PersonService服务层
9*
10*@authorHongten
11*
12*/
13publicinterfacePersonService{
14
15/**
16*保存Person
17*
18*@paramperson
19*/
20publicabstractvoidsave(Personperson);
21
22/**
23*更新Person
24*
25*@paramperson
26*/
27publicabstractvoidupdate(Personperson);
28
29/**
30*获取Person
31*
32*@paramid
33*@return
34*/
35publicabstractPersongetPerson(Integerid);
36
37/**
38*获取所有Person
39*
40*@return
41*/
42publicabstractList<Person>getPerson();
43
44/**
45*删除指定id的Person
46*
47*@paramid
48*/
49publicabstractvoiddelete(Integerid);
50
51}
/spring+hibernate/src/com/b510/service/impl/PersonServiceBean.java
1packagecom.b510.service.impl;
2
3importjava.util.List;
4
5importjavax.annotation.Resource;
6
7importorg.hibernate.SessionFactory;
8importorg.springframework.transaction.annotation.Propagation;
9importorg.springframework.transaction.annotation.Transactional;
10
11importcom.b510.domain.Person;
12importcom.b510.service.PersonService;
13
14/**
15*使用注解方式进行事务管理
16*
17*@authorHongten
18*
19*/
20@Transactional
21publicclassPersonServiceBeanimplementsPersonService{
22/**
23*通过bean.xml配置文件按名称sessionFactory注入属性sessionFactory,
24*当sessionFactory注入成功后,我们可以得到Session对象
25*/
26@Resource
27privateSessionFactorysessionFactory;
28
29@Override
30publicvoiddelete(Integerid){
31sessionFactory.getCurrentSession().delete(
32sessionFactory.getCurrentSession().load(Person.class,id));
33}
34
35//在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率
36@Override
37@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
38publicPersongetPerson(Integerid){
39return(Person)sessionFactory.getCurrentSession()
40.get(Person.class,id);
41}
42
43//在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率
44@Override
45@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
46@SuppressWarnings("unchecked")
47publicList<Person>getPerson(){
48returnsessionFactory.getCurrentSession().createQuery("fromPerson")
49.list();
50
51}
52
53@Override
54publicvoidsave(Personperson){
55sessionFactory.getCurrentSession().persist(person);
56}
57
58@Override
59publicvoidupdate(Personperson){
60sessionFactory.getCurrentSession().merge(person);
61}
62}
/spring+hibernate/src/com/b510/test/PersonServiceBeanTest.java
1packagecom.b510.test;
2
3importorg.junit.BeforeClass;
4importorg.junit.Test;
5importorg.springframework.context.ApplicationContext;
6importorg.springframework.context.support.ClassPathXmlApplicationContext;
7
8importcom.b510.domain.Person;
9importcom.b510.service.PersonService;
10
11publicclassPersonServiceBeanTest{
12staticPersonServicepersonService;
13
14@BeforeClass
15publicstaticvoidsetUpBeforeClass()throwsException{
16
17try{
18ApplicationContextact=newClassPathXmlApplicationContext(
19"bean.xml");
20personService=(PersonService)act.getBean("personService");
21}catch(Exceptione){
22e.printStackTrace();
23}
24}
25
26@Test
27publicvoidtestSave(){
28personService.save(newPerson("hongten",21,"男"));
29}
30
31@Test
32publicvoidtestUpdate(){
33Personperson=personService.getPerson(2);
34person.setName("hanyuan");
35person.setAge(21);
36person.setSex("男");
37personService.update(person);
38}
39
40@Test
41publicvoidtestGetPersonInteger(){
42Personperson=personService.getPerson(1);
43System.out.println(person.getId()+""+person.getName()+""
44+person.getAge()+""+person.getSex());
45}
46
47@Test
48publicvoidtestGetPerson(){
49java.util.List<Person>list=personService.getPerson();
50System.out.println("*******************");
51for(Personperson:list){
52System.out.println(person.getId()+""+person.getName()+""
53+person.getAge()+""+person.getSex());
54}
55}
56
57@Test
58publicvoidtestDelete(){
59personService.delete(1);
60}
61
62}
/spring+hibernate/src/bean.xml
1<?xmlversion="1.0"encoding="UTF-8"?>
2<beansxmlns="http://www.springframework.org/schema/beans"
3xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
4xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
5xsi:schemaLocation="http://www.springframework.org/schema/beans
6http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
7http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
8http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd
9http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
10<context:annotation-config/>
11
12<!--读取jdbc.properties配置文件-->
13<context:property-placeholderlocation="classpath:jdbc.properties"/>
14
15<!--配置数据源-->
16<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
17destroy-method="close">
18<propertyname="driverClassName"value="${driverClassName}"/>
19<propertyname="url"value="${url}"/>
20<propertyname="username"value="${username}"/>
21<propertyname="password"value="${password}"/>
22<!--连接池启动时的初始值-->
23<propertyname="initialSize"value="${initialSize}"/>
24<!--连接池的最大值-->
25<propertyname="maxActive"value="${maxActive}"/>
26<!--最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止-->
27<propertyname="maxIdle"value="${maxIdle}"/>
28<!--最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请-->
29<propertyname="minIdle"value="${minIdle}"/>
30</bean>
31
32<beanid="sessionFactory"
33class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
34<!--配置SessionFactory所需的数据源,注入上面定义的dataSource-->
35<propertyname="dataSource"ref="dataSource"/>
36
37<!--mappingResources属性用来列出全部映射文件-->
38<propertyname="mappingResources">
39<list>
40<!--配置所有PO映射文件-->
41<value>com/b510/domain/Person.hbm.xml</value>
42</list>
43</property>
44
45<!--定义hibernate的SessionFactory的属性-->
46<propertyname="hibernateProperties">
47<value>
48hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
49hibernate.hbm2ddl.auto=update
50hibernate.show_sql=true
51hibernate.format_sql=true
52hibernate.cache.use_second_level_cache=true
53hibernate.cache.use_query_cache=false
54hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
55</value>
56</property>
57</bean>
58
59<!--配置Hibernate的局部事务管理器,使用HibernateTransactionManager类-->
60<!--该类是PlatformTransactionManager接口对采用Hibernate的特定实现类-->
61<beanid="txManager"
62class="org.springframework.orm.hibernate3.HibernateTransactionManager">
63<propertyname="sessionFactory"ref="sessionFactory"/>
64</bean>
65
66<!--采用注解方式配置事务-->
67<tx:annotation-driventransaction-manager="txManager"/>
68
69<beanid="personService"class="com.b510.service.impl.PersonServiceBean"></bean>
70</beans>
这里我们可以重写占位符配置器:
那么/spring+hibernate/src/bean.xml的另外一种配置方式是:要知道,程序执行是完全相同的。
1<?xmlversion="1.0"encoding="UTF-8"?>
2<beansxmlns="http://www.springframework.org/schema/beans"
3xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
4xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
5xsi:schemaLocation="http://www.springframework.org/schema/beans
6http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
7http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd
8http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd
9http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
10<context:annotation-config/>
11
12<!--
13重写占位符配置器,读取jdbc.properties配置文件
14这时候jdbc.properties配置文件的书写方式如下:
15dataSource.driverClassName=org.gjt.mm.mysql.Driver
16dataSource.url=jdbc\:mysql\://localhost\:3307/spring?useUnicode\=true&characterEncoding\=UTF-8
17dataSource.username=root
18dataSource.password=root
19dataSource.initialSize=1
20dataSource.maxActive=300
21dataSource.maxIdle=2
22dataSource.minIdle=1
23
24dataSource.driverClassName对于dataSource必须是在此xml配置文件中可以找到的bean,
25否则程序会出错。
26-->
27<context:property-overridelocation="classpath:jdbc.properties"/>
28<!--配置数据源-->
29<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
30destroy-method="close">
31</bean>
32
33<beanid="sessionFactory"
34class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
35<!--配置SessionFactory所需的数据源,注入上面定义的dataSource-->
36<propertyname="dataSource"ref="dataSource"/>
37
38<!--mappingResources属性用来列出全部映射文件-->
39<propertyname="mappingResources">
40<list>
41<!--配置所有PO映射文件-->
42<value>com/b510/domain/Person.hbm.xml</value>
43</list>
44</property>
45
46<!--定义hibernate的SessionFactory的属性-->
47<propertyname="hibernateProperties">
48<value>
49hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
50hibernate.hbm2ddl.auto=update
51hibernate.show_sql=true
52hibernate.format_sql=true
53hibernate.cache.use_second_level_cache=true
54hibernate.cache.use_query_cache=false
55hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
56</value>
57</property>
58</bean>
59
60<!--配置Hibernate的局部事务管理器,使用HibernateTransactionManager类-->
61<!--该类是PlatformTransactionManager接口对采用Hibernate的特定实现类-->
62<beanid="txManager"
63class="org.springframework.orm.hibernate3.HibernateTransactionManager">
64<propertyname="sessionFactory"ref="sessionFactory"/>
65</bean>
66
67<!--采用注解方式配置事务-->
68<tx:annotation-driventransaction-manager="txManager"/>
69
70<beanid="personService"class="com.b510.service.impl.PersonServiceBean"></bean>
71</beans>
/spring+hibernate/src/jdbc.properties
1driverClassName=org.gjt.mm.mysql.Driver
2url=jdbc\:mysql\://localhost\:3307/spring?useUnicode\=true&characterEncoding\=UTF-8
3username=root
4password=root
5initialSize=1
6maxActive=300
7maxIdle=2
8minIdle=1
运行结果:
1log4j:WARNNoappenderscouldbefoundforlogger(org.springframework.context.support.ClassPathXmlApplicationContext).
2log4j:WARNPleaseinitializethelog4jsystemproperly.
3Hibernate:
4select
5max(id)
6from
7person
8Hibernate:
9insert
10into
11spring.person
12(name,age,sex,id)
13values
14(?,?,?,?)
15Hibernate:
16select
17person0_.idasid0_0_,
18person0_.nameasname0_0_,
19person0_.ageasage0_0_,
20person0_.sexassex0_0_
21from
22spring.personperson0_
23where
24person0_.id=?
25Hibernate:
26select
27person0_.idasid0_0_,
28person0_.nameasname0_0_,
29person0_.ageasage0_0_,
30person0_.sexassex0_0_
31from
32spring.personperson0_
33where
34person0_.id=?
35Hibernate:
36select
37person0_.idasid0_,
38person0_.nameasname0_,
39person0_.ageasage0_,
40person0_.sexassex0_
41from
42spring.personperson0_
43*******************
442hanyuan21男
453hongten21男
46Hibernate:
47select
48person0_.idasid0_0_,
49person0_.nameasname0_0_,
50person0_.ageasage0_0_,
51person0_.sexassex0_0_
52from
53spring.personperson0_
54where
55person0_.id=?
本文内容总结:
原文链接:https://www.cnblogs.com/hongten/archive/2012/03/10/java_spring_hibernate.html