Spring Learning (v) Spring integration hibernate

Source: Internet
Author: User
Tags sessions

In the previous blog, we talked about the spring DAO layer's encapsulation of JDBC and used the design idea of template pattern. In this article we look at the ORM layer in spring, the encapsulation of hibernate, the so-called Spring integration hibernate. The same template pattern is used to encapsulate the hibernate development process in the template class Hibernatetemplate provided by the ORM layer, which replaces the traditional hibernate development process by using the template class in DAO.

First, take a look at Hibernate's traditional development process:
    1) 配置SessionFactory对象        hibernate.cfg.xml <session-factory>        a 数据源  driver_class url username password        b 映射文件 mapping        c 可选参数 show_sql format_sql dialect ...    2) 创建SessionFactory实例        工厂类 - 解析xml - SessionFactory    3) 获取会话 Session        sessionFactory.getSession()如果是 insert delete update        4) 开启事务 Transaction            session.beginTransaction()        5) 执行操作 save() delete() update()        6) 提交/回滚事务            commit() / rollback()如果是 select        4) 定义执行hql语句        5) 编译hql Query            session.createQuery()        6) 执行hql             list()  unqueObject()    7) 关闭会话         session.close()

The use of hibernate in spring is basically similar to the traditional hibernate usage, where sessionfactory, data sources, etc. are configured in the configuration file, except that spring configures hibernatetemplate in the container. The operation of the database is accomplished by injecting the Bean object into the DAO layer.

Second, the integration process:
    1) 添加spring框架支持(core层)    2) 添加spring整合hibernate需要的jar(hibernate目录)    3) 添加hibernate支持(导入3.5/3.6版本jar包)spring4.0中,如果以注解的方式整合hibernate,仅支持hibernate3.6及以上版本    4) 反向生成表对应的javaBean和映射文件    5)编写applicationContext.xml文件添加支持
Third, the concrete realization:

Applicationcontext.xml:

<beans xmlns="Http://www.springframework.org/schema/beans"xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/ Schema/beans/spring-beans-3.2.xsd ">                     <!--Studaoimpl Hibernatetemplate is configured as an IOC container --    <bean id="DAO" class="Com.etoak.dao.CityDaoImpl">        < property name="ht" ref="HT"></Property >    </Bean>    <!--The hibernatetemplate temporarily does not have the ability to connect to a database to provide a Sessionfactory object 1 data Source ~ Describes the database that currently needs to be connected 2 mapping File ~ Describes which table is currently required to operate setsessionfactory ()-    <bean id= "ht" class=" Org.springframework.orm.hibernate3.HibernateTemplate ">        < property name="Sessionfactory" ref="SF"></Property >    </Bean>    <!--configuration Sessionfactory[Interface] Object 1 implementation Class The Spring framework does not provide a Sessionfactory implementation Class 2 factory        Bean Spring provides a factory class for Sessionfactory to instantiate Localsessionfactorybean impliments Factorybean            How do I use this factory to configure Sessionfactory objects? And hibernate are configured in a manner similar to 1 data source Setdatasource (DataSource DS) 2 mapping file Setmappingr Esources (string[] mapping) 3 optional Parameters sethibernateproperties (Properties props) List element: Indicates the adjustment parameter types that need to be injected with the current setter method each time a mapping file is added to the project, a value child element is added under the list element to point to the mapping file-->    <bean id= "SF" class=" Org.springframework.orm.hibernate3.LocalSessionFactoryBean ">        < property name="DataSource" ref="ds"></Property >        < property name="Mappingresources" >            <list>                  <value>Com/etoak/po/city.hbm.xml</value>            </list>        </Property >        < property name="Hibernateproperties">            <props>                <prop key="dialect">Org.hibernate.dialect.MySQLDialect</prop>                <prop key="Hibernate.show_sql">True</prop>                <prop key="Hibernate.format_sql">True</prop>            </props>        </Property >    </Bean>    <!--configuring datasource data Sources --      <bean id= "ds" class=" Org.springframework.jdbc.datasource.DriverManagerDataSource ">        < property name="Driverclassname" value="Com.mysql.jdbc.Driver" ></Property >        < property name="url" value="jdbc:mysql://localhost:3306/ Yitu "></Property >        < property name="username" value="root"></Property >        < property name="password" value="root"></Property >      </Bean></Beans>

Citydaoimpl.java (DAO)

 PackageCom.etoak.dao;Importjava.io.Serializable;ImportJava.sql.SQLException;ImportJava.util.List;ImportOrg.hibernate.HibernateException;ImportOrg.hibernate.Query;ImportOrg.hibernate.Session;ImportOrg.springframework.orm.hibernate3.HibernateCallback;ImportOrg.springframework.orm.hibernate3.HibernateTemplate;Importcom.etoak.po.City;/** * crud the city with Hibernate * Integrated solution provided by spring Hibernatetemplate * @author D_xiao * */ Public  class citydaoimpl {    PrivateHibernatetemplate HT; Public void setht(Hibernatetemplate HT) { This. HT = HT; } Public Boolean addcity(city) {Serializable SE = ht.save (city);//se The primary key value of the data after it has been added successfullyInteger id = (integer) se;returnId>0; }/** * Query single data based on primary key * Get loaded immediately * First level cache-level two cache-database-null * load deferred load [database connection delay] * Query phase       * First cache, terminate query, return proxy object * Use stage * Level two cache--Exception * Proxy mode * Determine if the Load method can be used, * this cannot be used with load only get * /              PublicCitySelectcitybyid(Integer ID) {returnHt.get (City.class, id); }//Cannot control success failure here, only after adding a transaction to control     Public Boolean Delcitybyid(Integer ID) {Ht.delete (Ht.load (City.class, id));//load can be used here because there are sessions in the query (object) and use (delete)        return true; } Public Boolean updatecity(city) {ht.update (city);return true; }//Query bulk Data list<city>     PublicListselectallcity() {String hql =" from City"; List List = Ht.find (HQL);returnList }//non-primary key query single data     PublicCitySelectcitybyname(String name) {String HQL ="from the city where name=?";        object[] args = {name}; List List = Ht.find (Hql,args);if(List.size ()! =0)return(city) List.get (0);Else             return NULL; }//Query data volume    //hibernate3.2 after the query data volume return type is a long type     Public Long Selectcitycount() {String hql ="SELECT COUNT (*) from city"; List List = Ht.find (HQL);return(Long) List.get (0); }/** * Paging query * Hibernate in paged query: * Serfirstresult () Sermaxresult () * Method provided in hibernatetemplate (Save U Pdate Delete Get load Find) By default encapsulates the hibernate entire process * But the template class provides a subset of methods that encapsulate only hibernate part of the function * Execute (hibernatecallback[ Interface] C1) * T currently needs to query the data type * Anonymous internal class access to external properties you need to set the property to final * /     PublicList<city>Selectcitybypage(Final intStartFinal intEnd) {returnHt.execute (NewHibernatecallback<list<city>> () {//This method encapsulates the creation of session sessions only            @Override             PublicList<city>doinhibernate(Session session)throwsHibernateexception, SQLException {query query = session.createquery (" from City");                Query.setfirstresult (start); Query.setmaxresults (end);returnQuery.list ();    }        }); }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring Learning (v) Spring integration hibernate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.