转自:http://www.cnblogs.com/hongten/archive/2012/03/10/java_spring_hibernate.html
项目结构:
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
1 package com.b510.domain;
2
3 /**
4 * Person实体类
5 *
6 * @author Hongten
7 *
8 */
9
10 public class Person implements java.io.Serializable {
11
12 // Fields
13
14 /**
15 * 版本号
16 */
17 private static final long serialVersionUID = -47270870639923184L;
18 /**
19 * id号
20 */
21 private Integer id;
22 /**
23 * 姓名
24 */
25 private String name;
26 /**
27 * 年龄
28 */
29 private Integer age;
30 /**
31 * 性别
32 */
33 private String sex;
34
35 // Constructors
36
37 /** default constructor */
38 public Person() {
39 }
40
41 /** minimal constructor */
42 public Person(String name) {
43 this.name = name;
44 }
45
46 /** full constructor */
47 public Person(String name, Integer age, String sex) {
48 this.name = name;
49 this.age = age;
50 this.sex = sex;
51 }
52
53 // Property accessors
54
55 public Integer getId() {
56 return this.id;
57 }
58
59 public void setId(Integer id) {
60 this.id = id;
61 }
62
63 public String getName() {
64 return this.name;
65 }
66
67 public void setName(String name) {
68 this.name = name;
69 }
70
71 public Integer getAge() {
72 return this.age;
73 }
74
75 public void setAge(Integer age) {
76 this.age = age;
77 }
78
79 public String getSex() {
80 return this.sex;
81 }
82
83 public void setSex(String sex) {
84 this.sex = sex;
85 }
86
87 }
/spring+hibernate/src/com/b510/domain/Person.hbm.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5 <hibernate-mapping>
6 <class name="com.b510.domain.Person" table="person" catalog="spring">
7 <id name="id" type="java.lang.Integer">
8 <column name="id" />
9 <generator class="increment" />
10 </id>
11 <property name="name" type="java.lang.String">
12 <column name="name" length="20" not-null="true" />
13 </property>
14 <property name="age" type="java.lang.Integer">
15 <column name="age" />
16 </property>
17 <property name="sex" type="java.lang.String">
18 <column name="sex" length="2" />
19 </property>
20 </class>
21 </hibernate-mapping>
/spring+hibernate/src/com/b510/service/PersonService.java
1 package com.b510.service;
2
3 import java.util.List;
4
5 import com.b510.domain.Person;
6
7 /**
8 * PersonService服务层
9 *
10 * @author Hongten
11 *
12 */
13 public interface PersonService {
14
15 /**
16 * 保存Person
17 *
18 * @param person
19 */
20 public abstract void save(Person person);
21
22 /**
23 * 更新Person
24 *
25 * @param person
26 */
27 public abstract void update(Person person);
28
29 /**
30 * 获取Person
31 *
32 * @param id
33 * @return
34 */
35 public abstract Person getPerson(Integer id);
36
37 /**
38 * 获取所有Person
39 *
40 * @return
41 */
42 public abstract List<Person> getPerson();
43
44 /**
45 * 删除指定id的Person
46 *
47 * @param id
48 */
49 public abstract void delete(Integer id);
50
51 }
/spring+hibernate/src/com/b510/service/impl/PersonServiceBean.java
1 package com.b510.service.impl;
2
3 import java.util.List;
4
5 import javax.annotation.Resource;
6
7 import org.hibernate.SessionFactory;
8 import org.springframework.transaction.annotation.Propagation;
9 import org.springframework.transaction.annotation.Transactional;
10
11 import com.b510.domain.Person;
12 import com.b510.service.PersonService;
13
14 /**
15 * 使用注解方式进行事务管理
16 *
17 * @author Hongten
18 *
19 */
20 @Transactional
21 public class PersonServiceBean implements PersonService {
22 /**
23 * 通过bean.xml配置文件按名称sessionFactory注入属性sessionFactory,
24 * 当sessionFactory注入成功后,我们可以得到Session对象
25 */
26 @Resource
27 private SessionFactory sessionFactory;
28
29 @Override
30 public void delete(Integer id) {
31 sessionFactory.getCurrentSession().delete(
32 sessionFactory.getCurrentSession().load(Person.class, id));
33 }
34
35 // 在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率
36 @Override
37 @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
38 public Person getPerson(Integer id) {
39 return (Person) sessionFactory.getCurrentSession()
40 .get(Person.class, id);
41 }
42
43 // 在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率
44 @Override
45 @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
46 @SuppressWarnings("unchecked")
47 public List<Person> getPerson() {
48 return sessionFactory.getCurrentSession().createQuery("from Person")
49 .list();
50
51 }
52
53 @Override
54 public void save(Person person) {
55 sessionFactory.getCurrentSession().persist(person);
56 }
57
58 @Override
59 public void update(Person person) {
60 sessionFactory.getCurrentSession().merge(person);
61 }
62 }
/spring+hibernate/src/com/b510/test/PersonServiceBeanTest.java
1 package com.b510.test;
2
3 import org.junit.BeforeClass;
4 import org.junit.Test;
5 import org.springframework.context.ApplicationContext;
6 import org.springframework.context.support.ClassPathXmlApplicationContext;
7
8 import com.b510.domain.Person;
9 import com.b510.service.PersonService;
10
11 public class PersonServiceBeanTest {
12 static PersonService personService;
13
14 @BeforeClass
15 public static void setUpBeforeClass() throws Exception {
16
17 try {
18 ApplicationContext act = new ClassPathXmlApplicationContext(
19 "bean.xml");
20 personService = (PersonService) act.getBean("personService");
21 } catch (Exception e) {
22 e.printStackTrace();
23 }
24 }
25
26 @Test
27 public void testSave() {
28 personService.save(new Person("hongten", 21, "男"));
29 }
30
31 @Test
32 public void testUpdate() {
33 Person person =personService.getPerson(2);
34 person.setName("hanyuan");
35 person.setAge(21);
36 person.setSex("男");
37 personService.update(person);
38 }
39
40 @Test
41 public void testGetPersonInteger() {
42 Person person = personService.getPerson(1);
43 System.out.println(person.getId() + " " + person.getName() + " "
44 + person.getAge() + " " + person.getSex());
45 }
46
47 @Test
48 public void testGetPerson() {
49 java.util.List<Person> list = personService.getPerson();
50 System.out.println("*******************");
51 for (Person person : list) {
52 System.out.println(person.getId() + " " + person.getName() + " "
53 + person.getAge() + " " + person.getSex());
54 }
55 }
56
57 @Test
58 public void testDelete() {
59 personService.delete(1);
60 }
61
62 }
/spring+hibernate/src/bean.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
10 <context:annotation-config />
11
12 <!-- 读取jdbc.properties配置文件 -->
13 <context:property-placeholder location="classpath:jdbc.properties" />
14
15 <!-- 配置数据源 -->
16 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
17 destroy-method="close">
18 <property name="driverClassName" value="${driverClassName}" />
19 <property name="url" value="${url}" />
20 <property name="username" value="${username}" />
21 <property name="password" value="${password}" />
22 <!-- 连接池启动时的初始值 -->
23 <property name="initialSize" value="${initialSize}" />
24 <!-- 连接池的最大值 -->
25 <property name="maxActive" value="${maxActive}" />
26 <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
27 <property name="maxIdle" value="${maxIdle}" />
28 <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
29 <property name="minIdle" value="${minIdle}" />
30 </bean>
31
32 <bean id="sessionFactory"
33 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
34 <!-- 配置SessionFactory所需的数据源,注入上面定义的dataSource -->
35 <property name="dataSource" ref="dataSource" />
36
37 <!-- mappingResources属性用来列出全部映射文件 -->
38 <property name="mappingResources">
39 <list>
40 <!-- 配置所有PO映射文件 -->
41 <value>com/b510/domain/Person.hbm.xml</value>
42 </list>
43 </property>
44
45 <!-- 定义hibernate的SessionFactory的属性 -->
46 <property name="hibernateProperties">
47 <value>
48 hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
49 hibernate.hbm2ddl.auto=update
50 hibernate.show_sql=true
51 hibernate.format_sql=true
52 hibernate.cache.use_second_level_cache=true
53 hibernate.cache.use_query_cache=false
54 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
55 </value>
56 </property>
57 </bean>
58
59 <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->
60 <!-- 该类是PlatformTransactionManager接口对采用Hibernate的特定实现类 -->
61 <bean id="txManager"
62 class="org.springframework.orm.hibernate3.HibernateTransactionManager">
63 <property name="sessionFactory" ref="sessionFactory" />
64 </bean>
65
66 <!-- 采用注解方式配置事务 -->
67 <tx:annotation-driven transaction-manager="txManager" />
68
69 <bean id="personService" class="com.b510.service.impl.PersonServiceBean"></bean>
70 </beans>
这里我们可以重写占位符配置器:
那么/spring+hibernate/src/bean.xml的另外一种配置方式是:要知道,程序执行是完全相同的。
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
10 <context:annotation-config />
11
12 <!--
13 重写占位符配置器,读取jdbc.properties配置文件
14 这时候jdbc.properties配置文件的书写方式如下:
15 dataSource.driverClassName=org.gjt.mm.mysql.Driver
16 dataSource.url=jdbc\:mysql\://localhost\:3307/spring?useUnicode\=true&characterEncoding\=UTF-8
17 dataSource.username=root
18 dataSource.password=root
19 dataSource.initialSize=1
20 dataSource.maxActive=300
21 dataSource.maxIdle=2
22 dataSource.minIdle=1
23
24 dataSource.driverClassName对于dataSource必须是在此xml配置文件中可以找到的bean,
25 否则程序会出错。
26 -->
27 <context:property-override location="classpath:jdbc.properties" />
28 <!-- 配置数据源 -->
29 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
30 destroy-method="close">
31 </bean>
32
33 <bean id="sessionFactory"
34 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
35 <!-- 配置SessionFactory所需的数据源,注入上面定义的dataSource -->
36 <property name="dataSource" ref="dataSource" />
37
38 <!-- mappingResources属性用来列出全部映射文件 -->
39 <property name="mappingResources">
40 <list>
41 <!-- 配置所有PO映射文件 -->
42 <value>com/b510/domain/Person.hbm.xml</value>
43 </list>
44 </property>
45
46 <!-- 定义hibernate的SessionFactory的属性 -->
47 <property name="hibernateProperties">
48 <value>
49 hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
50 hibernate.hbm2ddl.auto=update
51 hibernate.show_sql=true
52 hibernate.format_sql=true
53 hibernate.cache.use_second_level_cache=true
54 hibernate.cache.use_query_cache=false
55 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
56 </value>
57 </property>
58 </bean>
59
60 <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->
61 <!-- 该类是PlatformTransactionManager接口对采用Hibernate的特定实现类 -->
62 <bean id="txManager"
63 class="org.springframework.orm.hibernate3.HibernateTransactionManager">
64 <property name="sessionFactory" ref="sessionFactory" />
65 </bean>
66
67 <!-- 采用注解方式配置事务 -->
68 <tx:annotation-driven transaction-manager="txManager" />
69
70 <bean id="personService" class="com.b510.service.impl.PersonServiceBean"></bean>
71 </beans>
/spring+hibernate/src/jdbc.properties
1 driverClassName=org.gjt.mm.mysql.Driver
2 url=jdbc\:mysql\://localhost\:3307/spring?useUnicode\=true&characterEncoding\=UTF-8
3 username=root
4 password=root
5 initialSize=1
6 maxActive=300
7 maxIdle=2
8 minIdle=1
运行结果:
1 log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
2 log4j:WARN Please initialize the log4j system properly.
3 Hibernate:
4 select
5 max(id)
6 from
7 person
8 Hibernate:
9 insert
10 into
11 spring.person
12 (name, age, sex, id)
13 values
14 (?, ?, ?, ?)
15 Hibernate:
16 select
17 person0_.id as id0_0_,
18 person0_.name as name0_0_,
19 person0_.age as age0_0_,
20 person0_.sex as sex0_0_
21 from
22 spring.person person0_
23 where
24 person0_.id=?
25 Hibernate:
26 select
27 person0_.id as id0_0_,
28 person0_.name as name0_0_,
29 person0_.age as age0_0_,
30 person0_.sex as sex0_0_
31 from
32 spring.person person0_
33 where
34 person0_.id=?
35 Hibernate:
36 select
37 person0_.id as id0_,
38 person0_.name as name0_,
39 person0_.age as age0_,
40 person0_.sex as sex0_
41 from
42 spring.person person0_
43 *******************
44 2 hanyuan 21 男
45 3 hongten 21 男
46 Hibernate:
47 select
48 person0_.id as id0_0_,
49 person0_.name as name0_0_,
50 person0_.age as age0_0_,
51 person0_.sex as sex0_0_
52 from
53 spring.person person0_
54 where
55 person0_.id=?
haibernate 配置资源的XML配置方式:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory> <property name="hibernate.connection.url" >jdbc:mysql://localhost/EducationCRM?useUnicode=true&characterEncoding=utf-8</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!--方言 -->
<property name="hibernate.show_sql">false</property><!--是否打印SQL语句 -->
<property name="hibernate.format_sql">true</property><!--在控制台和log4j 优化打印的语句 -->
<property name="hibernate.hbm2ddl.auto">update</property><!--自动跟新 --> <property name="sessionInfoName">sessionInfo</property>
<property name="uploadFieldName">filedata</property>
<property name="uploadFileMaxSize">20971520</property>
<property name="uploadFileExts">txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid</property>
<property name="uploadDirectory">attached</property> <!-- 配置mapping示例 -->
<mapping class="com.educationcrm.dao.BuyVipCard"/> </session-factory>
</hibernate-configuration>