Spring ibatis Maven Mysql Junit

Spring ibatis Maven Mysql Junit开发

1. 安装maven和nexus server,以及tomcat

2. 下载eclipse,比如Kepler,并安装相应的插件,最重要的是m2e

m2e
http://download.eclipse.org/technology/m2e/releases/1.2/?d

如果遇到问题,可能会需要安装下面的插件
slf4j
http://www.slf4j.org/dist/

Helios
http://download.eclipse.org/releases/helios

Cocoon
http://cocoon.apache.org/2.2/maven-plugins/

3. 通过eclipse新建Maven项目

4. 建立附件中的目录结构

5. Java文件
User.javapackage dao.bean;

import java.io.Serializable;

public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6380960346970416195L;
private Integer id;
private String name;
private Integer sex;

public User(){}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getSex() {
return sex;
}

public void setSex(Integer sex) {
this.sex = sex;
}

}

IUserDAO.java
package dao.iface;

import dao.bean.User;
public interface IUserDAO {
public boolean add(User user) throws Exception;
}

UserDAOImpl.java 
package dao.impl;

import dao.bean.User;
import dao.iface.IUserDAO;
import util.BasicSqlSupport;

public class UserDAOImpl extends BasicSqlSupport implements IUserDAO {

@Override
public boolean add(User user) throws Exception {
boolean flag = false;
int count = this.session.insert("dao.bean.User.add",user);
if (count > 0)
flag = true;
return flag;
}

}

配置文件 

ApplicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<bean id="user" class="dao.bean.User">
<property name="name" value="yangys" />
</bean>

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="dao.iface.UserMapper"/>
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="configLocation" value="classpath:/mybatis/SqlMapConfig.xml" />
  <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/TestIbatis" />
<property name="username" value="root" />
<property name="password" value="root" />
<!-- data source configuration -->
<property name="initialSize" value="60" /><!-- initial connections -->
<property name="maxActive" value="100" /><!-- MAX connections -->
<property name="maxIdle" value="50" /><!-- MAX idle connections -->
<property name="minIdle" value="10" /><!-- MIN idle connections -->
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="validationQuery" value="select 1" />
<property name="timeBetweenEvictionRunsMillis" value="20000" />
<property name="numTestsPerEvictionRun" value="100" />
</bean>


<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="userTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pc"
expression="execution(* com.comverse.timesheet.web.business.*.*(..))" />
<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
</aop:config>



<import resource="ImplAndBusinessBeans.xml" />
<!--  <import resource="/resources/mybatis/SqlMapConfig.xml" /> -->
</beans>


ImplAndBusinessBeans.xml
<?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:sws="http://www.springframework.org/schema/web-services"
       xmlns:security="http://www.springframework.org/schema/security"
       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/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
       http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
   

<bean id="UserDAOImpl" class="dao.impl.UserDAOImpl">
<property name="session" ref="sqlSession" />
</bean>
<bean id="TestBusiness" class="test.TestUser">
<property name="IUserDAO" ref="UserDAOImpl" />
</bean>

</beans>

log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,FILEOUT
log4j.addivity.org.apache=true

# CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
#log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n

#
# FILEOUT
log4j.appender.FILEOUT=org.apache.log4j.RollingFileAppender
log4j.appender.FILEOUT.File=${catalina.home}\\file.log
log4j.appender.fileout.MaxFileSize=100000KB
# default is true,append to the file; if false, the replace the log file whenever restart system
log4j.appender.FILEOUT.Append=true
#RollingFileAppender??DatePattern????
log4j.appender.FILEOUT.layout=org.apache.log4j.PatternLayout
#log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%n

datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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"
>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfiguer">
  <property name="locations" value="classpath:/jdbc.properties"/>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
   <property name="driverClassName" value="${driver}" />
   <property name="url" value="${url}" />
   <property name="username" value="${user}"/>
   <property name="password" value="${password}"/>
   <property name="initialSize" value="60"/>
   <property name="maxActive" value="100" />
   <property name="maxIdle" value="50" />
   <property name="minIdle" value="10" />
   <property name="testWhileIdle" value="true" />
   <property name="testOnBorrow" value="false" />
   <property name="testOnReturn" value="false" />
   <property name="validationQuery" value="select 1" />
   <property name="timeBetweenEvictionRunsMillis" value="20000" />
   <property name="numTestsPerEvictionRun" value="100" />  
