淺析hibnate+spring mvc

  除了hibnate+  spring mvc模式,還有PHP mvc ,asp.net mvc模式,他們均可以搭建不一樣的框架。 html

  只不過平臺不一樣,一種Java平臺,能夠到java.com網站下載。能夠開發javaweb,javabean,一種net平臺。數據庫不一樣,asp.net使用sql,spring mvc可以使用MySQL java

oracle。 mysql

  

開發框架搭建

建立工程

         EclipseJava EE版本或MyEclipse中建立一個Dynamic Web Project。並建立以下包: web

1com.dao:系統的DAO spring

2com.model:表的實體類(使用Hibernate),在該工程中不配置.hbm.xml映射文件,採起註解的方式; sql

3com.service:業務邏輯接口類和實現類; shell

4com.webSpring MVCControllor類; 數據庫

5com.configSpringSpring MVC的配置文件。 express

建立成功後包結構以下所示:
   springmvctest
        src 
        ----com
            ----amigo
                ----dao
                ----model
                ----service
                ----web
         ----config
         WebContent
         ----META-INF
         ----WEB-INF
             ----lib
             ----classes

apache

 引入相關包

         須要將SpringSpring MVCHibernateMySQL驅動、log4jc3p0數據源等的相關包引入。lib目錄下的jar包以下:
      antlr-2.7.6.jar
      aopalliance.jar
      asm-attrs.jar
      asm.jar
      c3p0-0.9.0.jar
      cglib-2.1.3.jar
      commons-beanutils-1.8.0.jar
      commons-beanutils-bean-collections-1.8.0.jar
      commons-betwixt-0.8.jar
      commons-collections-2.1.1.jar
      commons-digester-2.1.jar
      commons-discovery-0.2.jar
      commons-httpclient.jar
      commons-logging.jar
      dom4j-1.6.1.jar
      ehcache-1.2.3.jar
      ejb3-persistence.jar
      hibernate-annotations.jar
      hibernate-commons-annotations.jar
      hibernate-entitymanager.jar
      hibernate-validator.jar
      hibernate3.jar
      jaas.jar
      javassist.jar
      jaxen-1.1-beta-7.jar
      jaxrpc.jar
      jboss-archive-browsing.jar
      jdbc2_0-stdext.jar
      jta.jar
      log4j-1.2.11.jar
      mysql-connector-java-5.0.4-bin.jar
      org.springframework.aop-3.0.5.RELEASE.jar
      org.springframework.asm-3.0.5.RELEASE.jar
      org.springframework.aspects-3.0.5.RELEASE.jar
      org.springframework.beans-3.0.5.RELEASE.jar
      org.springframework.context-3.0.5.RELEASE.jar
      org.springframework.context.support-3.0.5.RELEASE.jar
      org.springframework.core-3.0.5.RELEASE.jar
      org.springframework.expression-3.0.5.RELEASE.jar
      org.springframework.instrument-3.0.5.RELEASE.jar
      org.springframework.instrument.tomcat-3.0.5.RELEASE.jar
      org.springframework.jdbc-3.0.5.RELEASE.jar
      org.springframework.jms-3.0.5.RELEASE.jar
      org.springframework.orm-3.0.5.RELEASE.jar
      org.springframework.oxm-3.0.5.RELEASE.jar
      org.springframework.test-3.0.5.RELEASE.jar
      org.springframework.transaction-3.0.5.RELEASE.jar
      org.springframework.web-3.0.5.RELEASE.jar
      org.springframework.web.servlet-3.0.5.RELEASE.jar
      saaj.jar 
      wsdl4j.jar
      xerces-2.6.2.jar
      xml-apis.jar

 配置文件 配置web.xml

         web.xml中須要配置Spring的配置文件(applicationContext.xml)和Spring MVC配置文件(spring-mvc.xml),配置指定全部.do的請求都由SpringDispatcherServlet類進行處理。

web.xml文件的參考配置以下:

<? xml version = " 1.0 "  encoding = " UTF-8 " ?>

< web - app xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance "  xmlns = " http://java.sun.com/xml/ns/javaee "  xmlns:web = " http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "  xsi:schemaLocation = " http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "  id = " WebApp_ID "  version = " 2.5 " >
 
< display - name > springmvctest </ display - name >
 
< welcome - file - list >
    
