MyBatis入门

一 简介

mybatis让程序将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成(半自动化,大部分需要程序员编写sql)满足需要sql语句。
mybatis可以将向preparedStatement中输入参数自动进行输入映射,将查询结果灵活映射成java对象。(输出映射)

二 原理
MyBatis入门_第1张图片
mabatis框架原理
三 入门程序
1 环境搭建
(1)maven jar包
    
    
      junit
      junit
      4.11
      test
    

    
    
      asm
      asm
      3.3.1
    

    
    
      cglib
      cglib
      2.2.2
    

    
    
      commons-logging
      commons-logging
      1.1.1
    

    
    
      org.javassist
      javassist
      3.17.1-GA
    

    
    
      log4j
      log4j
      1.2.17
    

    
    
      org.apache.logging.log4j
      log4j-api
      2.0
    

    
    
      org.apache.logging.log4j
      log4j-core
      2.0
    
    
    
      org.slf4j
      slf4j-api
      1.7.5
    

    
    
      org.slf4j
      slf4j-log4j12
      1.7.5
      test
    

    
    
      org.mybatis
      mybatis
      3.2.7
    

    
    
      mysql
      mysql-connector-java
      5.1.18
    
(2)log4j.properties
#Global logging configuration
#在开发环境下日志级别要设置成DEBUG,生产环境设置成info或error
log4j.rootLogger=DEBUG,stdout
#Console output
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %5p [%t] - %m%n
(3)SqlMapConfig.xml



    
    
        
            
            
            
            
                
                
                
                
            
        
    
MyBatis入门_第2张图片
环境搭建
2 根据id查询用户
(1) User Bean
package entity;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
(2) userMap.xml


        

    
   
 
    

(3) 在核心配置文件中加载映射文件
MyBatis入门_第3张图片
图片.png
(4) 测试
import 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.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

public class mybatisTest {
    @Test
    public void findUserById() throws IOException {
        //配置文件
        String resource = "SqlMapConfig.xml";
        //得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建会话工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过工厂得到SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过SqlSession操作数据库
            //第一个参数:等于 = namespace+“.”+statement的id
            //第二个参数:指定映射文件中所匹配的parameterType类型的参数
        User user = sqlSession.selectOne("test.findUserById",1);
        System.out.println(user);
        sqlSession.close();
    }
}
MyBatis入门_第4张图片
执行结果
3 根据用户名称模糊查询信息
(1) userMap.xml
...
    
    
    
...
(2) 测试
    @Test
    public void findUserByName() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List list = sqlSession.selectList("test.findUserByName","马");
        System.out.println(list);
    }
MyBatis入门_第5张图片
执行结果
4 添加用户
(1)userMap.xml
....
    
    
        
        
            SELECT LAST_INSERT_ID()
        
        INSERT INTO user (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
    
....
(2) 测试
    @Test
    public void insertUser() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername("张三");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("美国纽约");
        sqlSession.insert("test.insertUser",user);
        sqlSession.commit();
        System.out.println(user.getId());
        System.out.println(new Date());
        sqlSession.close();
    }
5 删除用户
(1)userMap.xml
....
    
    
        DELETE from user where id = #{id}
    
....
(2) 测试
    @Test
    public void deleteUser() throws IOException {
       InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       SqlSession sqlSession = sqlSessionFactory.openSession();
       sqlSession.delete("test.deleteUser",12);
        sqlSession.commit();
        sqlSession.close();
    }
6 更新用户
(1)userMap.xml
.....

    
        UPDATE user SET username = #{username},birthday = #{birthday},sex = #{sex},address = #{address} WHERE  id = #{id}
    
.....
(2) 测试
    @Test
    public void updateUser() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession= sqlSessionFactory.openSession();
        User user = new User();
        user.setId(12);
        user.setUsername("李四");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("英国伦敦");
        sqlSession.update("test.updateUser",user);
        sqlSession.commit();
        sqlSession.close();
    }

你可能感兴趣的:(MyBatis入门)