整合Spring4+SpringMVC4+hibernate4+druid+fastjson

阅读更多

之前一直使用spring3+status+hibernate3做开发,但是使用的技术,好像有点老了,于是,今天研究了下Spring4+SpringMVC4+hibernate4+druid+fastjson,现将搭建项目源码分享出来,希望对你有帮助。

 

pom.xml

 


  4.0.0
  com.sofn
  sofn.cms
  war
  1.0-SNAPSHOT
  sofn.cms Maven Webapp
  http://maven.apache.org

  
    
    4.3.0.RELEASE
  

  
  
    
    
      maven
      Maven Repository Switchboard
      default
      http://repo1.maven.org/maven2
      
        false
      
    
    
    
      alibaba-opensource
      alibaba-opensource
      http://code.alibabatech.com/mvn/releases/
      default
    
    
    
      alibaba-opensource-snapshot
      alibaba-opensource-snapshot
      http://code.alibabatech.com/mvn/snapshots/
      default
    
  




  
    
    
      junit
      junit
      4.11
      test
    

    
    
      javax.servlet
      servlet-api
      3.0-alpha-1
      provided
    

    
    
      log4j
      log4j
      1.2.17
    

    
    
      javax.servlet
      jstl
      1.2
    
    
      javax.servlet.jsp
      jsp-api
      2.2.1-b03
      provided
    

    
    
      commons-fileupload
      commons-fileupload
      1.2.2
    

      
      
          com.alibaba
          fastjson
          1.2.23
      




      
      
          mysql
          mysql-connector-java
          5.1.21
      

    
    
      com.alibaba
      druid
      1.0.18
    

    
    
      org.aspectj
      aspectjweaver
      1.7.1
    

    
    
      org.hibernate
      hibernate-core
      4.2.5.Final
    
    
      org.hibernate
      hibernate-entitymanager
      4.2.5.Final
    
    
      org.hibernate
      hibernate-ehcache
      4.2.5.Final
    
    
      org.hibernate.javax.persistence
      hibernate-jpa-2.0-api
      1.0.1.Final
    

    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    

    
    
      org.springframework
      spring-core
      ${spring.version}
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-jdbc
      ${spring.version}
    
    
      org.springframework
      spring-beans
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    
    
      org.springframework
      spring-expression
      ${spring.version}
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework
      spring-test
      ${spring.version}
    

    
      junit
      junit
      RELEASE
    

  


  
    sofn.cms
  



 config.properties

 

 

#\u5C5E\u6027\u6587\u4EF6

#Oracle \u7684\u914D\u7F6E
hibernate.dialect=org.hibernate.dialect.OracleDialect
driverClassName=oracle.jdbc.driver.OracleDriver
validationQuery=SELECT 1 FROM DUAL
jdbc_url=jdbc:oracle:thin:@192.168.21.139:1521:moonl
jdbc_username=sofn_sx
jdbc_password=sofn_sx

#SQLServer \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=
#jdbc_password=

#Derby \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=
#jdbc_password=

#MySQL \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.MySQLDialect
#driverClassName=com.mysql.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:mysql://localhost:3306/sshf?useUnicode=true&characterEncoding=utf-8
#jdbc_username=root
#jdbc_password=

hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false

sessionInfoName=sessionInfo

uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached

 log4j.properties

 

 

