String架構整合Hibernate

來源:互聯網
上載者:User

標籤:spring   web   java   javaweb   hibernate   

在前一個項目SpringDemo的基礎上加以改進,將Hibernate整合到項目中。

1、匯入Hibernate所需jar包,這裡我用的是Hibernate3.3.2版本的。

主要匯入這幾個包:antlr-2.7.6.jar、commons-collections-3.1.jar、dom4j.jar、ejb3、hibernate3.jar、hibernate-annotations、hibernate-common-annotations、javassist-3.9.0.GA.jar、jta-1.1.jar、slf4j-api.jar、slf4j-nop.jar;此外還有cglib。

缺少jar包,會在運行時出現各奇怪缺包的錯誤,需根據控制台資訊添加jar包。比如ERROR:Ljavax/transaction/TransactionManager;是因為缺少jta.jar包。

我確實還不是很清楚Hibernate中各jar包的功能,好幾個包都是根據錯誤資訊逐個添加進去的。


2、這裡我採用Spring風格的配置,無需建立hibernate.cfg.html檔案,直接在在applicationContext.xml中對Hibernate進行配置。

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:mvc="http://www.springframework.org/schema/mvc"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/context http://www.springframework.org/schema/context/spring-context.xsd   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">         <!-- 啟動包掃描功能,將帶有@Controller、@Service、@repository、@Component等註解的類    自動轉化為成為spring的bean -->    <context:component-scan          base-package="com.demo.service" />      <context:component-scan          base-package="com.demo.dao" />                 <!-- 資料來源配置的檔案,引入spring容器 -->    <context:property-placeholderlocation="classpath:database.properties" />    <!-- dataSource,配置構建基於DBCP的資料來源 -->    <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"lazy-init="false"p:driverClassName="${dataSource.driverClassName}"p:url="${dataSource.url}"p:username="${dataSource.username}"p:password="${dataSource.password}"p:maxActive="${dataSource.maxActive}"p:maxIdle="${dataSource.maxIdle}"p:maxWait="${dataSource.maxWait}" />        <!-- 定義jdbcTemplate模版的Bean    <beanclass="org.springframework.jdbc.core.JdbcTemplate"p:dataSource-ref="dataSource" />--><!-- sessionFactory --><bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"p:dataSource-ref="dataSource"><!-- 這裡使用AnnotationSessionFactoryBean,以使用實體類的註解擷取ORM配置資訊 --><!-- 若使用LocalSessionFactoryBean,則用mappingLocations屬性和xml檔案擷取配置 --><property name="annotatedClasses"><!-- name="packageToScan",則載入包類的帶註解實體類 --><list><value>com.demo.domain.Account</value></list></property><!-- 指定hibernate配置屬性 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop></props></property></bean><!-- 定義hibernateTemplete的Bean --><bean id="hibernateTemplete" class="org.springframework.orm.hibernate3.HibernateTemplate">  <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 更改後的Hibernate交易管理配置 --><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"/>    </bean>    <tx:annotation-driven transaction-manager="txManager"/>        <!-- 交易管理配置     <beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"p:dataSource-ref="dataSource" /><tx:annotation-driventransaction-manager="transactionManager" />     -->     </beans>

註:這裡主要是配置了sessionFactory;Spring架構為建立SessionFactory提供了FactoryBean工廠類。

LocalSessionFactoryBean或AnnotationSessionFactoryBean可利用Hibernate設定檔建立SessionFactory代理對象,以便和Spring的事務機制配合工作。

3、在Account實體類中添加註解,使之能被hibernate持久化。

package com.demo.domain;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity//@Entity表示該類能被hibernate持久化@Table(name="user")public class Account {@Id//指定該列為主鍵@GeneratedValue(strategy=GenerationType.AUTO)//auto為自增長private Integer id;@Column(name="name")private String username;@Column(name="password")private String password;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Account(){}}
4、修改AccountDaoImpl;把原來的函數注釋掉,用注入的hibernateTemplate來進行資料庫操作。

修改後的AccountDaoImpl.java代碼如下:

