Still Silicon Valley Spring integration hibernate based on XML configuration

Source: Internet
Author: User

Description: This is one of the simplest online bookstore demos.

: http://download.csdn.net/detail/u013488580/8370899

1. What does Spring integration Hibernate integrate? 1). There are IOC containers to manage Hibernate's SessionFactory2). Let Hibernate use declarative transaction 2 on Spring. Integration steps: 1). Join Hibernate①. Jar Package ②. Add Hibernate configuration file: Hibernate.cfg.xml③. The. hbm.xml file that corresponds to the persisted class has been written. 2). Join Spring①. Jar Package ②. Join Spring's configuration file 3). Integration. 3. Writing code


Project structure:


Bookshopdao Code:

Package Com.atguigu.spring.hibernate.dao;public interface Bookshopdao {//per ISBN get book price public int FINDBOOKPRICEBYISBN ( String ISBN);//The Inventory of the updated number. Keep the ISBN corresponding in stock-1public void Updatebookstock (String ISBN);//update the user's account balance: Make username balance-pricepublic void Updateuseraccoun T (String username, int price);}


Bookshopdaoimpl Code:

Package Com.atguigu.spring.hibernate.dao.impl;import Org.hibernate.query;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.repository;import Com.atguigu.spring.hibernate.dao.bookshopdao;import Com.atguigu.spring.hibernate.exceptions.bookstockexception;import Com.atguigu.spring.hibernate.exceptions.UserAccountException, @Repositorypublic class Bookshopdaoimpl implements Bookshopdao {@Autowiredprivate sessionfactory sessionfactory;//not recommended Hibernatetemplate and hibernatedaosupport// Because this causes the Dao and Spring APIs to be coupled//portability-poor//private hibernatetemplate hibernatetemplate;//gets and the current thread binds to the Session. Private Session getsession () {return sessionfactory.getcurrentsession ();} @Overridepublic int Findbookpricebyisbn (string ISBN) {string hql = "Select B.price from book b WHERE b.isbn =?"; Query query = getsession (). CreateQuery (HQL). SetString (0, ISBN); return (Integer) Query.uniqueresult ();} @Overridepublic void Updatebookstock (String ISBN) {//Verify that the inventory is sufficient. String hql2 = "Select B.stock from book b WHERE b.isbn =?"; int stock = (int) getsession (). CreateQuery (HQL2). SetString (0, ISBN). Uniqueresult (); if (stock = = 0) {throw new Bookstockexception ("Insufficient stock!");} String hql = "UPDATE book b SET b.stock = b.stock-1 WHERE b.isbn =?"; GetSession (). CreateQuery (HQL). SetString (0, ISBN). executeupdate ();  @Overridepublic void Updateuseraccount (string username, int price) {//Verify that the balance is sufficient String hql2 = "Select A.balance from Account A WHERE a.username =? "; int balance = (int) getsession (). CreateQuery (HQL2). setString (0, username). Uniqueresult (); if (balance < price) {throw New Useraccountexception ("Insufficient balance!");} String hql = "UPDATE account a SET a.balance = a.balance-?" WHERE a.username =? "; GetSession (). CreateQuery (HQL). Setinteger (0, Price). setString (1, username). Executeupdate ();}}

Unit Test class Springhibernatetest code:

Package Com.atguigu.spring.hibernate.test;import Java.sql.sqlexception;import Java.util.arrays;import Javax.sql.datasource;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.atguigu.spring.hibernate.service.bookshopservice;import Com.atguigu.spring.hibernate.service.cashier;public Class Springhibernatetest {private ApplicationContext CTX = null;private Bookshopservice bookshopservice = null;private C Ashier cashier = null; {CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); Bookshopservice = Ctx.getbean ( Bookshopservice.class); cashier = Ctx.getbean (Cashier.class);} @Testpublic void Testcashier () {cashier.checkout ("AA", Arrays.aslist ("1001", "1002"));} @Testpublic void Testbookshopservice () {bookshopservice.purchase ("AA", "1001");} @Testpublic void Testdatasource () throws SQLException {DataSource DataSource = Ctx.getbean (Datasource.class); System.out.println (Datasource.getConnection ());}} 

Database Configuration Db.properties Code:

jdbc.user=rootjdbc.password=1230jdbc.driverclass=com.mysql.jdbc.driverjdbc.jdbcurl=jdbc:mysql:/// spring7jdbc.initpoolsize=5jdbc.maxpoolsize=10# ...


Hibernate.cfg.xml File Code:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
Applicationcontext.xml File Code:

<?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:tx= "Http://www.springframework.org/schema/tx" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi: schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/ Spring-aop-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.0.xsd "><!--Configure automatic scanning of packages--><context:component-scan base-package=" Com.atguigu.spring.hibernate "></context:component-scan><!--Import resource file--><context: Property-placeholder location= "classpath:db.properties"/><!--configuration dataSOURCE--><bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" ><property name= "user" Value= "${jdbc.user}" ></property><property name= "password" value= "${jdbc.password}" ></property ><property name= "Driverclass" value= "${jdbc.driverclass}" ></property><property name= "JdbcUrl" Value= "${jdbc.jdbcurl}" ></property><property name= "initialpoolsize" value= "${jdbc.initPoolSize}" > </property><property name= "maxpoolsize" value= "${jdbc.maxpoolsize}" ></property></bean> <!--configuring Hibernate sessionfactory instances: Configuring--><bean id= "Sessionfactory" with Spring-provided Localsessionfactorybean ass= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean" ><!--Configuring Data Source Properties--><property name= " DataSource "ref=" DataSource "></property><!--Configure Hibernate profile location and name--><!--<property name=" Configlocation "value=" Classpath:hibernate.cfg.xml "></property>--><!--using HibernateProperties zodiac to configure Hibernate native attributes--><property name= "hibernateproperties" ><props><prop key= " Hibernate.dialect ">org.hibernate.dialect.mysql5innodbdialect</prop><prop key=" Hibernate.show_sql " >true</prop><prop key= "Hibernate.format_sql" >true</prop><prop key= " Hibernate.hbm2ddl.auto ">update</prop></props></property><!--Configure the location and name of the hibernate mapping file, You can use a wildcard character--><property name= "mappinglocations" value= "classpath:com/atguigu/spring/hibernate/entities/*. Hbm.xml "></property></bean><!--Configure Spring's declarative transaction--><!--1. Configure transaction manager--><bean id= "TransactionManager" class= " Org.springframework.orm.hibernate4.HibernateTransactionManager "><property name=" sessionfactory "ref=" Sessionfactory "></property></bean><!--2. Configuring transaction properties requires transaction manager--><tx:advice id= "Txadvice" transaction-manager= "TransactionManager" ><tx:attributes ><tx:method name= "get*" read-only= "true"/><tx: Method name= "Purchase" propagation= "requires_new"/><tx:method name= "*"/&GT;&LT;/TX:ATTRIBUTES&GT;&LT;/TX: advice><!--3. Configure the transaction pointcut and associate the Tangency and transaction properties--><aop:config><aop:pointcut expression= "Execution (* Com.atguigu.spring.hibernate.service.*.* (..)) " Id= "Txpointcut"/><aop:advisor advice-ref= "Txadvice" pointcut-ref= "Txpointcut"/></aop:config></ Beans>


Still Silicon Valley Spring integration hibernate based on XML configuration

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.