MyBatis+Spring+Maven的简单整合Demo

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

项目概述

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

新建web project

如图所示(勾选Maven支持):

一路next,勾选产生web.xml

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

准备数据库表

使用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 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 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 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
  

<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:


<configuration>
  <mappers>
    <mapper resource="com/liuhao/dao/UserDao.xml"/>
  mappers>
configuration>
  • Spring配置文件,本例中我们放在/test/config/applicationContext.xml

<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配置:

<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>testdisplay-name>
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-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.0modelVersion>
  <groupId>testgroupId>
  <artifactId>testartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>warpackaging>
  <name>testname>
  <description />
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
  properties>
  <dependencies>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
    dependency>
    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.2.2version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.3.0version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>3.0.5.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.2.3version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>3.0.5.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-daoartifactId>
      <version>2.0.5version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.5version>
      <type>jartype>
      <scope>compilescope>
    dependency>
    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
    dependency>
    
    <dependency>
      <groupId>org.apache.directory.studiogroupId>
      <artifactId>org.apache.logging.log4jartifactId>
      <version>1.2.16version>
    dependency>
  dependencies>
  <build>
    <sourceDirectory>srcsourceDirectory>
    <resources>
      <resource>
        <directory>srcdirectory>
        <excludes>
          <exclude>**/*.javaexclude>
        excludes>
      resource>
    resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-pluginartifactId>
        <version>2.3.2version>
        <configuration>
          <source>1.7source>
          <target>1.7target>
        configuration>
      plugin>
      <plugin>
        <artifactId>maven-war-pluginartifactId>
        <version>2.2version>
        <configuration>
          <warSourceDirectory>${basedir}/WebRootwarSourceDirectory>
          <version>3.0version>
          <failOnMissingWebXml>falsefailOnMissingWebXml>
        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 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


您的关注是我坚持写作的动力,如果觉得有用,欢迎关注我的微信,海量学习资源免费送!

你的关注是对我最大的鼓励!

你可能感兴趣的:(JavaWeb)