log4j.rootLogger=INFO,A1,R

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=sshf.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.Threshold=ALL
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

 applicationContext.xml

 

 






	

	
	


	
	
		
		
		

		
		
		
		
		
		
		
		
		
		

		
		

		
		
		
		

		
		
		
		

		
		
		
		
		
		

		
		
		
	


	
	
		
		
			
				${hibernate.hbm2ddl.auto}
				${hibernate.dialect}
				${hibernate.show_sql}
				${hibernate.format_sql}
			
		

		
		
			
				classpath:hbm
			
		
	

	
	
		
	


	


	
	
		
	

	
	
		
		
	




 spring-mvc.xml

 

 




    
    
    
        
            
            
                
                    
                        text/html;charset=UTF-8
                        application/json
                    
                
                
                    
                        WriteMapNullValue
                        QuoteFieldNames
                    
                
            
        
    
    
    
        
        
        
    


    
    
        
        
        
        
        
        
    


 web.xml

 



  Archetype Created Web Application

  
    contextConfigLocation
    classpath:applicationContext.xml
  


  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    true
    
      encoding
      UTF-8
    
  

  
    encodingFilter
    /*
  

  
  
    org.springframework.web.context.ContextLoaderListener
  
  
  
    org.springframework.web.util.IntrospectorCleanupListener
  


  
    DruidWebStatFilter
    com.alibaba.druid.support.http.WebStatFilter
    
      exclusions
      *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
    
    
      sessionStatMaxCount
      2000
    
    
      sessionStatEnable
      true
    
    
      principalSessionName
      session_user_key
    
    
      profileEnable
      true
    
  

  
    DruidWebStatFilter
    /*
  


  
    DruidStatView
    com.alibaba.druid.support.http.StatViewServlet
    
      
      resetEnable
      true
    
    
      
      loginUsername
      druid
    
    
      
      loginPassword
      druid
    
  

  
    DruidStatView
    /druid/*
  


  
  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    1
    true
  

  
    SpringMVC
    
    /
  

  
    default
    *.html
  

  
    default
    *.css
  

  
    default
    *.gif
  

  
    default
    *.jpg
  

  
    default
    *.js
  

  
    default
    *.woff
  

  
    default
    *.woff2
  

  
    default
    *.ttf
  

  
    10
  

  
    /index.jsp
  


    到此,配置文件,已经编辑完成

 

 

   现在我们来做下测试

   TestSpring.java

 

package org.moon;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.moon.framework.beans.Menus;
import org.moon.framework.dao.BaseDAO;
import org.moon.framework.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.util.List;

/**
 * Created by Administrator on 2016/12/30.
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestSpring {

    private static Logger logger = Logger.getLogger(TestSpring.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private BaseService baseService;

    @Test
    public void test(){
        String hql = "from Menus vo";
        List list = (List)baseService.pageQuery(hql,0,10);
        for (Menus menus : list) {
            System.out.println(menus.getName());
        }

    }
}

 

 

    看到这里,对spring,hibernate,SpringMVC比较熟悉的同学,应该可以跑起来了,如果没有跑起来,那就把剩下的代码也贴出来。

     bean目录下

    AbstractValueObject.java

 

package org.moon.framework.beans.pub;

import java.io.Serializable;
import java.util.Date;

public abstract class AbstractValueObject implements Comparable, Serializable {

	Date ts;

	public AbstractValueObject() {
	}

	public AbstractValueObject(String pk) {
		setPrimaryKey(pk);
	}

	public String getEntityName() {
		return "";
	}

	abstract public String getPrimaryKey();

	abstract public void setPrimaryKey(String key);

	public String toString() {
		return getPrimaryKey();
	}

	public Date getTs() {
		return ts;
	}

	public void setTs(Date ts) {
		this.ts = ts;
	}

	/**
	 * 克隆一个完全相同的VO对象(前层复制)。
	 * 
	 * 创建日期:(2007-3-7 11:34:51)
	 * 
	 * @return Object
	 */
	public Object clone() {

		Object o = null;
		try {
			o = super.clone();
		} catch (CloneNotSupportedException e) {
			System.out.println("clone not supported!");
		}
		return o;
	}

	public int compareTo(Object o) {
		return 0;
	}

}

 

 

 

 

   Menus.java

 

 

package org.moon.framework.beans;

import org.moon.framework.beans.pub.AbstractValueObject;

import java.util.List;

/**
 * Created by Administrator on 2016/12/30.
 */
public class Menus extends AbstractValueObject {

