spring mybatis集成

本文讲spring mybatis的集成,只需按照一步步搭建,不讲原理,文末附有源码链接,有不正确的地方还请指正

首先创建表- mysql数据库

 
  

CREATE TABLE user_t (
id int(11) ,
user_name varchar(40),
password varchar(255),
age int(4),
PRIMARY KEY (id)
);

INSERT INTO user_t VALUES ("1","张三","123","25");

 

1 项目结构预览

spring mybatis集成_第1张图片

2 配置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.0modelVersion>
  <groupId>com.shangcggroupId>
  <artifactId>springmvc.mybaitsartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>springmvc.mybaits Maven Webappname>
  <url>http://maven.apache.orgurl>
  <properties>
      <spring.version>4.0.2.RELEASEspring.version>
      <mybatis.version>3.2.6mybatis.version>
  properties>
  
  <dependencies>
  
      
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    
       <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>${spring.version}version>
    dependency>
    
    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>3.1.0version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>${spring.version}version>
    dependency>
   
    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-oxmartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>${spring.version}version>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-context-supportartifactId>
        <version>${spring.version}version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>${mybatis.version}version>
    dependency>
    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>1.2.2version>
    dependency>
    
    
    <dependency>
        <groupId>javaxgroupId>
        <artifactId>javaee-apiartifactId>
        <version>7.0version>
    dependency>
        
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.30version>
    dependency>
    
    
    <dependency>
        <groupId>commons-dbcpgroupId>
        <artifactId>commons-dbcpartifactId>
        <version>1.2.2version>
    dependency>
  dependencies>
  
  <build>
    <finalName>springmvc.mybaitsfinalName>
  build>
project>

 

3 配置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"
    version="3.0">
    <display-name>Archetype Created Web Applicationdisplay-name>
    
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring-mybatis.xmlparam-value>
    context-param>
    
    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <async-supported>trueasync-supported>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    
    <servlet>
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
        <async-supported>trueasync-supported>
    servlet>
    <servlet-mapping>
        <servlet-name>SpringMVCservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    
    <welcome-file-list>
        <welcome-file>/index.jspwelcome-file>
    welcome-file-list>
    

web-app>

4 配置spring-mvc.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
                        
    
    
    <context:component-scan base-package="com.shangcg" />

    
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    bean>
    

beans>

5 添加jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://10.10.5.62:3306/cw80dev1206
username=root
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

6 配置spring-mybatis.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <context:component-scan base-package="com.shangcg" />
    
    
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" 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="${username}" />
        <property name="password" value="${password}" />
        
        <property name="initialSize" value="${initialSize}">property>
        
        <property name="maxActive" value="${maxActive}">property>
        
        <property name="maxIdle" value="${maxIdle}">property>
        
        <property name="minIdle" value="${minIdle}">property>
        
        <property name="maxWait" value="${maxWait}">property>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations" value="classpath:com/shangcg/mapping/*.xml">property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.shangcg.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
    bean>

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

beans>

7 创建javaBean

package com.shangcg.pojo;

public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

 

8 controller

package com.shangcg.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shangcg.pojo.User;
import com.shangcg.service.IUserService;


@Controller
@RequestMapping("/user")
public class UserController {
    
    @Resource
    private IUserService userService;
    
    @RequestMapping("/showUser")
    public String toIndex(HttpServletRequest request,Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        model.addAttribute("user", user);
        return "showUser";
    }
    
    //http://localhost:8080/springmvc.mybaits/user/showUser?id=1
}

9 service

package com.shangcg.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.shangcg.dao.IUserDao;
import com.shangcg.pojo.User;
import com.shangcg.service.IUserService;

@Service("userService")
public class UserServiceImpl implements IUserService {
    
    @Resource
    private IUserDao userDao;

    public User getUserById(int userId) {
        
        return this.userDao.selectByPrimaryKey(userId);
    }

    public User saveUser(User user) {
        
        return null;
    }


}

10 dao

package com.shangcg.dao;

import com.shangcg.pojo.User;

public interface IUserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

11 mapper.xml





  
    
    
    
    
  
  
  
    id, user_name, password, age
  
  
  
  
  
    delete from user_t
    where id = #{id,jdbcType=INTEGER}
  
  
  
    insert into user_t (id, user_name, password, 
      age)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER})
  
  
  
    insert into user_t
    
      <if test="id != null" >
        id,
      if>
      <if test="userName != null" >
        user_name,
      if>
      <if test="password != null" >
        password,
      if>
      <if test="age != null" >
        age,
      if>
    
    
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      if>
    
  
  
  
    update user_t
    
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      if>
    
    where id = #{id,jdbcType=INTEGER}
  
  
  
    update user_t
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  
  

13单元测试

package com.shangcg.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.shangcg.pojo.User;
import com.shangcg.service.IUserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})

public class TestMyBatis {
    
    @Resource
    private IUserService userService = null;

    @Test
    public void test1() {
        User user = userService.getUserById(1);
        System.out.println("id:" + user.getId());
        System.out.println("userName:" + user.getUserName());
        System.out.println("passWord:" + user.getPassword());
    }
}

14 输出结果:说明通过Mybatis已成功连接数据库并读取信息

 

源码地址:http://download.csdn.net/download/s418683338/10151233

 

你可能感兴趣的:(spring mybatis集成)