最近公司一个项目开发环境要求Struts2+Spring+MyBatis 框架,之前都是用Struts2+Spring+Hibernate 的。个人觉得MyBatis和Hibernate的最大区别,就是MyBatis是一个不完全的ORM框架,可自定义很多比较复杂的sql语句,比如调用 sql自定义函数和存储过程,很适合金融和门户之类的项目。而Hibernate是完全的ORM,有些时候写自定义的sql还是不太方便。好了,废话不多说,今天凭着对Hibernate的经验搭建了MyBatis,过程还挺顺利的。
1.下载和导入jar包
当然在之前得建立一个web项目或maven生成,导入的jar包可到官方下载,也可以到http://download.csdn.net/detail/u012131769/8779655下载。
2.web.xml配置 利用监听器整合spring,让应用启动时首先加载beans.xml
在web.xml添加一下代码:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:beans.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.Spring配置文件beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">
<!-- 1、注解的自动扫描,表示组件(如:@controler,@Service,@Repository,@Resource等)的扫描 -->
<context:component-scan base-package="com.huaxun.ssmtest"></context:component-scan>
<!-- 2、配置C3P0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mysite?useUnicode=true&characterEncoding=UTF8"/>
<property name="user" value="root" />
<property name="password" value="123" />
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="5" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="30" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="10"/>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5" />
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="0" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
<property name="breakAfterAcquireFailure" value="true" />
</bean>
<!-- 3、MyBatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:Mybatis_Configuration.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.huaxun.ssmtest.*" />
</bean>
<!--4、创建事务管理器,由spring负责创建 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 5、使用注解的形式管理事务 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
4.MyBatis配置文件(和Hibernate的有点类似,当然这步可以注解方式实现,不过我觉得xml还是比较直观和简洁一些)Mybatis_Configuration.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="com/huaxun/ssmtest/domain/mapper/NoteMapper.xml"/>
</mappers>
</configuration>
5.实体对象实体(随便建立来测试的)
package com.huaxun.ssmtest.domain;
import java.util.Date;
/**
* Class Name: Note.java
* Function:
* @author Yang Ji.
* @DateTime 2015年6月6日 下午1:47:52
* @version 1.0
*/
public class Note {
private Integer note_id;
private String name;
private String telephone;
private String email;
private String content;
private Date create_time = new Date();
// Getter and Setter...
}
6.Mapper配置内容,先写一个方法试试,所谓大道至简,简单的能实现,以后扩展就不难了。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="note">
<select id="selectNote" resultMap="noteRM"
parameterType="com.huaxun.ssmtest.domain.Note">
select * from note where note_id = #{note_id}
</select>
<resultMap type="com.huaxun.ssmtest.domain.Note" id="noteRM"></resultMap>
</mapper>
7.好了,MVC的Model层实体和配置都完成了,接下来进入Dao和service的管理。spring项目应尽力面向接口编程,aop才好管理。下面贴出实现类吧,Interface就不重复了。
package com.huaxun.ssmtest.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import com.huaxun.ssmtest.dao.IBaseDao;
/**
* Class Name: BaseDaoImpl.java
* Function:
* @author Yang Ji.
* @DateTime 2015年6月6日 下午2:28:14
* @version 1.0
*/
public class BaseDaoImpl<T> implements IBaseDao<T> {
private Class entityClass = getActualTypeClass(this.getClass());
public Class getActualTypeClass(Class entity) {
ParameterizedType type = (ParameterizedType) entity.getGenericSuperclass();
Class entityClass = (Class) type.getActualTypeArguments()[0];
return entityClass;
}
@Resource(name="sqlSessionFactory")
private SqlSessionFactory sessionFactory;
public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sessionFactory = sqlSessionFactory;
}
@Override
public void insert(String stateName, T t) {
this.sessionFactory.openSession().insert(stateName,t);
}
@Override
public void delete(String stateName, T t) {
this.sessionFactory.openSession().delete(stateName,t);
}
@Override
public void update(String stateName, T t) {
this.sessionFactory.openSession().delete(stateName,t);
}
@Override
public List<T> queryForParam(String stateName, T param) {
return this.sessionFactory.openSession().selectList(stateName, param);
}
@Override
public List<T> query(String stateName) {
return this.sessionFactory.openSession().selectList(stateName);
}
}
8.Note实体的Dao实现
package com.huaxun.ssmtest.dao.impl;
import org.springframework.stereotype.Repository;
import com.huaxun.ssmtest.dao.INoteDao;
import com.huaxun.ssmtest.domain.Note;
/**
* Class Name: NoteDaoImpl.java
* Function:
* @author Yang Ji.
* @DateTime 2015年6月6日 下午2:49:17
* @version 1.0
*/
@Repository(INoteDao.SERVICE_NAME)
public class NoteDaoImpl extends BaseDaoImpl<Note> implements INoteDao {
}
9.Note实体的Service实现
package com.huaxun.ssmtest.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.huaxun.ssmtest.dao.INoteDao;
import com.huaxun.ssmtest.dao.impl.BaseDaoImpl;
import com.huaxun.ssmtest.domain.Note;
import com.huaxun.ssmtest.service.NoteService;
/**
* Class Name: NoteServiceImpl.java
* Function:
* @author Yang Ji.
* @DateTime 2015年6月6日 下午2:44:05
* @version 1.0
*/
@Service(NoteService.SERVICE_NAME)
@Transactional(readOnly=true) // Remove Transaction
public class NoteServiceImpl extends BaseDaoImpl<Note> implements NoteService {
@Resource(name=INoteDao.SERVICE_NAME)
private INoteDao noteDao;
@Override
public List<Note> queryForParam(String stateName, Note param) {
return noteDao.queryForParam(stateName, param);
}
}
10.所有的都准备好了,写个测试类测试一下吧。
package com.huaxun.ssmtest.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.huaxun.ssmtest.domain.Note;
import com.huaxun.ssmtest.service.NoteService;
/**
* Class Name: NoteTest.java
* Function:
* Note实体方法测试
* @author Yang Ji.
* @DateTime 2015年6月6日 下午2:04:00
* @version 1.0
*/
public class NoteTest
{
@Test
public void selectTest(){
ApplicationContext aContext = new ClassPathXmlApplicationContext("beans.xml");
NoteService adminService = (NoteService) aContext.getBean(NoteService.SERVICE_NAME);
Note note = new Note();
note.setNote_id(4);
List<Note> notes = adminService.queryForParam("note.selectNote", note);
for(Note n : notes){
System.out.println(n.toString()+"\n");
}
}
}
11.测试成功,MVC架构Model和Controller已经完成,就差View,也就是Struts2了,最近Struts2的2.x-3.0.x出现的安全漏洞听起来挺恐怖的,建议使用3.0以后的版本,或者自己写拦截器拦截一下,不然到时候被攻击就悔不当初了。Struts2配置都是家常便饭,平时写得手都软了,就不再多说什么,上点struts配置和action的模板吧。
Web.xml中集成struts2,添加一下代码:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Struts.xml配置模板
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 修改访问的后缀名
<constant name="struts.action.extension" value=""></constant>
-->
<constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<!-- 设置为开发模式,运行时输入更多错误信息 -->
<constant name="struts.devMode" value="false"></constant>
<!-- 设置为ui简单主题 -->
<constant name="struts.yi.theme" value="simple"></constant>
<!-- 设置上传文件最大值 -->
<constant name="struts.multipart.maxSize" value="90000000"></constant>
<package name="front" namespace="/" extends="struts-default">
<!-- 用户资料管理 -->
<action name="muser_*" class="auserAction" method="{1}">
<result name="index">/front/index.jsp</result>
</action>
</package>
</struts>
Action模板
package net.hillsstudio.gmsite.view.front;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import net.hillsstudio.gmsite.domain.Area;
import net.hillsstudio.gmsite.service.IAreaService;
import net.hillsstudio.gmsite.view.BaseAction;
import net.hillsstudio.gmsite.view.model.AreaModel;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ModelDriven;
/**
* Class Name: FAreaAction.java
* Function:
* Front Area Entity Manage Action.
* @author Gym Yung.
* @DateTime 2015-4-11 下午8:26:52
* @version 1.0
*/
@SuppressWarnings("serial")
@Controller("fareaAction")
@Scope(value="prototype")
public class FAreaAction extends BaseAction implements ModelDriven<AreaModel>
{
private AreaModel areaModel = new AreaModel();
@Override
public AreaModel getModel()
{
return areaModel;
}
@Resource(name=IAreaService.SERVICE_NAME)
private IAreaService areaService;
/**
* Function:
* Query Province Data And Skip The Page of Change City Page.
* @author Gym Yung.
* @DateTime 2015-4-11 下午8:33:58
* @return
*/
public String ccp(){
try
{
List<Area> areas = areaService.findAreasByType(Area.AREA_TYPE_PROVINCE);
request.setAttribute("areas", areas);
}
catch (Exception e)
{
// e.printStackTrace();
}
return "cityChoice";
}
}