[笔记]MyBatis快速入门

此为B站“黑马程序员”的JavaWeb课程p48的随手记。
视频地址:https://www.bilibili.com/video/BV1Qf4y1T7Hx?spm_id_from=333.1007.top_right_bar_window_custom_collection.content.click&vd_source=90d331db0a6318c9a7390f54595d06f1

0 准备数据库

MySQL数据库,搭配Navicat 15 for MySQL.

数据库名:mybatis-testdb

表名:users

插入数据:

-- 建库
CREATE DATABASE `mybatis-testdb`;
use `mybatis-testdb`;
-- 建表
drop table if EXISTS users;

CREATE TABLE users(
	id int PRIMARY KEY auto_increment,
	name varchar(20),
	password varchar(20),
	gender varchar(10);
	home varchar(30);
);
-- 查数据
insert into users VALUES(1,'zhangsan','123','male','Beijing');
insert into users VALUES(2,'lisi','234','female','Tianjin');
insert into users VALUES(3,'wangwu','11','male','Xian');
-- 查看
SELECT * from users;

表中数据:
[笔记]MyBatis快速入门_第1张图片

1 创建maven 导入依赖

导入mybatis, mysql和日志依赖。

		<dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.5version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.46version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.20version>
        dependency>
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-coreartifactId>
            <version>1.2.3version>
        dependency>

把logback.xml导入src.main目录,logback.xml是我从网上找的,主要起记录日志的作用。

2 编写MyBatis核心配置文件

xml内容出自https://mybatis.org/mybatis-3/zh/getting-started.html

mybatis-config.xml:


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <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-testdb?useSSL=false"/>
                <property name="username" value="lubiao"/>
                <property name="password" value="2808516"/>
            dataSource>
        environment>
    environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    mappers>
configuration>

其中“数据库连接信息”中:

第2行:驱动版本6以上的要添加全球标准时间:jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC

​ 其中mybatis-testdb为数据库名

第3行:用户名

第4行:密码

mapper标签,导入储存数据库操作的xml文件:UserMapper.xml

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
    <select id="selectAll" resultType="com.ouc.User">
        select * from users;
    select>
mapper>

需要修改:

  • mapper标签的namespace属性
  • select的id,resultType
  • select(或intert, alter, drop)中间的内容为sql语句,这里不怕报错,以sql语法为准

resultType为返回值类型,这里需要创建一个class,我这里叫User,在com.ouc下,在User类中声明与被查表字段数据类型相同的成员。

User类:

package com.ouc;

public class User {
    private int id;
    private String name;
    private String password;
    private String gender;
    private String home;
    
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", home='" + home + '\'' +
                '}';
    }
}

3 访问数据库

新建一个class,写主函数:

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. get a SqlSession object to execute sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 执行sql
        List<User> users = sqlSession.selectList("test.selectAll");

        System.out.println(users);

        //Release
        sqlSession.close();
    }
}

第3步中参数为UserMapper.xml中: [mapper标签的namespace].[select标签的id]

通过唯一的标识来执行sql语句。

4 运行结果

工程结构:
[笔记]MyBatis快速入门_第2张图片
运行结果:
[笔记]MyBatis快速入门_第3张图片

你可能感兴趣的:(mybatis,java,mysql)