栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis——基础部分

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis——基础部分

一、获取MyBatis
  • maven仓库:

    
      org.mybatis
      mybatis
      x.x.x
    
    
  • Github:https://github.com/mybatis/mybatis-3/releases

  • 中文文档:https://mybatis.net.cn/getting-started.html

二、环境搭建 1.数据库搭建
CREATE TABLE `user` ( 
`id` INT ( 20 ) NOT NULL PRIMARY KEY, 
`name` VARCHAr ( 30 ) DEFAULT NULL,
`pwd` VARCHAr ( 30 ) DEFAULT NULL 
) ENGINE = INNODB DEFAULT charset = utf8

insert into `user` (`id`,`name`,`pwd`) values
(1,'chenyu','123456'),
(2,'cy','123456'),
(3,'admin','123456')
2.新建Maven项目

删除src文件夹,编写父项目的pom.xml文件



    4.0.0
    
    org.example
    myBatis
    1.0-SNAPSHOT

    
    
        
        
            mysql
            mysql-connector-java
            8.0.21
        
        
        
            org.mybatis
            mybatis
            3.5.7
        
        
        
            junit
            junit
            4.13.1
            test
        
    

3.创建一个模块
  • 编写核心配置文件 mybatis-config.xml




    
        
            
            
                
                
                
                
                
                
                
                
            
        
    

  • 编写mybatis工具类
package com.chen.utils;

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

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

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            // 使用Mybatis第一步:获取sqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例
    // SqlSession 完全包含了面向数据库执行SQL命令所需的所有方法。
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
4.编写代码
  • 实体类(pojo)
package com.chen.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", pwd='" + pwd + ''' +
                '}';
    }
}
  • Dao接口(dao)
package com.chen.mapper;

import com.chen.pojo.User;
import java.util.List;

public interface userMapper {
    List getUserList();
}
  • 接口实现类(Mapper.xml)




    
    
    
        select * from mybatis.user
    

5.测试

在src/test/java里面创建测试类

package com.chen.dao;

import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    @Test
    public void test() {
        // 1.获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            // 方式一:getMapper
            // 2.获得Mapper
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            // 3.执行SQL
            List userList = mapper.getUserList();
            // 方式二:
            // List userList = sqlSession.selectList("com.chen.mapper.UserMapper.getUserList");
            for (User user : userList) {
                System.out.println(user.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 4.关闭SqlSession
            sqlSession.close();
        }
    }
}

注意点:绑定异常

org.apache.ibatis.binding.BindingException:
Type interface com.chen.mapper.UserMapper is not known to the MapperRegistry.

MapperRegistry 不知道类型接口 com.chen.mapper.UserMapper。

解决方法:mybatis-config.xml中注册Mapper



   

注册了但是扫描不到mapper的文件需要在配置文件中添加扫描配置

解决方法:pom.xml增加配置



    
        
            src/main/resources
            
                ***.xml
            
            true
        
        
            src/main/java
            
                ***.xml
            
            true
        
    
    
    
        
            org.apache.maven.plugins
            maven-resources-plugin
            
                UTF-8
            
        
    

三、SQL基本操作 1.namespace

namespace中的包名要和Dao/mapper接口包名一致

2.select

选择,查询语句;

  • id:对应namespace接口中的方法名
  • parameterType:参数类型
  • resultType:返回值类型,可以是class也可以是基本数据类型。
3.Insert

  insert into mybatis.user (id,name,pwd) value (#{id},#{name},#{pwd});

4.Update

    update mybatis.user
    set name = #{name},pwd = #{pwd}
    where id = #{id};

5.Delete

    delete from mybatis.user where id = #{id}

6.测试

注意:增删改需要提交事务,否则所做操作无效

package com.chen.dao;

import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;
import java.util.Scanner;

public class UserMapperTest {

    @Test
    public void test() {
        // 1.获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            // 方式一:getMapper
            // 2.获得Mapper
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            // 3.执行SQL
            List userList = mapper.getUserList();
            // 方式二:
            // List userList = sqlSession.selectList("com.chen.mapper.UserMapper.getUserList");
            for (User user : userList) {
                System.out.println(user.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 4.关闭SqlSession
            sqlSession.close();
        }
    }

    @Test
    public void testGetUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user.toString());
        sqlSession.close();
    }

    @Test
    public void testAddUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int row = mapper.addUser(new User(5, "zhang", "123456"));
        if (row > 0) {
            System.out.println("增加成功!");
        }
        sqlSession.commit();
        sqlSession.close();
        this.test();
    }

    @Test
    public void testUpdateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int row = mapper.updateUser(new User(2, "chen", "123456"));
        if (row > 0) {
            System.out.println("修改成功!");
        }
        sqlSession.commit();
        this.test();
    }

    @Test
    public void testDeleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int row = mapper.deleteUser(1);
        if (row > 0) {
            System.out.println("删除成功!");
        }
        sqlSession.commit();
        this.test();
    }


}
四、SQL进阶操作 1.万能Map

好处:不受字段限制就能进行数据操作

List getUserByMap(Map map);

    select *
    from mybatis.user
    where ${where}

@Test
public void testGetUserWhere() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List userList = mapper.getUserWhere("id = 1");
    System.out.println(userList.toString());
    sqlSession.close();
}

}。

List getUserWhere(String where);

@Test
public void testGetUserWhere() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List userList = mapper.getUserWhere("id = 1");
    System.out.println(userList.toString());
    sqlSession.close();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943444.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号