Sprin2.5+Hibernate3.3整合

來源:互聯網
上載者:User

標籤:des   http   io   os   ar   使用   java   for   sp   

Sprin2.5+Hibernate3.3整合

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);
}
}
}

 

Sprin2.5+Hibernate3.3整合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.