package com.demo.dao.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.orm.hibernate3.HibernateTemplate;import org.springframework.stereotype.Repository;import com.demo.dao.AccountDao;import com.demo.domain.Account;@Repositorypublic class AccountDaoImpl implements AccountDao {/*@Autowiredprivate JdbcTemplate jdbcTemplate;*/@Autowiredprivate HibernateTemplate hibernateTemplate;@Overridepublic int getMatchCount(String username, String password) {return hibernateTemplate.find("from Account a where a.username = ? "+ "and a.password = ? ",username, password).size();}@Overridepublic Account getAcoountById(int id) {return hibernateTemplate.get(Account.class, id);}@Overridepublic Account getAccountByName(String username) {//return hibernateTemplate.get(Account.class, username); //errorreturn (Account) hibernateTemplate.find("from Account a where a.username = ?", username).get(0);}/*@Overridepublic int getMatchCount(String username, String password) {String strSql = "select count(*) from user "+ " where name = ? and password = ?";//?為參數預留位置return jdbcTemplate.queryForInt(strSql, new Object[]{ username, password});}@Overridepublic Account getAcoountById(int id) {String strSql = "select id,name from user "+ " where id = ?";System.out.println("##########execute sql: "+strSql);final Account account = new Account();jdbcTemplate.query(strSql, new Object[]{ id },//匿名方式實現的回呼函數new RowCallbackHandler(){@Overridepublic void processRow(ResultSet rs) throws SQLException {//將查詢結果封裝到對象執行個體中account.setId(rs.getInt("id"));account.setUsername(rs.getString("name"));}});return account;}@Overridepublic Account getAccountByName(String username) {String strSql = "select id,name from user "+ " where name = ?";System.out.println("##########execute sql: "+strSql);final Account account = new Account();jdbcTemplate.query(strSql, new Object[]{ username },//匿名方式實現的回呼函數new RowCallbackHandler(){@Overridepublic void processRow(ResultSet rs) throws SQLException {//將查詢結果封裝到對象執行個體中account.setId(rs.getInt("id"));account.setUsername(rs.getString("name"));}});return account;}*/}

註:代碼明顯短了不少,是不是~~~。

基於模版類使用Hibernate是最簡單的方式,HibernateTemplate代理了Hibernate Session的大多數持久化操作,調用也確實簡單。

5、運行效果跟之前SpringDemo一樣。
[2014-11-27 17:40:40,578][DEBUG][org.hibernate.hql.ast.AST:266] - --- HQL AST --- \-[QUERY] 'query'    +-[SELECT_FROM] 'SELECT_FROM'    |  \-[FROM] 'from'    |     \-[RANGE] 'RANGE'    |        +-[DOT] '.'    |        |  +-[DOT] '.'    |        |  |  +-[DOT] '.'    |        |  |  |  +-[IDENT] 'com'    |        |  |  |  \-[IDENT] 'demo'    |        |  |  \-[IDENT] 'domain'    |        |  \-[IDENT] 'Account'    |        \-[ALIAS] 'a'    \-[WHERE] 'where'       \-[EQ] '='          +-[DOT] '.'          |  +-[IDENT] 'a'          |  \-[IDENT] 'username'          \-[PARAM] '?'[2014-11-27 17:40:40,579][DEBUG][org.hibernate.hql.ast.ErrorCounter:68] - throwQueryException() : no errors......[2014-11-27 17:40:40,716][DEBUG][org.hibernate.SQL:401] - select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_ where account0_.name=?Hibernate: select account0_.id as id0_, account0_.password as password0_, account0_.name as name0_ from user account0_ where account0_.name=?......[2014-11-27 17:40:40,812][DEBUG][org.hibernate.jdbc.ConnectionManager:421] - opening JDBC connection[2014-11-27 17:40:40,813][DEBUG][org.hibernate.SQL:401] - select account0_.id as id0_0_, account0_.password as password0_0_, account0_.name as name0_0_ from user account0_ where account0_.id=?Hibernate: select account0_.id as id0_0_, account0_.password as password0_0_, account0_.name as name0_0_ from user account0_ where account0_.id=?......
通過控制台資訊,可以看到整合了Hibernate後的運行流程。

用Hibernate作為持久化技術還是比Spring JDBC便捷不少的。


6、總結:通過在Spring中整合Hibernate的Demo,可以發現架構有其各自的優勢和不足,整合時的配置方式多樣。

Java架構也是巨多,在實際開發,根據需求選擇合適的架構即可,不必拘泥於其中一兩個。

後面,將繼續把Struts2整合到該項目中,這樣就搭建起了一個完整基於SSH架構的項目,萬裡長征第一步。


String架構整合Hibernate

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.