</bean>

<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="configLocation" value="classpath:/mybatis/mapper/SqlMapConfig.xml"/>
  <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionfactory"/>
</bean>

<import resource="ImplAndBusinessBeans.xml"/>
</beans>

User.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="dao.bean.User">
<insert id="add" parameterType="User"
useGeneratedKeys="true" keyProperty="classId">
INSERT INTO User (NAME,SEX)
VALUES(#{name},#{sex})
</insert>
</mapper>

SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="dao.bean.User" alias="User" />
</typeAliases>
<mappers>
<mapper resource="mybatis/mapper/User.xml" />
</mappers>
</configuration>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--  <!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
-->

<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"
version="2.5">

<!--  <web-app> -->
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>StripesResources</param-value>
  </context-param>
  <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>

  <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>
      classpath:/config/log4j.peroperties
    </param-value>
  </context-param>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:/config/dispatcher-servlet.xml
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>IbatisExample</groupId>
  <artifactId>learnIbatis</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>learnIbatis Maven Webapp</name>
  <url>http://maven.apache.org</url>
 
  <properties>
    <org.springframework.version>3.0.0.RELEASE</org.springframework.version>
  </properties>
 
  <dependencies>
    <!-- 
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.5.10</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.5.10</version>
    </dependency>
    -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc-portlet</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
   
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.1.1</version>
    </dependency>
   
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.1.1</version>
    </dependency>
   
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
   
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
   
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.21</version>     
    </dependency>
   
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
    </dependency>
   
    <dependency>
     <groupId>commons-dbcp</groupId>
     <artifactId>commons-dbcp</artifactId>
     <version>1.4</version>
    </dependency>
   
    <dependency>
     <groupId>commons-pool</groupId>
     <artifactId>commons-pool</artifactId>
     <version>1.4</version>
    </dependency>
   
    <dependency>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging-api</artifactId>
     <version>1.1</version>
    </dependency>
   
    <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.2.2</version>
    </dependency>
   
    <dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-io</artifactId>
     <version>1.3.2</version>
    </dependency>
   
    <dependency>
     <groupId>dom4j</groupId>
     <artifactId>dom4j</artifactId>
     <version>1.6.1</version>
    </dependency>
   
    <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.7.0</version>
    </dependency>
   
    <dependency>
     <groupId>aopalliance</groupId>
     <artifactId>aopalliance</artifactId>
     <version>1.0</version>
    </dependency>
   
   
    <dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib-nodep</artifactId>
     <version>2.2.2</version>
    </dependency>
   
   
    <dependency>
     <groupId>net.sf.json-lib</groupId>
     <artifactId>json-lib</artifactId>
     <classifier>jdk15</classifier>
     <version>2.4</version>
    </dependency>
   
    <dependency>
     <groupId>commons-beanutils</groupId>
     <artifactId>commons-beanutils</artifactId>
     <version>1.8.3</version>
    </dependency>
   
    <dependency>
     <groupId>commons-collections</groupId>
     <artifactId>commons-collections</artifactId>
     <version>3.2.1</version>
    </dependency>
   
    <dependency>
     <groupId>commons-lang</groupId>
     <artifactId>commons-lang</artifactId>
     <version>2.6</version>
    </dependency>
   
    <dependency>
     <groupId>net.sf.ezmorph</groupId>
     <artifactId>ezmorph</artifactId>
     <version>1.0.5</version>
    </dependency>
   
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>learnIbatis</finalName>
  </build>
</project>


测试文件
package test;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import util.SessionFactory;
import dao.bean.User;
import dao.iface.IUserDAO;

public class TestUser {


private IUserDAO userDAO = null;

public IUserDAO getIUserDAO() {
return userDAO;
}

public void setIUserDAO(IUserDAO userDAO) {
this.userDAO = userDAO;
}


@Test
public void add() throws Exception {
String[] contextFiles = {"config/ApplicationContext.xml"};
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(contextFiles);
User user=(User) appContext.getBean("user");
// User user = new User();
user.setName("testbyyangys");
user.setSex(1);
SqlSession session = (SqlSession)appContext.getBean("sqlSession");

try{
session.insert("dao.bean.User.add",user);
} catch (Exception e) {
throw e;
}
}
}

通过junit运行测试文件,可以看到新的数据保存到数据库中

你可能感兴趣的:(spring)