javascript
Spring与Hibernate结合使用
1、使用Spring的IOC容器,將對(duì)象之間的依賴關(guān)系交給Spring,可以降低組件之間的耦合性,可以更專注于應(yīng)用邏輯。同時(shí)可以提供眾多服務(wù),數(shù)據(jù)庫(kù)事務(wù)管理,WS等。
2、Hibernate是對(duì)JDBC的輕量級(jí)的對(duì)象封裝,是一個(gè)獨(dú)立的對(duì)象持久化對(duì)象。
1)對(duì)象/關(guān)系數(shù)據(jù)庫(kù)映射(ORM)
它使用時(shí)只需要操縱對(duì)象,使開(kāi)發(fā)更對(duì)象化,拋棄了數(shù)據(jù)庫(kù)中心的思想,完全的面向?qū)ο笏枷搿?/span>
2) 事務(wù)Transaction(org.hibernate.Transaction)
應(yīng)用程序用來(lái)指定原子操作單元范圍的對(duì)象,它是單線程的,生命周期很短。它通過(guò)抽象將應(yīng)用從底層具體的JDBC、JTA以及CORBA事務(wù)隔離開(kāi)。某些情況下,一個(gè)Session之內(nèi)可能包含多個(gè)Transaction對(duì)象。盡管是否使用該對(duì)象是可選的,但無(wú)論是使用底層的API還是使用Transaction對(duì)象,事務(wù)邊界的開(kāi)啟與關(guān)閉是必不可少的。
3)簡(jiǎn)潔的HQL編程。
將上述兩個(gè)框架結(jié)合起來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的操作將繼承兩個(gè)框架的優(yōu)點(diǎn)。
3、Spring與Hibernate框架整合
1)創(chuàng)建一個(gè)bean與與之對(duì)應(yīng)的bean.hbm.xml文件,使用Hibernate的ORM對(duì)數(shù)據(jù)庫(kù)表進(jìn)行設(shè)置。
bean:
package com.ruijie.bean;public class Person {private int id;private String name;private String password;public int getId() {return this.id;}public void setId(int id) {this.id = id;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public String getPassword() {return this.password;}public void setPassword(String password) {this.password = password;}} 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="com.ruijie.bean"><class name="Person" table="person"><id name="id" type="integer"><generator class="identity"></generator></id><property name="name" length="20" not-null="true"></property><property name="password" length="20" not-null="true"></property></class></hibernate-mapping>
2)面對(duì)接口編程。創(chuàng)建一個(gè)接口操作數(shù)據(jù)庫(kù),并實(shí)現(xiàn)。
PersonServer:
public interface PersonServer {public abstract void save(Person person);public abstract void update(Person person);public abstract Person getPerson(int id);public abstract List<Person> getAllPerson();public abstract void delete(int id);}實(shí)現(xiàn)類:
@Transactional public class PersonServerImpl implements PersonServer {private SessionFactory sessionFactory;public void save(Person person){sessionFactory.getCurrentSession().persist(person);}public void update(Person person){sessionFactory.getCurrentSession().merge(person);}@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)public Person getPerson(int personid){return (Person)sessionFactory.getCurrentSession().get(Person.class, personid);}public void delete(int personid){sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().load(Person.class, personid));}@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)@SuppressWarnings("unchecked")public List<Person> getAllPerson(){ return sessionFactory.getCurrentSession().createQuery("from Person").list();}public SessionFactory getSessionFactory() {return this.sessionFactory;}public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}}
3)配置beans.xml文件,配置bean和數(shù)據(jù)庫(kù)源等。
<?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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 設(shè)置datasource --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="url" value="jdbc:sqlserver://192.168.54.31:1433;DatabaseName=testdb"/><property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/><property name="username" value="sa"/><property name="password" value="shyfzx@163"/><!-- 連接池啟動(dòng)時(shí)的初始值 --><!-- <property name="initialSize" value="1"/>連接池的最大值<property name="maxActive" value="500"/>最大空閑值.當(dāng)經(jīng)過(guò)一個(gè)高峰時(shí)間后,連接池可以慢慢將已經(jīng)用不到的連接慢慢釋放一部分,一直減少到maxIdle為止<property name="maxIdle" value="2"/>最小空閑值.當(dāng)空閑的連接數(shù)少于閥值時(shí),連接池就會(huì)預(yù)申請(qǐng)去一些連接,以免洪峰來(lái)時(shí)來(lái)不及申請(qǐng)<property name="minIdle" value="1"/> --></bean><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mappingResources"><list><value>com/ruijie/bean/Person.hbm.xml</value></list></property><property name="hibernateProperties"><value>hibernate.dialect=org.hibernate.dialect.SQLServerDialect</value></property></bean><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/></bean><tx:annotation-driven transaction-manager="txManager"/><bean id="personService" class="com.ruijie.server.impl.PersonServerImpl"><property name="sessionFactory" ref="sessionFactory"/></bean> </beans>
4)編寫測(cè)試用例測(cè)試。
public class PersonServerTest {private Logger logger = Logger.getLogger(this.getClass().getName());private static PersonServer personServer;@BeforeClasspublic static void setupBean(){ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");personServer = (PersonServer) context.getBean("personService");}@Testpublic void testSave() {logger.debug("開(kāi)始插入數(shù)據(jù)");Person person = new Person();person.setName("ruijie");person.setPassword("awgagwg");personServer.save(person);logger.debug("數(shù)據(jù)插入成功");}@Testpublic void testUpdate(){Person person = new Person();person.setId(7);person.setName("李四");person.setPassword("wgeage");personServer.update(person );}@Testpublic void testDelete(){personServer.delete(7);}@Testpublic void testGetPerson(){Person person = personServer.getPerson(6);System.out.println("姓名:"+person.getName()+",密碼:"+person.getPassword());}@Testpublic void testGetAllPerson(){List<Person> persons = personServer.getAllPerson();for (Person person : persons) {System.out.println("姓名:"+person.getName()+",密碼:"+person.getPassword());}} }
一個(gè)小小的demo: SpringHibernateDemo
總結(jié)
以上是生活随笔為你收集整理的Spring与Hibernate结合使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 国家电网湖北电力做试验的部门属于哪个院?
- 下一篇: JSR311发布Restful WebS