< welcome - file > index.html </ welcome - file >
    
< welcome - file > index.htm </ welcome - file >
    
< welcome - file > index.jsp </ welcome - file >
 
</ welcome - file - list >
 
< context - param >
        
< param - name > contextConfigLocation </ param - name >
        
< param - value > classpath:config / applicationContext.xml </ param - value >
    
</ context - param >
    
< listener >
        
< listener - class >     org.springframework.web.context.ContextLoaderListener
        
</ listener - class >
    
</ listener >
    
< servlet >
        
< servlet - name > spring - mvc </ servlet - name >
        
< servlet - class > org.springframework.web.servlet.DispatcherServlet </ servlet - class >
        
< init - param >
            
< param - name > contextConfigLocation </ param - name >
            
< param - value > classpath:config / spring - mvc.xml </ param - value >
        
</ init - param >
        
< load - on - startup > 1 </ load - on - startup >
    
</ servlet >
    
< servlet - mapping >
        
< servlet - name > spring - mvc </ servlet - name >
        
< url - pattern >* . do </ url - pattern >
    
</ servlet - mapping >
    
< filter >
        
< filter - name > encodingFilter </ filter - name >
        
< filter - class > org.springframework.web.filter.CharacterEncodingFilter </ filter - class >
        
< init - param >
            
< param - name > encoding </ param - name >
            
< param - value > UTF - 8 </ param - value >
        
</ init - param >
        
< init - param >
            
< param - name > forceEncoding </ param - name >
            
< param - value > true </ param - value >
        
</ init - param >
    
</ filter >
    
< filter - mapping >
        
< filter - name > encodingFilter </ filter - name >
        
