javascript
Spring整合Hibernate。。。。
?環境搭建,在eclipse中導入spring和hibernate框架的插件,和導入所有使用到的架包
?
?首先,hibernate的創建:
建立兩個封裝類,其中封裝了數據庫中表的屬性,這兒只寫屬性,getter和setter方法就不寫了
?類:Account中的屬性
private Integer id; private String username; private int balance;類:Book中的屬性
private Integer id; private String bookName; private String isbn;//書號碼 private int price; private int stock;//書的庫存數量?
在該包下建立Hibernate XML Mapping file(hbm.xml)的映射文件,其是自動生成的,直接點擊下一步,下一步。。。,需要說明的是,其映射文件將封裝類中的屬性和數據庫中表的屬性相關聯
<hibernate-mapping><class name="com.atguigu.springhibernate.entities.Account" table="ACCOUNTS">//name,為,類中屬性名,type為屬性的類型,<column name..>為數據庫中表的屬性,下邊是主鍵的生成方式<id name="id" type="java.lang.Integer"><column name="ID" /><generator class="native" /></id><property name="username" type="java.lang.String"><column name="USERNAME" /></property><property name="balance" type="int"><column name="BALANCE" /></property></class> </hibernate-mapping> <hibernate-mapping><class name="com.atguigu.springhibernate.entities.Book" table="BOOK"><id name="id" type="java.lang.Integer"><column name="ID" /><generator class="native" /></id><property name="bookName" type="java.lang.String"><column name="BOOK_NAME" /></property><property name="isbn" type="java.lang.String"><column name="ISBN" /></property><property name="price" type="int"><column name="PRICE" /></property><property name="stock" type="int"><column name="STOCK" /></property></class> </hibernate-mapping>?
在src目錄下建立 Hibernate Configuration File(cfg)為?hibernate.cfg.xml,其是hibernate和配置文件
<hibernate-configuration><session-factory><!-- hibernate的配置文件 --><!-- 1. 數據源需配置到 IOC 容器中, 所以在此處不再需要配置數據源 --><!-- 2. 關聯的 .hbm.xml 也在 IOC 容器配置 SessionFactory 實例時在進行配置 --><!-- 3. 配置 hibernate 的基本屬性: 方言, SQL 顯示及格式化, 生成數據表的策略以及二級緩存等. --><property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><property name="hibernate.show_sql">true</property><property name="hibernate.format_sql">true</property><property name="hibernate.hbm2ddl.auto">update</property><!-- 配置hibernate二級緩存的配置 --></session-factory> </hibernate-configuration>--------------------------------------------------------------------------------
?然后spring框架整合hibernate。。。
建立一個接口
package com.atguigu.springhibernate.dao;import java.util.List;public interface BookShopDao {//根據書號獲取書的單價public int findBookPriceByIsbn(String isbn);//更新數的庫存. 使書號對應的庫存 - 1public void updateBookStork(String isbn);//更新用戶的賬戶余額: 使 username 的 balance - pricepublic void updateUserAccount(String username,int price);//購買批量的書籍,更新用戶的余額public int updateBatch(String username,List<String> isbns); }?
建立一個類,實現上邊的接口,方法是。。。,用的是hql語句,其是面向對象的,表名為其對應的類名,即寫hql語句時表名首字母大寫。。。
package com.atguigu.springhibernate.dao.impl;import java.util.List;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.springhibernate.dao.BookShopDao; import com.atguigu.springhibernate.exceptions.BookStockException; import com.atguigu.springhibernate.exceptions.UserAccountException;@Repository public class BookShopDaoImpl implements BookShopDao{@Autowiredprivate SessionFactory sessionFactory;//獲取和當前線程綁定的 Session.private Session getSession(){return sessionFactory.getCurrentSession();}/** hql是面向對象的,其表名為該表所映射的類名,即表名首字母大寫* *///根據書號獲取書的單價public 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();}//更新數的庫存. 使書號對應的庫存 - 1public void updateBookStork(String isbn) {//驗證書的庫存是否充足.String hql2="select b.stock from Book b where isbn=?";int stock= (Integer) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();if(stock==0){System.out.println("該書的庫存不足!!!");throw new BookStockException("該書的庫存不足!!!");}String hql="update Book b set b.stock=b.stock-1 where b.isbn=?";getSession().createQuery(hql).setString(0, isbn).executeUpdate();}//更新用戶的賬戶余額: 使 username 的 balance - pricepublic void updateUserAccount(String username, int price) {//首先,驗證余額是否足夠String hql2="select a.balance from Account a where a.username=?";int balance=(Integer) getSession().createQuery(hql2).setString(0, username).uniqueResult();if(balance<price){//System.out.println("賬戶的余額不足了!!!");throw new UserAccountException("賬戶余額不足了!!!!");}String hql="update Account a set a.balance=a.balance-? where username=?";getSession().createQuery(hql).setInteger(0, price).setString(1, username).executeUpdate();}public int updateBatch(String username, List<String> isbns) {//批量購買,首先驗證余額是否足夠//購買的所有書籍的總錢數int money=0;String hql2="select b.price from Book b where b.isbn=?";for(String isbn:isbns){money+=(Integer) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();}//用戶的賬戶余額String hql="select a.balance from Account a where a.username=?";int balance=(Integer) getSession().createQuery(hql).setString(0, username).uniqueResult();if(money>balance){throw new UserAccountException("余額不足,不能購買全部書籍");}return 0;}}?
在建立兩個接口,
package com.atguigu.springhibernate.service;import java.util.List;public interface Cashier {public void checkout(String username,List<String> isbns);} package com.atguigu.springhibernate.service;public interface BookShopService {public void purchase(String username,String isbn);}?
建立兩個類分別實現上邊的兩個接口。。。
package com.atguigu.springhibernate.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import com.atguigu.springhibernate.dao.BookShopDao; import com.atguigu.springhibernate.service.Cashier;@Service public class CashierImpl implements Cashier {@Autowiredprivate BookShopDao bookShopDao;//批量購買書籍public void checkout(String username, List<String> isbns) {//購買批量的書籍 bookShopDao.updateBatch(username, isbns);}} package com.atguigu.springhibernate.service.impl;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import com.atguigu.springhibernate.dao.BookShopDao; import com.atguigu.springhibernate.service.BookShopService;@Service public class BookShopServiceImpl implements BookShopService {@Autowiredprivate BookShopDao bookShopDao;/*** Spring hibernate 事務的流程* 1. 在方法開始之前* ①. 獲取 Session* ②. 把 Session 和當前線程綁定, 這樣就可以在 Dao 中使用 SessionFactory 的* getCurrentSession() 方法來獲取 Session 了* ③. 開啟事務* * 2. 若方法正常結束, 即沒有出現異常, 則* ①. 提交事務* ②. 使和當前線程綁定的 Session 解除綁定* ③. 關閉 Session* * 3. 若方法出現異常, 則:* ①. 回滾事務* ②. 使和當前線程綁定的 Session 解除綁定* ③. 關閉 Session*/public void purchase(String username, String isbn) {//由書的編號,的出書的價格int price = bookShopDao.findBookPriceByIsbn(isbn);//由書的編號,更新書的庫存 bookShopDao.updateBookStork(isbn);//更新該用戶的賬戶余額 bookShopDao.updateUserAccount(username, price);}}?
在src目錄下建立jdbc.properties文件:是連接數據庫的基本屬性和值
jdbc.user=root jdbc.password=lxn123 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///spring_hibernate jdbc.initPoolSize=5 jdbc.maxPoolSize=10?
在src下建立Spring Bean Configuration File的xml文件:applicationContext.xml,是spring的bean的配置文件和整合hibernate的文件
<!-- 配置自動掃描的包,及其子包,基于注解的bean配置 --><context:component-scan base-package="com.atguigu.springhibernate"></context:component-scan><!-- 配置數據源 --><!-- 導入資源文件 ,根目錄(src)下的文件--><context:property-placeholder location="classpath:jdbc.properties"/><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><!-- 配置 Hibernate 的 SessionFactory 實例: 通過 Spring 提供的 LocalSessionFactoryBean 進行配置 --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><!-- 配置數據源屬性 --><property name="dataSource" ref="dataSource"></property><!-- 配置 hibernate 配置文件的位置及名稱 --><property name="configLocation" value="classpath:hibernate.cfg.xml"></property><!-- 配置 hibernate 映射文件的位置及名稱, 可以使用通配符 --><property name="mappingLocations" value="classpath:com/atguigu/springhibernate/entities/*.hbm.xml"></property></bean><!-- 配置 Spring 的聲明事務 --><!-- 1. 配置事務管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 2. 配置事務屬性, 需要事務管理器 --><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="*"/></tx:attributes></tx:advice><!-- 3. 配置事務切點, 并把切點和事務屬性關聯起來 --><aop:config><aop:pointcut expression="execution(* com.atguigu.springhibernate.service.*.*(..))" id="txPointcut"/><!-- 把切點和事物屬性關聯起來 --><aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/></aop:config>?
建立一個測試類,對上面的方法進行測試;
package com.atguigu.springhibernate.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.springhibernate.service.BookShopService; import com.atguigu.springhibernate.service.Cashier;public class SpringHibernateTest {private static ApplicationContext ctx=null;private static BookShopService bookShopService=null;private static Cashier cashier=null;{ctx=new ClassPathXmlApplicationContext("applicationContext.xml");bookShopService=ctx.getBean(BookShopService.class);cashier=ctx.getBean(Cashier.class);}@Testpublic void testCashier(){cashier.checkout("AAA", Arrays.asList("1001","1002"));}@Testpublic void testBookShopService() {bookShopService.purchase("AAA", "1001");}//測試數據庫連接池是否連接成功public void jdbcConnection() throws SQLException{DataSource dataSource=(DataSource) ctx.getBean("dataSource");System.out.println(dataSource.getConnection());}}?
--------------------------------------------------------------------------------
在包com.atguigu.springhibernate.exceptions下建立兩個異常類:其繼承于RuntimeException,便于前面對異常的處理時,直接調用;
package com.atguigu.springhibernate.exceptions;public class UserAccountException extends RuntimeException{private static final long serialVersionUID = 1L;public UserAccountException() {super();}public UserAccountException(String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}public UserAccountException(String message, Throwable cause) {super(message, cause);}public UserAccountException(String message) {super(message);}public UserAccountException(Throwable cause) {super(cause);}}?
package com.atguigu.springhibernate.exceptions;public class BookStockException extends RuntimeException{private static final long serialVersionUID = 1L;public BookStockException() {super();}public BookStockException(String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}public BookStockException(String message, Throwable cause) {super(message, cause);}public BookStockException(String message) {super(message);}public BookStockException(Throwable cause) {super(cause);}}?
轉載于:https://www.cnblogs.com/lxnlxn/p/5905412.html
總結
以上是生活随笔為你收集整理的Spring整合Hibernate。。。。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell脚本规划化模板
- 下一篇: WinForm ListView