mybatis入门-1

MyBatis中文官网:
http://www.mybatis.cn/

我使用的工具是idea,jdk是1.8

1.创建一个maven项目 mbs_maven

 2.引入mybatis的jar包

 1         <dependency>
 2             <groupId>mysql</groupId>
 3             <artifactId>mysql-connector-java</artifactId>
 4             <version>5.1.46</version>
 5         </dependency>
 6 
 7         <dependency>
 8             <groupId>org.mybatis</groupId>
 9             <artifactId>mybatis</artifactId>
10             <version>3.5.1</version>
11         </dependency>    

3.引入log的jar包,mybatis是需要依赖log ,引入junit测试和lobok代码简化工具

 1         <dependency>
 2             <groupId>org.projectlombok</groupId>
 3             <artifactId>lombok</artifactId>
 4             <version>1.18.10</version>
 5         </dependency>
 6 
 7         <!-- log start -->
 8         <dependency>
 9             <groupId>org.slf4j</groupId>
10             <artifactId>slf4j-api</artifactId>
11             <version>${slf4j-api.version}</version>
12         </dependency>
13         <dependency>
14             <groupId>ch.qos.logback</groupId>
15             <artifactId>logback-core</artifactId>
16             <version>${logback.version}</version>
17         </dependency>
18         <dependency>
19             <groupId>ch.qos.logback</groupId>
20             <artifactId>logback-access</artifactId>
21             <version>${logback.version}</version>
22         </dependency>
23         <dependency>
24             <groupId>ch.qos.logback</groupId>
25             <artifactId>logback-classic</artifactId>
26             <version>${logback.version}</version>
27         </dependency>
28         <!-- log end -->
29 
30         <dependency>
31             <groupId>junit</groupId>
32             <artifactId>junit</artifactId>
33             <version>4.12</version>
34         </dependency>
1     <properties>
2         <slf4j-api.version>1.7.25</slf4j-api.version>
3         <logback.version>1.1.7</logback.version>
4     </properties>

4.创建logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoder 默认配置为PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
    <logger name="dao" level="DEBUG"/>
    <!--自己的dao层-->
    <logger name="cm.mbs.dao" level="INFO"/>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

5.创建mybatis-config.xml

<?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>
    <!--使用logback的配置-->
    <settings>
        <setting name="logPrefix" value="dao." />
    </settings>
    <!--<settings>-->
        <!--&lt;!&ndash; 指定使用LOG4J输出日志 &ndash;&gt;-->
        <!--<setting name="logImpl" value="LOG4J"/>-->
    <!--</settings>-->
    <typeAliases>
        <!-- 配置包的别名,通常在使用类时需要使用类的全限定名称,使用该配置后只要直接使用类名即可 -->
        <package name="cm.mbs.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 在src/main/resources目录下创建mapper目录 -->
        <mapper resource="mapper/UserMapper.xml" />
    </mappers>
</configuration>

6.创建数据库表

/*
 Navicat Premium Data Transfer

 Source Server         : localhost_3306
 Source Server Type    : MySQL
 Source Server Version : 50726
 Source Host           : localhost:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 50726
 File Encoding         : 65001

 Date: 25/10/2019 09:50:24
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `Id` bigint(20) NOT NULL AUTO_INCREMENT,
  `UserName` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Password` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`Id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, '张三', '123456');
INSERT INTO `t_user` VALUES (2, '李四', '123456');

SET FOREIGN_KEY_CHECKS = 1;

7.创建实体类

@Data  //这个是lombok的注解,为每一个私有属性创建get set方法
@NoArgsConstructor  //lombok 无参构造器
public class User {

    private Long id;
    private String userName;
    private String password;

}

8.创建dao

public interface UserMapper {

    List<User> selectAll();

    Integer addUser(User user);

    Integer updateUser(User user);

    Integer delUser(Integer id);

}

9.创建UserMapper.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="cm.mbs.dao.UserMapper">

    <select id="selectAll" resultType="User">
        select Id,UserName,Password from t_user
    </select>

    <insert id="addUser" parameterType="cm.mbs.entity.User" >
        INSERT INTO t_user (UserName,Password) VALUES ( #{userName}, #{password})
    </insert>

    <update id="updateUser" parameterType="cm.mbs.entity.User">
        update t_user set UserName = #{userName} ,Password = #{password} where id = #{id}
    </update>

    <delete id="delUser" parameterType="int">
        delete from t_user where Id = #{id}
    </delete>





</mapper>

10.编写测试类

package cm.mbs.dao;

import cm.mbs.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Description: example
 * Created by SMO992079 on 2019/10/22 9:53
 */
public class UserMapperTest {

    private static SqlSessionFactory sqlSessionFactory;


    @BeforeClass
    public static void init() {
        InputStream is = null;
        try {
            String resource = "mybatis-config.xml";
            is = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testSelectAll() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
//            List<User> list = sqlSession.selectList("selectAll");
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.selectAll();
            for (User user : users) {
                System.out.println(user.getUserName() + "  " + user.getPassword());
            }
        }
    }

    @Test
    public void testAddUser(){
        User user = new User("张三","123123213");
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Integer integer = mapper.addUser(user);
            System.out.println(integer);
        }
    }
    @Test
    public void testUpdateUser(){
        User user = new User(1,"张三","123123213");
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Integer integer = mapper.updateUser(user);
            System.out.println(integer);
        }
    }
    @Test
    public void testDelUser(){
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Integer integer = mapper.delUser(1);
            System.out.println(integer);
        }
    }



}

11.mybatis的启动理解

  1. 构建sqlSessionFactory (UserMapperTest.java)

// 指定全局配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream is = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

  2. 打开sqlSession对话,并执行sql (UserMapperTest.java)

// 获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 操作CRUD,指定statement,规则:命名空间+“.”+statementId
List<User> list = sqlSession.selectList("selectAll");
// 这个地方也可以使用 getMapper来获取mapper对象例如
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 执行查询方法
List<User> users = mapper.selectAll();
原文地址:https://www.cnblogs.com/L-o-g-i-c/p/11724844.html