Spring整合Mybatis的简单示例(xml)

1、相关依赖

<dependencies>
        <!--Spring相关-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.3.3</version>
      </dependency>

        <!--数据库连接相关-->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.49</version>
      </dependency>
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.2.3</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.3.3</version>
      </dependency>

        <!--Mybatis相关-->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.6</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>2.0.6</version>
      </dependency>

  </dependencies>

2、数据库表

  • 创建一个简单的用户表,能够显示增删改查操作即可
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(12) DEFAULT NULL,
  `password` varchar(12) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8

3、实体对象与接口

com.yusian.entity.User.java

package com.yusian.entity;

public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    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;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

com.yusian.dao.UserDao.java

package com.yusian.dao;

import com.yusian.entity.User;

import java.util.List;

public interface UserDao {

    /**
     * 保存用户
     * @param user
     */
    void saveUser(User user);

    /**
     * 获取所有用户
     * @return
     */
    List<User> getUsers();
}

4、Spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--数据库连接相关配置-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"/>
        <property name="password" value="******"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://example.com/table?useSSL=false"/>
    </bean>

    <!--SqlSessionFactory对象,集成了mybatis-config的相关配置-->
    <bean id="sqlSessionBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.yusian.entity"/>
        <property name="mapperLocations">
            <list>
                <value>classpath:com/yusian/mapper/*Mapper.xml</value>
            </list>
        </property>
    </bean>

    <!--SqlSession对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionBean"/>
        <property name="basePackage" value="com.yusian.dao"/>
    </bean>
</beans>

5、Mapper配置文件

com/yusian/mapper/UserDaoMapper.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.yusian.dao.UserDao">
    <insert id="saveUser" parameterType="User">
        insert into t_user(username, password) values(#{username}, #{password})
    </insert>

    <select id="getUsers" resultType="User">
        select * from t_user
    </select>
</mapper>

6、测试

package com.yusian.test;

import com.yusian.dao.UserDao;
import com.yusian.entity.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class mybatisTest {

    @Test
    public void insertTest() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) ctx.getBean("userDao");
        userDao.saveUser(new User("someOne", "999999"));
    }

    @Test
    public void selectTest() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) ctx.getBean("userDao");
        List<User> users = userDao.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

2 thoughts on “Spring整合Mybatis的简单示例(xml)

  1. Pingback: Spring整合Mybatis的简单示例(注解) | 年年有"余"

  2. Pingback: Spring整合Mybatis对事务的支持 | 年年有"余"

Leave a Reply