MyBatis+Spring+Maven的简单整合Demo

本文主要是示范基于Maven的MyBatis+Spring的简单使用,其中主要涉及到的是MyBatis的配置使用,另外还有部分log4j的配置使用。

项目概述

本文项目是基于MyEclipse、JDK1.7、MySQL进行开发的,主要功能是通过MyBatis实现对User这个Bean类进行增删改查操作。
先展示下整个项目的结构:
MyBatis+Spring+Maven的简单整合Demo_第1张图片

新建web project

如图所示(勾选Maven支持):
MyBatis+Spring+Maven的简单整合Demo_第2张图片

一路next,勾选产生web.xml
MyBatis+Spring+Maven的简单整合Demo_第3张图片

最后生成的项目pom.xml文件中会有很多乱七八糟的<dependency>,可以将他们删了,本小项目中暂时用不掉这些。

准备数据库表

使用mybatis数据库,没有就新建一个。

use mybatis;

drop table if exists tb_user;
create table tb_user( id int primary key auto_increment comment '主键', username varchar(40) not null unique comment '用户名', password varchar(40) not null comment '密码', email varchar(40) comment '邮件', age int comment '年龄', sex char(2) not null comment '性别' );

相关的Java处理类

  • 数据库表对应的实体类User.java
    (省略了相关的getter和setter)
package com.liuhao.entity;

public class User {
  private int id;
  private String username;
  private String password;
  private String sex;
  private String email;
  private int age;

  //getter() and setter () 
}
  • UserDao.java,可以对User进行插入、更新、删除、查找、列出所有等操作:
package com.liuhao.dao;
import java.util.List;
import com.liuhao.entity.User;

public interface UserDao {
  public int insert(User user);
  public int update(User user);
  public int delete(String userName);
  public List<User> selectAll();
  public int countAll();
  public User findByUserName(String userName);
}
  • UserService接口:
package com.liuhao.service;
import java.util.List;
import com.liuhao.entity.User;

public interface UserService {
. public int insert(User user);
  public int update(User user);
  public int delete(String userName);
  public List<User> selectAll();
  public int countAll();
  public User findByUserName(String userName);
}
  • 实现service接口,执行dao操作:
package com.liuhao.service.impl;
import java.util.List;
import com.liuhao.dao.UserDao;
import com.liuhao.entity.User;
import com.liuhao.service.UserService;

public class UserServiceImpl implements UserService {

  public UserDao userDao;
  public UserDao getUserDao() {
    return userDao;
  }
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }

  @Override
  public int insert(User user) {
    return userDao.insert(user);
  }

  @Override
  public int update(User user) {
    return userDao.update(user);
  }

  @Override
  public int delete(String userName) {
    return userDao.delete(userName);
  }

  @Override
  public List<User> selectAll() {
    return userDao.selectAll();
  }

  @Override
  public int countAll() {
    return userDao.countAll();
  }

  @Override
  public User findByUserName(String userName) {
    return userDao.findByUserName(userName);
  }
}

相关配置文件

  • Mapper文件配置/test/config/com/liuhao/dao/UserDao.xml
<?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="com.liuhao.dao.UserDao">
  <!-- 查询表中记录总数 -->
  <select id="countAll" resultType="int">
    select count(*) c from tb_user
  </select>

  <!-- 查询表中的所有用户 -->
  <select id="selectAll" resultType="com.liuhao.entity.User">
    select * from tb_user order by
    username asc
  </select> 

  <!-- 向数据库中插入用户 -->
  <insert id="insert" parameterType="com.liuhao.entity.User">
    insert into
    tb_user(username,password,email,sex,age)
    values(#{username},#{password},#{email},#{sex},#{age})
  </insert>

  <!-- 更新库中的用户 -->
  <update id="update" parameterType="com.liuhao.entity.User">
    update tb_user set
    username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age}
    where username=#{username}
  </update>

    <!-- 删除用户 -->
  <delete id="delete" parameterType="String">    
    delete from tb_user where username=#{username}
  </delete>

    <!-- 根据用户名查找用户 -->
  <select id="findByUserName" parameterType="String" resultType="com.liuhao.entity.User"> 
    select * from tb_user where username=#{username}
  </select>

