欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

02-Mybatis快速入门之一斑窥豹

程序员文章站 2024-01-29 22:49:58
...

上一篇:01-Mybatis初识https://blog.csdn.net/fsjwin/article/details/109640386
需求:写一个mysql的插入和查询

开发补助如下:
1.新建表
2.加入maven坐标、mysql驱动
3. 创建Student实体类
4.创建Dao接口
5.创建mybatis使用的配置文件sql映射文件,一个表一个,是一个xml文件 写在所在的接口目录中,名字一样
6.创建mybatis的主配置文件,一个项目中就一个,提供数据库的连接信息和sql文件(第五步中)的所在的路径信息
7.创建使用mybatis的类,访问数据库

1.新建表

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(0) NOT NULL,
  `name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_croatian_ci NOT NULL,
  `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_croatian_ci NOT NULL,
  `age` int(0) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_croatian_ci ROW_FORMAT = Dynamic;

2.加入maven坐标、mysql驱动

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.yuhl</groupId>
  <artifactId>ch01_hello</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>ch01_hello</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!--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.48</version>
    </dependency>
  </dependencies>

  <build>
    <!--编译插件-->
    <resources>
      <resource>
        <!--所在目录-->
        <directory>src/main/java</directory>
        <includes>
          <!--properties、xml均回扫描进来-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>

        </includes>
        <filtering>false</filtering>
      </resource>

      <!--包含resources文件夹以及子文件夹下所有资源-->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

特别说明,如果resources下的xml文件没有被打包进编译文件中,使用:
02-Mybatis快速入门之一斑窥豹

3. 创建Student实体类

package com.yuhl.domain;

import java.io.Serializable;

/**
 * @author yuhl
 * @Date 2020/11/12 21:02
 * @Classname Student
 * @Description TODO
 */
public class Student implements Serializable {
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    public Integer getId() {

        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }

    public Student() {
    }

    public Student(Integer id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }
}

4.创建Dao接口

package com.yuhl.dao;

import com.yuhl.domain.Student;

import java.util.List;

/**
 * @author yuhl
 * @Date 2020/11/12 21:03
 * @Classname StudentDao
 * @Description stuentDao接口
 */
public interface StudentDao {

    //获取所有Student对象
    public List<Student> selectStudents();

    //插入操作

    /**
     *
     * @param student
     * @return 插入的条数,影响的条数
     */
    public int insertStudent(Student student);
}

5.创建mybatis使用的配置文件sql映射文件,一个表一个,是一个xml文件 写在所在的接口目录中,名字一样