    public String pk_menus;// 主键
    public String name; // 名称
    public String enname; // 英文名称
    public String action; // 请求
    public String target; // 目标
    public String rel; // 关联
    public Integer orders; // 排序
    public Boolean islock; // 是否锁定
    public String parent_pk; // 上级菜单
    public List listMenus;// 菜单子集

    //
    public String getPrimaryKey() {
        return pk_menus;
    }

    public void setPrimaryKey(String key) {
        this.pk_menus = key;
    }

    public String getPk_menus() {
        return pk_menus;
    }

    // pk_menus set
    public void setPk_menus(String pk_menus) {
        this.pk_menus = pk_menus;
    }

    // 名称 get
    public String getName() {
        return name;
    }

    // 名称 set
    public void setName(String name) {
        this.name = name;
    }

    // 英文名称 get
    public String getEnname() {
        return enname;
    }

    // 英文名称 set
    public void setEnname(String enname) {
        this.enname = enname;
    }

    // 请求 get
    public String getAction() {
        return action;
    }

    // 请求 set
    public void setAction(String action) {
        this.action = action;
    }

    // 目标 get
    public String getTarget() {
        return target;
    }

    // 目标 set
    public void setTarget(String target) {
        this.target = target;
    }

    // 关联 get
    public String getRel() {
        return rel;
    }

    // 关联 set
    public void setRel(String rel) {
        this.rel = rel;
    }

    // 排序 get
    public Integer getOrders() {
        return orders;
    }

    // 排序 set
    public void setOrders(Integer orders) {
        this.orders = orders;
    }

    // 是否锁定 get
    public Boolean getIslock() {
        return islock;
    }

    // 是否锁定 set
    public void setIslock(Boolean islock) {
        this.islock = islock;
    }

    // 上级菜单 get
    public String getParent_pk() {
        return parent_pk;
    }

    // 上级菜单 set
    public void setParent_pk(String parent_pk) {
        this.parent_pk = parent_pk;
    }

    public List getListMenus() {
        return listMenus;
    }

    public void setListMenus(List listMenus) {
        this.listMenus = listMenus;
    }

}

 

 

    dao目录下

    BaseDAO.java

    

package org.moon.framework.dao;

import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;

import javax.sql.DataSource;

public interface BaseDAO {



	/**
	 * 分页查询
	 * 
	 * @param hql
	 * @param first
	 * @param max
	 * @return
	 */
	public List pageQuery(String hql, final int first, final int max);

	/**
	 * 查询数据行数
	 * 
	 * @param hql
	 * @return
	 */
	public int queryCount(String hql);

	/**
	 * 查询所有数据
	 * 
	 * @param hql
	 * @return
	 */
	public List query(String hql);

	public List query(String hql, Object[] args);

	/**
	 * 获取当前日期
	 * 
	 * @return
	 */
	public String getDate();

	/**
	 * 获取当前时间
	 * 
	 * @return
	 */
	public String getDateTime();
	
	public JdbcTemplate getJdbcTemplate();


}

 

 

    BaseDAOImpl.java

  

package org.moon.framework.dao.impl;

import javax.annotation.Resource;
import javax.sql.DataSource;


import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.moon.framework.dao.BaseDAO;
import org.moon.framework.util.date.DateUtilServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/12/30.
 */
@Repository("baseDAO")
public class BaseDAOImpl extends HibernateDaoSupport implements BaseDAO {