</mapper>
  • Mybatis应用配置文件/test/config/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/liuhao/dao/UserDao.xml"/>
  </mappers>
</configuration>
  • Spring配置文件,本例中我们放在/test/config/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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <!-- 配置数据源 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
  </bean>
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="configLocation" value="classpath:MyBatis-Configuration.xml"></property>
    <property name="dataSource" ref="dataSource" />
  </bean>
  <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.liuhao.dao.UserDao"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
  </bean>
  <bean id="userService" class="com.liuhao.service.impl.UserServiceImpl">
    <property name="userDao" ref="userDao"></property>
  </bean>
</beans>
  • 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>test</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!-- 配置上下文监听 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
  • 项目是基于Maven构建的,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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>test</name>
  <description />
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- mybatis和spring相关 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-dao</artifactId>
      <version>2.0.5</version>
    </dependency>
    <!-- MySQL数据库驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.5</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <!-- JUnit测试框架 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!-- log4j日志框架 -->
    <dependency>
      <groupId>org.apache.directory.studio</groupId>
      <artifactId>org.apache.logging.log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
          <version>3.0</version>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
  • 另外项目中使用了log4j进行日志采集,配置如下:
#log4j.rootLogger=DEBUG,CONSOLE,A1
#log4j.rootLogger=INFO,CONSOLE,A2
log4j.rootLogger=DEBUG,INFO,CONSOLE,A1,A2,A3

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %c %-5p %m%n

log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=D:/logs/debug.log
log4j.appender.A1.Threshold=INFO
log4j.appender.A1.ImmediateFlush=true
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %-25c -> %m%n

log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.File=D:/logs/log.log
log4j.appender.A2.Threshold=INFO
log4j.appender.A2.ImmediateFlush=true
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %-25c -> %m%n

log4j.appender.A3=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A3.File=D:/logs/error.log
log4j.appender.A3.Threshold=ERROR
log4j.appender.A3.ImmediateFlush=true
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %-5p %-25c -> %m%n

log4j.logger.com.springframework=DEBUG
log4j.logger.com.ibatis=DEBUG  
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG  
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG  
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG  
log4j.logger.java.sql.ResultSet=DEBUG

测试代码

如果按照上述代码进行部署,应该不会出问题。本人应为少加了MySQL的驱动,和同事搞了差不多一个上午。。。
- 基于JUnit的测试代码:

package com.liuhao.test;

import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.liuhao.entity.User;
import com.liuhao.service.UserService;

public class TestMyBatis {

  ApplicationContext context = null;
  UserService userService = null;

  @Before
  public void initContext() {
    this.context = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
    this.userService = (UserService) context.getBean("userService");
  }

  @Test
  public void TestInsert() {
    User user = new User();
    // username需要是唯一的
    user.setUsername("刘哈哈");
    user.setPassword("passtest");
    user.setEmail("[email protected]");
    user.setSex("男");
    user.setAge(23);
    userService.insert(user);
  }

  @Test
  public void TestCountAll() {
    System.out.println("数据库中的记录条数:" + userService.countAll());
  }

  @Test
  public void TestSelectAll() {
    List<User> list = userService.selectAll();
    for (int i = 0; i < list.size(); i++) {
      User user = list.get(i);
      System.out.println("用户名:" + user.getUsername() + "\t密码:"
          + user.getPassword() + "\t邮箱:" + user.getEmail());
    }
  }

  @Test
  public void TestFindByName() {
    User user = userService.findByUserName("刘哈哈");
    System.out.println("用户名:" + user.getUsername() + "\t密码:"
        + user.getPassword() + "\t邮箱:" + user.getEmail());

  }

  @Test
  public void TestUpdate() {
    User user = new User();
    user.setUsername("刘哈哈");
    user.setPassword("xxxxxxxx");
    user.setEmail("xxxxxx@163xxx");
    user.setSex("男");
    user.setAge(23);
    userService.update(user);
  }

  @Test
  public void TestDelete() {
    userService.delete("刘哈哈");
  }
}

源码下载:http://download.csdn.net/detail/bruce_6/8876565
参考:http://www.cnblogs.com/dennisit/archive/2013/04/10/3012972.html

你可能感兴趣的:(spring,maven,mybatis,mybatis)