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

MyBatis笔记-快速使用

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

MyBatis笔记-快速使用

MyBatis官方文档:https://mybatis.org/mybatis-3/

完整目录结构如下

1. 创建数据库表

首先创建一个User表,便于之后的测试

建表语句

create database `mybatis`;

use `mybatis`;

create table `user` (
	`id` int(20) not null,
    `name` varchar(30) default null,
    `pwd` varchar(30) default null
)engine = innodb default charset = utf8;

insert into `user`(`id`, `name`, `pwd`) values
(1,'a','123456'),
(2,'b','123456'),
(3,'c','123456')

user 表中内容

2 导入依赖包

新建一个maven项目,pom.xml中导入相关的包



    org.mybatis
    mybatis
    3.5.10



    mysql
    mysql-connector-java
    8.0.29



    junit
    junit
    4.13.1
    test

3 数据库连接配置

在 mybatis-config.xml 中可以对 MyBatis 进行配置

官方配置文档:https://mybatis.org/mybatis-3/zh/configuration.html

下面是一个数据库连接的配置例子




    
        
            
            
                
                
                
                
                
                
            
        
    

4 获取 SqlSession 封装

将官网提供的下面三行代码封装成工具类 MyBatisUtils,便于获取 sqlSession 实例

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public class MyBatisUtils {
    private static final SqlSessionFactory sqlSessionFactory;

    static {
        String resource = "org/mybatis/example/mybatis-config.xml";
        InputStream inputStream = null;
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
5 编写实体类和接口

实体类 User

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

    // 省略 getter 和 setter 方法

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

UserMapper 接口

public interface UserMapper {
    List getUserList();
}
6 XML 定义 SQL 映射

userMapper.xml




    
        select * from user
    

7 Mapper 注册

mybatis-config.xml




    
        
            
            
                
                
                
                
            
        
    
    
    
        
    


8 Maven 资源过滤配置

maven 项目默认资源是在 resources 目录下

如果目标资源文件在其他目录下,比如userMapper 就在 src/main/java目录下,需要在配置 resources,

pom.xml


    
        
            src/main/resources
            
                ***.xml
            
            true
        
        
            src/main/java
            
                ***.xml
            
            true
        
    

9 测试执行 SQL

通过 SqlSession 实例来直接执行已映射的 SQL 语句

方式一

try (SqlSession session = sqlSessionFactory.openSession()) {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
}

方式二(推荐)

try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
}

注意:确保 SqlSession 在finally代码中或try-resource中被关闭

public class UserMapperTest extends TestCase {
    SqlSession sqlSession = MyBatisUtils.getSqlSession();;
    public void testGetUserList() {
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List userList = userMapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } finally {
          sqlSession.close();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005843.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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