StudentDao.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="com.yuhl.dao.StudentDao">

    <!--插入操作-->
    <insert id="insertStudent">
        insert into student(id, name, email, age) values (#{id},#{name},#{email},#{age})
    </insert>

    <!--查询学生-->
    <select id="selectStudents" resultType="com.yuhl.domain.Student">
        select id,name,email,age from student
    </select>

    <!--
    1. 约束文件:<!DOCTYPE mapper    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    约束你使用的标签
    2. mapper 跟标签,不能改
    3. namespace 没有要求,唯一的,但是要求使用dao接口的权限定名称。com.yuhl.dao.StudentDao
    4. select 标签:可以使用特定标签,执行特殊操作
        其他:
            update:更新
            insert:插入
            delete:删除
            select:查询
                    id:你要执行的sql语句的唯一表示,mybatis会使用这个id找到唯一的值,可以自定义,但是要求使用接口中的方法名称。
                    resultType:表示sql执行后的结果的转换类型

    -->

</mapper>

6.创建mybatis的主配置文件,一个项目中就一个,提供数据库的连接信息和sql文件(第五步中)的所在的路径信息

mybatis.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>
    <!--日志的添加 可以把sql打印在控制台上-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--环境配置,熟即可的配置信息
    default 选择下面environment中的某个作为默认值即可。
    -->
    <environments default="development">
        <!--id:唯一值,可以自定义-->
        <environment id="development">
            <!--事务类型, JDBC:使用jdbc中的commit和rollback的-->
            <transactionManager type="JDBC"/>
            <!--数据源 type:连接池的类型-->
            <dataSource type="POOLED">
                <!--连接数据库的集体信息的driver、url、username、password不能改哦-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

        <!--表示生产数据库-->
        <environment id="product">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.220.11:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="kdsjfdskl"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>

        <!--sql映射文件的位置
            一个<mapper表示一个mapper文件的位置,可以使用package标签哦!
            可以加载sql文件
            可以添加多个
            注意:是路径/表示
        -->
        <mapper resource="com/yuhl/dao/StudentDao.xml"/>
        <!--<mapper resource="com/yuhl/dao/User.xml"/>-->
    </mappers>
</configuration>


<!--
    mybatis:的主配置文件
-->

7.创建使用mybatis测试的类,访问数据库

package com.yuhl;

import static org.junit.Assert.assertTrue;

import com.yuhl.domain.Student;
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.Test;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class AppTest {
    @Test
    public void test1() throws IOException {
        //主配置文件
        String conf = "mybatis.xml";
        //加载文件
        InputStream in = Resources.getResourceAsStream(conf);
        //SqlSessionFactoryBuilder:创建SqlSessionFactory
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //SqlSessionFactory 创建SqlSession
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
        //【重要】获取SqlSession对象 执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 【重要】namespace+.+id 的方式获得sql
        List<Student> studentList = sqlSession.selectList("com.yuhl.dao.StudentDao.selectStudents");
        studentList.forEach(student -> System.out.println(student));
        sqlSession.close();

    }

    @Test
    public void test2() throws IOException {
        //主配置文件
        String conf = "mybatis.xml";
        //加载文件
        InputStream in = Resources.getResourceAsStream(conf);
        //SqlSessionFactoryBuilder:创建SqlSessionFactory
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //SqlSessionFactory 创建SqlSession
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
        //【重要】获取SqlSession对象 执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 【重要】namespace+.+id 的方式获得sql
        Student studnet = new Student(1004,"rll","aaa@qq.com",20);
        int insert = sqlSession.insert("com.yuhl.dao.StudentDao.insertStudent", studnet);
        System.out.println(insert);
        sqlSession.commit();
        sqlSession.close();
    }
}

查询测试结果:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1345483087.
Setting autocommit to false on JDBC Connection [aaa@qq.com]
==>  Preparing: select id,name,email,age from student
==> Parameters: 
<==    Columns: id, name, email, age
<==        Row: 1001, 张三, aaa@qq.com, 20
<==        Row: 1002, 李四, aaa@qq.com, 28
<==        Row: 1003, yuhl, aaa@qq.com, 20
<==        Row: 1004, rll, aaa@qq.com, 20
<==      Total: 4
Student{id=1001, name='张三', email='aaa@qq.com', age=20}
Student{id=1002, name='李四', email='aaa@qq.com', age=28}
Student{id=1003, name='yuhl', email='aaa@qq.com', age=20}
Student{id=1004, name='rll', email='aaa@qq.com', age=20}
Resetting autocommit to true on JDBC Connection [aaa@qq.com]
Closing JDBC Connection [aaa@qq.com]
Returned connection 1345483087 to pool.

插入测试结果:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1579957528.
Setting autocommit to false on JDBC Connection [aaa@qq.com]
==>  Preparing: insert into student(id, name, email, age) values (?,?,?,?)
==> Parameters: 1005(Integer), 大佬(String), aaa@qq.com(String), 20(Integer)
<==    Updates: 1
1
Committing JDBC Connection [aaa@qq.com]
Resetting autocommit to true on JDBC Connection [aaa@qq.com]
Closing JDBC Connection [aaa@qq.com]
Returned connection 1579957528 to pool.

7.其他

善于参考官方文档,mybatis的中文官方文档写的特别好:

02-Mybatis快速入门之一斑窥豹
2. 切换数据库环境
02-Mybatis快速入门之一斑窥豹

8.总结

使用mybaits开发有一定的套楼,知道即可,后面我们也不会这样开发,使用boot后,你将知道什么叫丝滑,但是基础不牢地动山摇。希望大家把基础打牢固。
02-Mybatis快速入门之一斑窥豹

下一篇:03-Mybatis的关键核心类说明https://blog.csdn.net/fsjwin/article/details/109661578