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
  


    
    

    
     

    
    
        insert into
        tb_user(username,password,email,sex,age)
        values(#{username},#{password},#{email},#{sex},#{age})
    

    
    
        update tb_user set
        username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age}
        where username=#{username}
    

    
        
        delete from tb_user where username=#{username}
    

    
    


  • Mybatis应用配置文件/test/config/MyBatis-Configuration.xml:



    
        
    

  • Spring配置文件,本例中我们放在/test/config/applicationContext.xml



    
    
        
        
        
        
    
    
        
        
    
    
        
        
    
    
        
    

  • web.xml配置:


    test
    
        contextConfigLocation
        classpath:applicationContext.xml
    

    
    
        org.springframework.web.context.ContextLoaderListener
    
    
        index.jsp
    

  • 项目是基于Maven构建的,pom.xml

    4.0.0
    test
    test
    0.0.1-SNAPSHOT
    war
    test
    
    
        UTF-8
    
    
        
            javax.servlet
            javax.servlet-api
            3.1.0
        
        
            commons-dbcp
            commons-dbcp
            1.2.2
        
        
        
            org.mybatis
            mybatis
            3.3.0
        
        
            org.springframework
            spring-context
            3.0.5.RELEASE
        
        
            org.mybatis
            mybatis-spring
            1.2.3
        
        
            org.springframework
            spring-jdbc
            3.0.5.RELEASE
        
        
            org.springframework
            spring-dao
            2.0.5
        
        
        
            mysql
            mysql-connector-java
            5.1.5
            jar
            compile
        
        
        
            junit
            junit
            4.12
        
        
        
            org.apache.directory.studio
            org.apache.logging.log4j
            1.2.16
        
    
    
        src
        
            
                src
                
                    **/*.java
                
            
        
        
            
                maven-compiler-plugin
                2.3.2
                
                    1.7
                    1.7
                
            
            
                maven-war-plugin
                2.2
                
                    ${basedir}/WebRoot
                    3.0
                    false
                
            
        
    

  • 另外项目中使用了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

你可能感兴趣的:(MyBatis+Spring+Maven的简单整合Demo)