写点什么

MyBatis 学习笔记之 MyBatis 入门开发

作者:fly
  • 2022 年 10 月 02 日
    山东
  • 本文字数:5351 字

    阅读完需:约 18 分钟

相关链接

MyBatis 介绍

  1. MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。

  2. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。

  3. MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。

mybatis 执行流程

DEMO

POM 依赖

<?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">    <parent>        <artifactId>mybatis-learn</artifactId>        <groupId>com.fly9</groupId>        <version>1.0-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>
<artifactId>mybatis</artifactId>
<properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties>
<dependencies> <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic --> <!-- 引入以上依赖,会自动引入 logback-classic、 logback-core、 slf4j-api 依赖--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> </dependencies>
<build> <plugins> <!--https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin --> <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> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins>
<!--IDEA是不会编译src的java目录的文件,如果需要读取,则需要手动指定哪些配置文件需要读取--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> </resources> </build></project>
复制代码

配置文件

db-connection.properties

driver=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://192.168.5.129:3306/db_learnusername=rootpassword=123456
复制代码

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>    <!-- mybatis 官网配置文档:https://mybatis.org/mybatis-3/zh/configuration.html -->
<!-- 属性,可以直接赋值,也可以外部进行配置,同一属性名以最后加载的为准 通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的则是 properties 元素中指定的属性。--> <properties resource="db-connection.properties"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </properties>
<!-- settings 官网配置:https://mybatis.org/mybatis-3/zh/configuration.html#settings --> <settings> <!-- 这是是使用logback的配置,需要在logback配置文件配置dao--> <setting name="logPrefix" value="dao."/> <!-- 使用LOG4J打印日志--> <!--<setting name="logImpl" value="LOG4J"/>--> </settings>
<!-- 实体类别名设置 --> <typeAliases> <package name="com.fly9.domain"/> </typeAliases>
<!-- 类型处理器 https://mybatis.org/mybatis-3/zh/configuration.html#typeHandlers --> <typeHandlers> </typeHandlers>
<!-- 插件(略) https://mybatis.org/mybatis-3/zh/configuration.html#plugins -->
<!--配置环境,可以配置多个环境,但是每个 SqlSessionFactory 实例只能选择一种环境。--> <environments default="development"> <environment id="development"> <!--事务管理的配置 --> <transactionManager type="JDBC"></transactionManager> <!--数据源的配置--> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 事务隔离级别,默认数据库事务隔离级别--> <!--<property name="defaultTransactionIsolationLevel" value=""/>--> </dataSource> </environment> </environments>
<!--映射器(mappers)--> <mappers> <package name="com.fly9.mapper"/> </mappers></configuration>
复制代码

logback.xml

<?xml version="1.0" encoding="UTF-8"?><configuration scan="true" scanPeriod="60 seconds" debug="false">    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">        <encoder>            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %class.%method.%L %msg  %ex{full} %n</pattern>        </encoder>    </appender>
<logger name="dao" level="DEBUG"/>
<root level="DEBUG"> <appender-ref ref="console" /> </root>
</configuration>
复制代码

代码实现

User.java

package com.fly9.domain;
import lombok.Data;
import java.io.Serializable;import java.time.LocalDateTime;
/** * @author anthony * @date 2022/4/10 */@Datapublic class User implements Serializable { private static final long serialVersionUID = 6226302148605524294L;
private Long id; private String code; private String username; private String password; private String phone; private String email; private LocalDateTime birthday; private String address; private Byte isEnable; private Byte isDelete; private Long version; private LocalDateTime gmtCreate; private String creator; private Long creatorId; private LocalDateTime gmtModified; private String modifier; private Long modifierId;}
复制代码

UserMapper.java

package com.fly9.mapper;
import com.fly9.domain.User;
import java.util.List;
/** * @author anthony * @date 2022/4/10 */public interface UserMapper { /** * 查询所有 * @return */ List<User> selectAll();}
复制代码

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="com.fly9.mapper.UserMapper">    <resultMap id="all" type="com.fly9.domain.User">        <id column="id" jdbcType="BIGINT" property="id"/>        <result column="id" jdbcType="BIGINT" property="id"/>        <result column="code" jdbcType="VARCHAR" property="code"/>        <result column="username" jdbcType="VARCHAR" property="username"/>        <result column="password" jdbcType="VARCHAR" property="password"/>        <result column="phone" jdbcType="VARCHAR" property="phone"/>        <result column="email" jdbcType="VARCHAR" property="email"/>        <result column="birthday" jdbcType="TIMESTAMP" property="birthday"/>        <result column="address" jdbcType="VARCHAR" property="address"/>        <result column="is_enable" jdbcType="TINYINT" property="isEnable"/>        <result column="is_delete" jdbcType="TINYINT" property="isDelete"/>        <result column="version" jdbcType="BIGINT" property="version"/>        <result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate"/>        <result column="creator" jdbcType="VARCHAR" property="creator"/>        <result column="creator_id" jdbcType="BIGINT" property="creatorId"/>        <result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified"/>        <result column="modifier" jdbcType="VARCHAR" property="modifier"/>        <result column="modifier_id" jdbcType="BIGINT" property="modifierId"/>    </resultMap>
<select id="selectAll" resultMap="all"> select * from user </select></mapper>
复制代码

执行

package com.fly9;
import com.fly9.domain.User;import com.fly9.mapper.UserMapper;import lombok.extern.slf4j.Slf4j;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 java.io.IOException;import java.io.Reader;import java.util.List;
/** * @author anthony * @date 2022/4/10 */@Slf4jpublic class Application { public static void main(String[] args) { try { // 读取配置文件 Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); // 构建SQL会话工厂 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // 获取会话 SqlSession sqlSession = sqlSessionFactory.openSession(); // 获取Mapper UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 执行SQL语句,获取结果 List<User> userList = userMapper.selectAll(); userList.forEach(ele -> log.info("{}", ele)); sqlSession.close(); } catch (IOException e) { log.error("the exception is {}", e.getMessage(), e); } }}
复制代码


发布于: 刚刚阅读数: 4
用户头像

fly

关注

InfoQ签约作者 2021.08.03 加入

还未添加个人简介

评论

发布
暂无评论
MyBatis 学习笔记之MyBatis入门开发_mybatis_fly_InfoQ写作社区