1.添加jar文件
Hibernate3.3核心安装包下的
/-----------------------------------/
hibernate3.jar
lib\required\*.jar
lib\optional\ehcache-1.2.3.jar
hibernate注解安装包下的
lib\test\slf4j-log4j12.jar
/-----------------------------------/
Spring安装包下的
/-----------------------------------/
dist\spring.jar
dist\modules\spring-webmvc-struts.jar
lib\jakaarte-commons\commons-logging.jar、commons-dbcp.jar、commons-pool.jar
lib\aspectj\aspectjweaver.jar 、 aspectjrt.jar
lib\cglib\cglib-nodep-2.1.3.jar
lib\j2ee\common-annoutations.jar
lib\log4j\log4j-1.2.15.jar
/------------------------------------/
数据库驱动
2. 配置beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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">
<!--导入外部properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!--连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!--连接池的最大值 -->
<property name="maxActive" value="${maxActive}" />
<!--最大空闲值,当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释 放一部分一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}" />
<!--最小空闲值,当经空闲的连接邵谊阀值时,连接池就会申请一些连接, 以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>cn/soldier/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- 指定数据库方言 -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<!-- 是否根据需要每次自动创建数据库 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 显示Hibernate持久化操作所生成的SQL -->
<prop key="hibernate.show_sql">true</prop>
<!-- 将SQL脚本进行格式化后再输出 -->
<prop key="hibernate.format_sql">false</prop>
<!-- <prop key="hibernate.cache.use_second_level_cache">true</prop> -->
<!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
<!-- <prop key="hibernate.provider_class">org.hibernate.cache.EhCacheProvider</prop> -->
</props>
</property>
</bean>
<!--配置事务管理器 -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--启用@Transaction注解的支持- -->
<tx:annotation-driven transaction-manager="txManager" />
<!--使用field方法注入依赖对象 -->
<context:annotation-config />
<!-- -->
<bean id="personService" class="cn.soldier.service.impl.PersonServiceBean"></bean>
</beans>
3.新建实体bean Person
package cn.soldier.bean;
Person.java
public class Person {
private Long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Person [id=" + id + " name=" + name + "]";
}
}
4.建立对应的数据库映射
Person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.soldier.bean">
<class name="Person" table="person">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
</class>
</hibernate-mapping>
5.建立访问Person实体的Service接口
package cn.soldier.service;
import java.util.List;
import cn.soldier.bean.Person;
public interface PersonService {
public abstract void save(Person person);
public abstract void update(Person person);
public abstract void delete(Long id);
public abstract Person getPerson(Long id);
public abstract List<Person> getPersons();
}
6.建立访问Person实体的Service实现方法
package cn.soldier.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.soldier.bean.Person;
import cn.soldier.service.PersonService;
@Transactional //启用事务管理
public class PersonServiceBean implements PersonService {
@Resource//使用filed注入SessionFactory对象
SessionFactory sessionFactory;
public void save(Person person) {
// 得到容器里面正在被Transaction管理的Session
// 如果使用opeSession(),获得的Session对象是不受Transaction管理的。
Session session = (Session) sessionFactory.getCurrentSession();
session.persist(person);
}
public void update(Person person) {
sessionFactory.getCurrentSession().merge(person);// SaveOrUpdate
}
public void delete(Long id) {
// load方法性能最佳,因为get方法有一个数据装配的过程
sessionFactory.getCurrentSession().delete(
sessionFactory.getCurrentSession().load(Person.class, id));
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)// 不启用事务管理,只读
public Person getPerson(Long id) {
return (Person) sessionFactory.getCurrentSession()
.get(Person.class, id);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
@SuppressWarnings("unchecked")
// 终止警告
public List<Person> getPersons() {
return sessionFactory.getCurrentSession().createQuery("From Person").list();
}
}
7.测试开发好的PersonServiceBean
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.soldier.bean.Person;
import cn.soldier.service.PersonService;
public class PersonServiceBeanTest {
private static PersonService personService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
personService = (PersonService) ctx.getBean("personService");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSave() {
for (int i = 0; i <10; i++) {
Person person = new Person("逗比---"+i+"---号");
personService.save(person);
}
}
@Test
public void testUpdate() {
Person person = personService.getPerson(1L);
person.setName("逗比2号");
personService.update(person);
System.out.println(personService.getPerson(1L));
}
@Test
public void testDelete() {
personService.delete(2L);
}
@Test
public void testGetPersons() {
for (Person person : personService.getPersons()) {
System.out.println(person);
}
}
}