码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis入门(附源码压缩包下载)

时间:2018-05-29 20:35:50      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:lis   word   4.0   SQ   cto   mode   apache   junit   web   

 首先,来个项目全景预览,文章尾部附上Demo下载链接

技术分享图片

【1】pom.xml配置(加入jar包)

<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.0</modelVersion>
  <groupId>com.zyq</groupId>
  <artifactId>test</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>test Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>test</finalName>
  </build>
</project>

【2】创建对象实体User.java

package com.zyq.entity;

public class User {

    private int id;
    private String name;
    private String phone;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPhone() {
        return phone;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", phone=" + phone + "]";
    }

}

【3】创建Dao层接口

package com.zyq.dao;

import java.util.List;

import com.zyq.entity.User;

public interface UserDao {

    /**
     * 获取所有用户
     */
    List<User> getUserList();

    /**
     * 获取单个用户
     */
    User getUserById(int id);

    /**
     * 添加用户
     */
    void addUser(User user);

    /**
     * 更新用户
     */
    void updateUser(User user);

    /**
     * 删除单个用户
     */
    void deleteUserById(int id);

}

【4】mapper.xml配置(每个语句id与Dao层接口名称需要保持一致,parameterType="user" 中的user是取的别名,详见【5】)

<?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.zyq.dao.UserDao">
    <!-- 查询用户 -->
    <select id="getUserList" resultType="user">
        SELECT * FROM user
    </select>
    <!-- 查询所有用户 -->
    <select id="getUserById" parameterType="int" resultType="user">
        SELECT * FROM user WHERE id = #{id}
    </select>
    <!-- 新增用户 -->
    <insert id="addUser" parameterType="user">
        INSERT INTO user (id, name, phone) VALUES (#{id}, #{name}, #{phone})
    </insert>
    <!-- 修改用户 -->
    <update id="updateUser" parameterType="user">
        UPDATE user SET name=#{name}, phone=#{phone} WHERE id=#{id}
    </update>
    <!-- 删除用户 -->
    <delete id="deleteUserById" parameterType="int">
        DELETE FROM user WHERE id=#{id}
    </delete>
</mapper>

【5】mybatis-config.xml配置(主要用于加载数据源信息,特别说明:数据源中的url本来是用&链接,但在xml文件中,需要用转义为&amp;)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 别名 -->
    <typeAliases>
        <typeAlias type="com.zyq.entity.User" alias="user"/>
    </typeAliases>
    <!-- 数据源 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="zyq123"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 加载mapper文件 -->
    <mappers>
        <mapper resource="mapper.xml"/>
    </mappers>
</configuration>

【6】MySessionFactory(创建session,与数据库发生交互)

package com.zyq.until;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MySessionFactory {

    private static String mybatisResource = "mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory() throws Exception{
        if (sqlSessionFactory == null) {
            InputStream inputStream = Resources.getResourceAsStream(mybatisResource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        return sqlSessionFactory;
    }

    public static SqlSession getSession(){
        try {
            return getSqlSessionFactory().openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

【7】创建表
技术分享图片

顺便表中首先插入几条数据用于测试

技术分享图片

【8】MybatisTest(测试类。特别说明:这里事务由于回滚,并不会将修改后的数据保存在数据库中)

package test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import com.zyq.dao.UserDao;
import com.zyq.entity.User;
import com.zyq.until.MySessionFactory;

public class MybatisTest {

    private SqlSession session;
    private UserDao userDao;

    @Before
    public void initSession() {
        session = MySessionFactory.getSession();
        userDao = session.getMapper(UserDao.class);
    }

    /**
     * 单元测试 :根据ID查询用户
     */
    @Test
    public void getUserByIdTest(){
        int id = 1;
        User user = userDao.getUserById(id);
        if (user != null) {
            System.out.println(user.toString());
        } else {
            System.out.println("不存在id=" + id + "的用户!");
        }
    }

    /**
     * 单元测试 :获取所有用户
     */
    @Test
    public void getUserListTest(){
        List<User> users = userDao.getUserList();
        if (users != null && !users.isEmpty()) {
            for (User user : users) {
                System.out.println(user.toString());
            }
        } else {
            System.out.println("当前数据库无用户!");
        }
    }

    /**
     * 单元测试 :添加用户
     */
    @Test
    public void addUserTest(){
        User user = new User();
        user.setId(101);
        user.setName("诸葛亮");
        user.setPhone("13256565656");
        userDao.addUser(user);
        // 检测新增是否成功
        User check = userDao.getUserById(user.getId());
        session.commit(); // 这一句释放开会提交记录到数据库,注释则不会,下同
        if (check != null) {
            System.out.println("添加成功!");
        } else {
            System.out.println("添加失败!");
        }
    }

    /**
     * 单元测试:根据ID修改用户信息
     */
    @Test
    public void updateUserTest(){
        int id = 1;
        User user = userDao.getUserById(id);
        if (user != null) {
            // 这里调用了String.format()方法,不明白的请自行百度
            System.out.println(String.format("存在id=%s的用户:%s", id, user.toString()));
            // 修改内容为在原数据后面加一个"_upd"
            user.setName(user.getName() + "_upd");
            user.setPhone(user.getPhone() + "_upd");
            userDao.updateUser(user);
            session.commit();
            // 修改后查询对比
            User check = userDao.getUserById(id);
            System.out.println("修改后的用户:" + check.toString());
        } else {
            System.out.println(String.format("不存在id=%s的用户!", id));
        }
    }

    /**
     * 单元测试:根据ID删除用户
     */
    @Test
    public void deleteUserByIdTest(){
        int id = 1;
        User user = userDao.getUserById(id);
        if (user != null) {
            System.out.println("已存在的用户:" + user.toString());
            userDao.deleteUserById(id);
            session.commit();
            // 检测删除是否成功
            User check = userDao.getUserById(id);
            if (check == null) {
                System.out.println("删除成功!");
            } else {
                System.out.println("删除失败!");
            }
        } else {
            System.out.println("不存在id=" + id + "的用户!");
        }
    }
}

以上就是一个简单的Mybatis配置及使用过程,

下面附上项目源码下载地址:提取码【5m26】

https://pan.baidu.com/s/1YPWeqUZStArXTzy3cKj9gA

 

在下载项目导入后你需要注意2点,即可到测试类进行测试:

(1)到数据库中建立一个user表,并插入几条数据,详见【7】

(2)修改数据源,如果是本地的话,则只需要修改用户名(username)和密码(password),详见【5】

 

Mybatis入门(附源码压缩包下载)

标签:lis   word   4.0   SQ   cto   mode   apache   junit   web   

原文地址:https://www.cnblogs.com/zhangyuanqiang/p/9107434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!