项目结构
依赖jar包
mybatis 相关
- mybatis-3.4.1.jar
- mybatis-spring-1.3.0.jar
数据库相关
- mysql-connector-java-5.1.18-bin.jar
Spring相关
- 这里可以全部导入,不做具体描述
JSTL相关
- jstl-1.2.jar
- standard-1.1.2.jar
日志相关
- commons-logging-1.1.1.jar
- log4j-1.2.17.jar
整合Spring与MyBatis
创建数据库及相关数据表
create database mybatis;
use mybatis;CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT);
INSERT INTO users(NAME, age) VALUES('Tom', 12);
INSERT INTO users(NAME, age) VALUES('Jack', 11);
编写数据表所对应的实体类User
package entities;
public class User {
private int id;
private String name;
private int age;
public User() {
super();
}
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
编写DAO接口UserDAO
package dao;
import org.springframework.stereotype.Repository;
import entities.User;
@Repository
public interface UserDAO {
/**
* 根据用户ID查询用户
*
* @param id
* @return
*/
public User getUser(int id);
}
编写映射文件userMapper.xml
编写userService
package service;
import entities.User;
public interface UserService {
/**
* 根据id查找用户
*
* @param id
* @return
*/
public User getUserByID(int id);
}
编写UserServiceImpl
package service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.UserDAO;
import entities.User;
import service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDao;
@Override
public User getUserByID(int id) {
return this.userDao.getUser(id);
}
}
编写数据库配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
编写配置文件spring-mybatis.xml
编写log4j.properties
log4j.rootLogger=info, console, log, error
###Console ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n
### log ###
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File = ${catalina.base}/logs/debug.log
log4j.appender.log.Append = true
log4j.appender.log.Threshold = DEBUG
log4j.appender.log.DatePattern='.'yyyy-MM-dd
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern = %d %p[%c:%L] - %m%n
### Error ###
log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.File = ${catalina.base}/logs/error.log
log4j.appender.error.Append = true
log4j.appender.error.Threshold = ERROR
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n
###\u8F93\u51FASQL
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
Spring与MyBatis整合结束,编写测试类
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import entities.User;
import service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:resources/spring-mybatis.xml" })
public class SMTest {
@Autowired
private UserService userService;
@Test
public void test() {
User user = userService.getUserByID(1);
System.out.println(user);
}
}
测试截图
继续整合SpringMVC
编写控制器UserController
package controller;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import entities.User;
import service.UserService;
@RequestMapping("/")
@Controller
public class UserController {
private static final String SUCCESS = "success";
@Autowired
private UserService userService;
@RequestMapping(value = "user", method = RequestMethod.GET)
public String showUser(@Param(value = "id") Integer id, Map map) {
User user = userService.getUserByID(id);
map.put("user", user);
return SUCCESS;
}
}
编写配置文件spring-mvc.xml
编写web.xml
contextConfigLocation
classpath:resources/spring-*.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
true
encoding
UTF-8
encodingFilter
/*
springDispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:resources/spring-mvc.xml
1
springDispatcherServlet
/
编写测试页面index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Index
编写结果显示页面success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Insert title here
没有该用户
用户信息
ID: ${user.id }
Name: ${user.name }
Age: ${user.age }