javascript
Spring与Hibernate结合使用
1、使用Spring的IOC容器,將對象之間的依賴關系交給Spring,可以降低組件之間的耦合性,可以更專注于應用邏輯。同時可以提供眾多服務,數據庫事務管理,WS等。
2、Hibernate是對JDBC的輕量級的對象封裝,是一個獨立的對象持久化對象。
1)對象/關系數據庫映射(ORM)
它使用時只需要操縱對象,使開發更對象化,拋棄了數據庫中心的思想,完全的面向對象思想。
2) 事務Transaction(org.hibernate.Transaction)
應用程序用來指定原子操作單元范圍的對象,它是單線程的,生命周期很短。它通過抽象將應用從底層具體的JDBC、JTA以及CORBA事務隔離開。某些情況下,一個Session之內可能包含多個Transaction對象。盡管是否使用該對象是可選的,但無論是使用底層的API還是使用Transaction對象,事務邊界的開啟與關閉是必不可少的。
3)簡潔的HQL編程。
將上述兩個框架結合起來實現對數據庫的操作將繼承兩個框架的優點。
3、Spring與Hibernate框架整合
1)創建一個bean與與之對應的bean.hbm.xml文件,使用Hibernate的ORM對數據庫表進行設置。
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)面對接口編程。創建一個接口操作數據庫,并實現。
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);}實現類:
@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和數據庫源等。
<?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"><!-- 設置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"/><!-- 連接池啟動時的初始值 --><!-- <property name="initialSize" value="1"/>連接池的最大值<property name="maxActive" value="500"/>最大空閑值.當經過一個高峰時間后,連接池可以慢慢將已經用不到的連接慢慢釋放一部分,一直減少到maxIdle為止<property name="maxIdle" value="2"/>最小空閑值.當空閑的連接數少于閥值時,連接池就會預申請去一些連接,以免洪峰來時來不及申請<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)編寫測試用例測試。
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("開始插入數據");Person person = new Person();person.setName("ruijie");person.setPassword("awgagwg");personServer.save(person);logger.debug("數據插入成功");}@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());}} }
一個小小的demo: SpringHibernateDemo
總結
以上是生活随笔為你收集整理的Spring与Hibernate结合使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 国家电网湖北电力做试验的部门属于哪个院?
- 下一篇: 智能测控能进电网吗?