< url - pattern > /*</url-pattern>
    </filter-mapping>
</web-app>

 

配置 spring 的配置文件

 

         Spring的配置文件applicationContext.xml文件中主要配置對Hibernate的事務的管理,該配置文件的參考配置以下:

<? 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:aop
= " http://www.springframework.org/schema/aop "
xmlns:task
= " http://www.springframework.org/schema/task "
    xsi:schemaLocation
= "
http: // www.springframework.org/schema/beans 
http: // www.springframework.org/schema/beans/spring-beans-3.0.xsd
http: // www.springframework.org/schema/context 
http: // www.springframework.org/schema/context/spring-context-3.0.xsd
    http: // www.springframework.org/schema/aop
http: // www.springframework.org/schema/aop/spring-aop-3.0.xsd
http: // www.springframework.org/schema/task   
http: // www.springframework.org/schema/task/spring-task-3.0.xsd"> 
     < context:annotation - config  />

    
<!--  掃描annotation類,過濾Service,Repository  -->
    
< context:component - scan base - package = " com.amigo "   >
    
< context:include - filter type = " annotation "  expression = " org.springframework.stereotype.Service "   />
        
< context:include - filter type = " annotation "  expression = " org.springframework.stereotype.Repository "   />
    
</ context:component - scan >

    
< bean id = " dataSource "   class = " com.mchange.v2.c3p0.ComboPooledDataSource "  destroy - method = " close " >
        
< property name = " driverClass " >
           
< value > com.mysql.jdbc.Driver </ value >
        
</ property >
        
< property name = " jdbcUrl " >
< value > jdbc:mysql: // localhost/test</value> 
         </ property >
        
< property name = " user " >
            
< value > root </ value >
        
</ property >
        
< property name = " password " >
            
< value > 123456 </ value >
        
</ property >
        
< property name = " maxPoolSize " >
            
< value > 80 </ value >
        
</ property >
        
< property name = " minPoolSize " >
            
< value > 1 </ value >
        
</ property >
        
< property name = " initialPoolSize " >
            
< value > 1 </ value >
        
</ property >
        
< property name = " maxIdleTime " >
            
< value > 20 </ value >
        
</ property >
    
</ bean >
    
< bean id = " sessionFactory "   class = " org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean " >
        
< property name = " dataSource "  ref = " dataSource " />
        
< property name = " packagesToScan "  value = " com.amigo.model* "   ></ property >
        
< property name = " hibernateProperties " >
            
< props >
                
< prop key = " hibernate.dialect " > org.hibernate.dialect.MySQLDialect </ prop >
                
< prop key = " show_sql " > true </ prop >
                
< prop key = " hibernate.jdbc.batch_size " > 20 </ prop >
            
</ props >
        
</ property >
    
</ bean >

    
<!--  不破壞數據庫,註冊SessionFactory  -->
    
< bean id = " transactionManager "   class = " org.springframework.orm.hibernate3.HibernateTransactionManager " >
        
< property name = " sessionFactory "  ref = " sessionFactory " ></ property >
    
</ bean >
    
< bean id = " transactionInterceptor "
class = " org.springframework.transaction.interceptor.TransactionInterceptor " >
        
< property name = " transactionManager "  ref = " transactionManager " ></ property >
        
< property name = " transactionAttributes " >
            
< props >
                
< prop key = " save* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " update* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " delete* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " find* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " get* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " execute* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " load* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " merge* " > PROPAGATION_REQUIRED </ prop >
                
< prop key = " add* " > PROPAGATION_REQUIRED </ prop >
            
</ props >
        
</ property >
    
</ bean >
    
< bean
class = " org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator " >
        
< property name = " beanNames " >
            
< list >
                
< value >* Service </ value >
            
</ list >
        
</ property >
        
< property name = " interceptorNames " >
            
< list >
         
< value > transactionInterceptor </ value >
            
</ list >
        
</ property >
    
</ bean >  
</ beans >


  配置 Spring MVC 配置文件

 

Spring MVC的配置文件spring-mvc.xml中主要是Controller的配置信息,該文件的參考配置以下:

<? 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:p ="http://www.springframework.org/schema/p"
xmlns:context
="http://www.springframework.org/schema/context"
xmlns:mvc
="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation
="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
   
    default-lazy-init
="true" >
    
< context:annotation-config  />
    
<!-- 使Spring支持自動檢測組件,如註解的Controller  -->
    
< context:component-scan  base-package ="com.amigo.web" />

    
< bean  id ="viewResolver"       class ="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix
="/WEB-INF"
          p:suffix
=".jsp"   />
    
    
< bean  class ="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"   />
    
<!--  啓動 Spring MVC 的註解功能,完成請求和註解 POJO 的映射  -->
    
< bean      class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
        
< property  name ="messageConverters" >
            
< list >
                
< bean  class ="org.springframework.http.converter.StringHttpMessageConverter" >  
                
</ bean >
            
</ list >
        
</ property >
    
</ bean >
</ beans >

 

 建立數據庫和表

建立test數據庫和user_info表的SQL語句以下(爲了簡便,user_info只有一個USER_NAME字段):

CREATE   DATABASE  test;
USER  test;
CREATE   TABLE  user_info (
 
USER_NAME   varchar ( 32 NOT   NULL ,
 
PRIMARY   KEY  ( USER_NAME )
) ENGINE
= InnoDB  DEFAULT  CHARSET = utf8;


3、實例代碼

3.1 DAO

BaseHibernateDao類的代碼以下所示:

package  com.amigo.dao;

import  javax.annotation.Resource;

import  org.hibernate.HibernateException;
import  org.hibernate.Session;
import  org.hibernate.SessionFactory;
import  org.springframework.dao.DataAccessException;
import  org.springframework.dao.DataAccessResourceFailureException;
import  org.springframework.dao.support.DaoSupport;
import  org.springframework.orm.hibernate3.HibernateTemplate;
import  org.springframework.orm.hibernate3.SessionFactoryUtils;

public   class  BaseHibernateDao  extends  DaoSupport {
    
private SessionFactory sessionFactory;
    
private HibernateTemplate hibernateTemplate;
    
public SessionFactory getSessionFactory() {
        
return sessionFactory;
    }


    @Resource(name
="sessionFactory")
    
public void setSessionFactory(SessionFactory sessionFactory) {
        
this.sessionFactory = sessionFactory;
        
this.hibernateTemplate=createHibernateTemplate(sessionFactory);
    }


    
public Session getSession() {
        
if (this.sessionFactory == null{
            
throw new HibernateException("Session Create Fail,SessionFactory is null!");
        }

        
return this.sessionFactory.getCurrentSession();
    }


    
protected HibernateTemplate createHibernateTemplate(
            SessionFactory sessionFactory) 
{
        
return new HibernateTemplate(sessionFactory);
    }


    @Override
    
protected void checkDaoConfig() throws IllegalArgumentException {
        
if (this.hibernateTemplate == null{
            
throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
        }

    }

    
    
protected final Session getSession(boolean allowCreate)
            
throws DataAccessResourceFailureException, IllegalStateException {
        
return (!allowCreate ? SessionFactoryUtils.getSession(
                getSessionFactory(), 
false) : SessionFactoryUtils.getSession(
                getSessionFactory(),

     
this.hibernateTemplate.getEntityInterceptor(),    this.hibernateTemplate.getJdbcExceptionTranslator()));
    }


    
protected final DataAccessException convertHibernateAccessException(
            HibernateException ex) 
{
        
return this.hibernateTemplate.convertHibernateAccessException(ex);
    }


    
protected final void releaseSession(Session session) {
        SessionFactoryUtils.releaseSession(session, getSessionFactory());
        
if(null!=session)session=null;
    }


    
public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        
this.hibernateTemplate = hibernateTemplate;
    }


    
public final HibernateTemplate getHibernateTemplate() {
        
return this.hibernateTemplate;
    }

}

USER_INFO表的DaoUserInfoDao類的代碼以下所示:

package  com.amigo.dao;
import  org.springframework.stereotype.Repository;

@Repository
public   class  UserInfoDao  extends  BaseHibernateDao  {
}

  業務邏輯層

接口類IHelloService的代碼以下:

package  com.amigo.service;
public   interface  IHelloService  {
    
public int addUser(String userName) throws Exception;;
}

實現類HelloService類的代碼以下:

package  com.amigo.service;
import  javax.annotation.Resource;

import  org.apache.commons.logging.Log;
import  org.apache.commons.logging.LogFactory;
import  org.springframework.stereotype.Repository;
import  org.springframework.stereotype.Service;

import  com.amigo.dao.UserInfoDao;
import  com.amigo.model.UserInfo;

@Service(
" helloService " )
@Repository
public   class  HelloService  implements  IHelloService  {
    
private static final Log log = LogFactory.getLog(HelloService.class);
    
private UserInfoDao userDao;

    
public UserInfoDao getUserDao() {
        
return userDao;
    }


    @Resource
    
public void setUserDao(UserInfoDao userDao) {
        
this.userDao = userDao;
    }


    @Override
    
public int addUser(String userName) throws Exception {
        log.info(
"----------------addUser---------------");
        UserInfo userInfo 
= new UserInfo();
        userInfo.setUserName(userName);
        userDao.getSession().save(userInfo);
        
return 1;
    }

}

 控制層

   控制類HelloControllor類接收userName參數,並調用相應的Service類將用戶名保存到USER_INFO表中,該類的代碼以下:

package  com.amigo.web;

import  javax.annotation.Resource;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  org.apache.commons.logging.Log;
import  org.apache.commons.logging.LogFactory;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.ResponseBody;
import  com.amigo.service.IHelloService;

@Controller
@RequestMapping(
" /test " )
public   class  HelloControllor  {
    
private static final Log log = LogFactory.getLog(HelloControllor.class);

    
private IHelloService helloService;

    
public IHelloService getHelloService() {
        
return helloService;
    }


    @Resource
    
public void setHelloService(IHelloService helloService) {
        
this.helloService = helloService;
    }


    @RequestMapping(
"/hello.do")
    
public @ResponseBody 
        String sayHello(HttpServletRequest request, HttpServletResponse response) 
throws Exception {
        request.setCharacterEncoding(
"UTF-8");
        String userName 
= request.getParameter("userName");
        log.info(
"userName=" + userName);
        
int resultCode = helloService.addUser(userName);
        String rspInfo 
= "你好!" + userName + ",操做結果碼=" + resultCode;
        response.setHeader(
"Content-type","text/html;charset=UTF-8"); 
        response.getOutputStream().write(rspInfo.getBytes(
"UTF-8"));
        
return "";
    }

}

@Controller註解標識一個控制器,@RequestMapping註解標記一個訪問的路徑;若是@RequestMapping註解在類級別上,則表示一相對路徑,在方法級別上,則標記訪問路徑;

、測試

測試時能夠經過訪問http://localhost:8080/springmvctest/test/hello.do?userName=amigo777,經過userName參數將用戶名添加到USER_INFO表中。

從實例代碼能夠看出,POJODAO層、Service層和Controller層都是採用註解的方式將servicedao注入的,減小了配置量,方便了開發工做。

a


FeedBack:
#  re: 基於註解的Spring MVC+Hiberntae簡單入門
2012-11-30 08:35 |  21
Ext.namespace('ext.ptc.part.commpartview') //定義包名 

ext.ptc.part.commpartview.setConfigure = function(){ //定義類名稱 
this.checkboxGroup = new Ext.form.CheckboxGroup({ 
layout : 'column', 
style : 'padding-left:15px;', 
items : [{ 
xtype : 'compositefield', 
items : [{ 
xtype :'checkbox', 
id : 'collapsible', 
name :'isCollapsible', 
inputValue : 'TRUE', 
boxLabel :'是否摺疊' 
}] 
},{ 
xtype : 'compositefield', 
items : [{ 
xtype :'checkbox', 
id : 'endItem', 
name :'isEndItem', 
inputValue : 'TRUE', 
boxLabel :'是否頂層部件' 
}] 
}] 

}); 

this.panel = new Ext.form.FormPanel({ 
width : 500, 
height : 300, 
border : false, 
style :'padding: 10px 20px 2px 40px;', 
border : false, 
paramsAsHash : true, 
id :'panelConfig', 
baseParams : { oid : urlOid }, 
api :{ 
load : partToolsController.geItemConfigInfo, 
submit : partToolsController.saveItemConfigInfo 
}, 
listeners : { 
'render' : function() { 
this.getForm().load({ 
success : function(form, action) { 
if(action.result.data.isDynamic == 'TRUE'){ 
document.getElementById('dynamic').checked = true; 


}, 

failure : function(form, action) { 
alert('load is failure!') 

}); 

}, 
items : [this.checkboxGroup ,{ 

buttons : [{ 
text :'保存', 
border :false, 
handler : function(){
Ext.getCmp('panelConfig').getForm().submit({ 
clientValidation: false, 
success: function(form, action) {
//表單提交成功則 
var partURL = action.result.partURL; 
var exception = action.result.exception; 
//alert(partURL); 
if(!Ext.isEmpty(partURL)){ 
location.href = partURL; 
}
}
}); 

}] 


}); 


//定義構造函數 
ext.ptc.part.commpartview.setConfigure.superclass.constructor.call(this,{ 

region : 'center', 
renderTo : Ext.getBody(), 
autoHeight : true, 
border : false, 
items : [this.simple], 
scope : this, 
items :[this.panel], 
listeners : { 
'render' : function(){ 


}); 

}; 

Ext.extend(ext.ptc.part.commpartview.setConfigure ,Ext.Panel,{ //定義繼承的父類 
//這裏定義類的方法 


}); 





//一、調用示例1 
var mainContent = Ext.getCmp('centerContent'); 
mainContent.removeAll(); 
mainContent.add(new ext.ptc.part.commpartview.setConfigure()); 
mainContent.doLayout(); 

//二、調用示例2(完整js文件)
Ext.ns('ext.ptc.viewmain'); 
Ext.onReady(function() {
this.northMenuItem = new ext.ptc.part.commpartview.setConfigure(); 
new Ext.Viewport({ 
xtype : 'panel', 
layout : 'border', 
autoWidth : true, 
border : true, 
cls : 'wcshell', 
id : "mainpage", 
defaults : { 
split : true 
}, 
items : [this.northMenuItem] 
}); 

}); 



//DirectStore 
var madstore = new Ext.data.DirectStore( 

paramsAsHash : true, 
baseParams : { 
fileJson : '', 
replaceOrLeave : '', 
partTemplate : Ext.getCmp('id_usag_model').getValue() 
}, 
api : { 
read : createUsageLinkController.getUsageLinkFromFile 
}, 
reader : new Ext.data.JsonReader({ 
fields : [ 'removeFlag', 'uploadPartNumber', 
'uploadPartNumberHref', 'description', 'quantity', 
'unit', 'lineNumber', 'isMustNeed', 'salePartType', 
'isPlanningPart', 'status', 'version', 'occName', 
'isLabelPart', 'quotePrice', 'packingABC', 
'template', 'hintkMsg', 'isSyncOK'] 
}), 
listeners : { 
scope : this, 
load : function(p, records, options) { 


搭建完成能夠開發系統框架啦

end

相關文章
相關標籤/搜索