探索
持久层(数据持久层框架-Mybatis)

前言:

MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发,也是对jdbc代码进行了封装。

下面就聊一聊mybaits的使用

mybaits入门

1.创建user表,添加数据

create database mybatis;use mybatis;drop table if exists tb_user;create table tb_user(	id int primary key auto_increment,	username varchar(20),	password varchar(20),	gender char(1),	addr varchar(30));INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');

2.创建模块,导入坐标

<dependencies>    <!--mybatis 依赖-->    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis</artifactId>        <version>3.5.5</version>    </dependency>    <!--mysql 驱动-->    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.46</version>    </dependency>    <!--junit 单元测试-->    <dependency>        <groupId>junit</groupId>        <artifactId>junit</artifactId>        <version>4.13</version>        <scope>test</scope>    </dependency>    <!-- 添加slf4j日志api -->    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-api</artifactId>        <version>1.7.20</version>    </dependency>    <!-- 添加logback-classic依赖 -->    <dependency>        <groupId>ch.qos.logback</groupId>        <artifactId>logback-classic</artifactId>        <version>1.2.3</version>    </dependency>    <!-- 添加logback-core依赖 -->    <dependency>        <groupId>ch.qos.logback</groupId>        <artifactId>logback-core</artifactId>        <version>1.2.3</version>    </dependency></dependencies>

注意:需要在项目的 resources 目录下创建logback的配置文件

3.编写 MyBatis 核心配置文件,替换连接信息解决硬编码问题,在模块下的 resources 目录下创建mybatis的配置文件 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>    <typeAliases>        <package name="com.itma.pojo"/>    </typeAliases>        <!--    environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment    -->    <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:///mybatis?useSSL=false"/>                <property name="username" value="root"/>                <property name="password" value="1234"/>            </dataSource>        </environment>        <environment id="test">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <!--数据库连接信息-->                <property name="driver" value="com.mysql.jdbc.Driver"/>                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>                <property name="username" value="root"/>                <property name="password" value="1234"/>            </dataSource>        </environment>    </environments>    <mappers>       <!--加载sql映射文件-->       <mapper resource="UserMapper.xml"/>    </mappers></configuration>

4.编写 SQL 映射文件,统一管理sql语句,解决硬编码问题

在模块的 resources 目录下创建映射配置文件 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="test">      <!--resultType返回值的类型    -->    <select id="selectAll" resultType="com.itheima.pojo.User">        select * from tb_user;    </select></mapper>

5.实体类编码:
com.itma.pojo 包下创建 User类:

public class User {    private int id;    private String username;    private String password;    private String gender;    private String addr;        //省略了 setter 和 getter}

6.在 com.itma 包下编写 MybatisDemo 测试类

  • 加载mybatis的核心配置文件,获取 SqlSessionFactory
  • 获取SqlSession对象,用它来执行sql
  • 执行sql
  • 释放资源
public class MyBatisDemo {    public static void main(String[] args) throws IOException {        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory        String resource = "mybatis-config.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        //2. 获取SqlSession对象,用它来执行sql        SqlSession sqlSession = sqlSessionFactory.openSession();        //3. 执行sql        List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id        System.out.println(users);        //4. 释放资源        sqlSession.close();    }}

使用mybatis实现对表的CRUD操作

com.itma.mapper 包下创建 UserMapper接口,代码如下:

public interface UserMapper {    List<User> selectAll();    User selectById(int id);}

resources 下创建 com/itma/mapper 目录,并在该目录下创建 UserMapper.xml 映射配置文件

<!--    namespace:名称空间。必须是对应接口的全限定名--><mapper namespace="com.itheima.mapper.UserMapper">    <select id="selectAll" resultType="com.itma.pojo.User">        select *        from tb_user;    </select></mapper>

com.itma 包下创建 MybatisDemo2 测试类,代码如下:

public class MyBatisDemo2 {    public static void main(String[] args) throws IOException {        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory        String resource = "mybatis-config.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        //2. 获取SqlSession对象,用它来执行sql        SqlSession sqlSession = sqlSessionFactory.openSession();        //3. 执行sql        //3.1 获取UserMapper接口的代理对象        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);        List<User> users = userMapper.selectAll();        System.out.println(users);        //4. 释放资源        sqlSession.close();    }}

以上讲解了mybtis的基本用法,希望对大家有帮助!


顶一下()     踩一下()

热门推荐

发表评论
0评