    // 数据源
    @Autowired
    public DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }



    @Autowired
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }


    public List pageQuery(final String hql, final int first, final int max) {
        List list = (List) getHibernateTemplate().execute(
                new HibernateCallback() {
                    public Object doInHibernate(Session session)
                            throws HibernateException {
                        Query queryObject = session.createQuery(hql);
                        queryObject.setFirstResult(first);
                        queryObject.setMaxResults(max);
                        return queryObject.list();
                    }
                });
        return list;
    }

    /**
     * 查询某个对象的个数
     *
     * @param hql
     * @return
     */
    public int queryCount(String hql) {
        String sql = hql;
        if (sql.toLowerCase().startsWith("select ")) {
            sql = "select count(*) "
                    + hql.substring(hql.toLowerCase().indexOf("from"));
        } else {
            sql = "select count(*) " + hql;
        }
        List list = getHibernateTemplate().find(sql);
        if (list.size() == 0) {
            return 0;
        }
        return ((Long) list.get(0)).intValue();
    }

    /**
     * 查询全部数据
     */
    public List query(String hql) {

        return getHibernateTemplate().find(hql);
    }

    /**
     * 根据条件查询全部数据
     */
    public List query(String hql, Object[] args) {

        return getHibernateTemplate().find(hql, args);
    }

    public String getDate() {
        String date = DateUtilServer.dateToString(new Date(), "yyyy-MM-dd");
        return date;
    }

    public String getDateTime() {
        String datetime = DateUtilServer.dateToString(new Date(),
                "yyyy-MM-dd HH:mm:ss");
        return datetime;
    }


    public JdbcTemplate getJdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }



}

 

 

service部分

    BaseService.java

 

package org.moon.framework.service;

import org.moon.framework.beans.Menus;
import org.moon.framework.dao.BaseDAO;

/**
 * Created by Administrator on 2016/12/30.
 */
public interface BaseService extends BaseDAO {

    public void save(Object vo);

    public void delete(Object vo);

    public Object getObject(Class clzz,String pk);
}

 

 

BaseServiceImpl.java

 

 

package org.moon.framework.service.impl;

import org.moon.framework.dao.impl.BaseDAOImpl;
import org.moon.framework.service.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Administrator on 2016/12/30.
 */

@Service("baseService")
public class BaseServiceImpl extends BaseDAOImpl implements BaseService {


    /**
     * 添加数据或者修改数据  注:ts为Date类型,为乐观锁标记
     * @param vo
     */
    @Transactional(propagation= Propagation.REQUIRED)
    public void save(Object vo) {
        getHibernateTemplate().saveOrUpdate(vo);
    }


    /**
     * 数据删除
     * @param vo
     */
    @Transactional(propagation= Propagation.REQUIRED)
    public void delete(Object vo) {
        getHibernateTemplate().delete(vo);
    }


    /**
     * 获取单条数据
     * @param clzz
     * @param pk
     * @return
     */
    public Object getObject(Class clzz,String pk) {
        return getHibernateTemplate().get(clzz,pk);
    }
}

 

     Controller部份

 

package org.moon.framework.controller;

import org.moon.framework.beans.PageInfo;
import org.moon.framework.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by Administrator on 2016/12/30.
 */

@Controller
@RequestMapping(value = "/base")
public class BaseController {


    @Autowired
    private BaseService baseService;


    /**
     * 默认的获取操作的bean对象名称
     * @return
     */
    public String getBeanName(){
        return "";
    }

    /**
     * 默认查询条件
     * @return
     */
    public String getWhere(){

        return "";
    }

    /**
     * 默认的排序
     * @return
     */
    public String getOrders(){

        return "";
    }


    /**
     *
     * @param start
     * @param length
     * @return
     */
    @RequestMapping("/pageInfo")
    @ResponseBody
    public PageInfo pageList(int start,int length,Object vo){
        PageInfo pageInfo = new PageInfo();
        String hql = "from "+getBeanName()+" vo";
        List list = baseService.pageQuery(hql,start,length);
        int count = baseService.queryCount(hql);
        pageInfo.setPageNum(start);
        pageInfo.setPageSize(length);
        pageInfo.setList(list);
        pageInfo.setTotal(count);
        return pageInfo;
    }
}

 

 

 

      BaseController.java 是用于具体实现的*Controller继承

 

     并且重写:getBeanName()方法,将Bean对象的名称放入

  

 

   如果还不清楚,那就请留言吧!

 

 

 

 

 

你可能感兴趣的:(spirng4,springmvc4,hibernate4,druid,fastjson)