springboot项目0-1之mybatis

2023-12-21 19:09:59


一文弄懂mybatis

概述

Apache下的一个开源项目
用于操作数据库
基于java语言的持久层框架,通过XML描述符或注解将对象与存储过程或SQL语句进行映射,并提供了普通SQL查询、查询过程和高级映射登操作

优缺点

优点

灵活性高
SQL可控性强
缓存机制好
生态系统完善

缺点

性能问题:大规模数据处理能力和并发性发面略逊
配置复杂
映射错误难以追踪

配置

引入安装包

pom.xml依赖

<!--连接数据库-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

<!--mybatis springboot -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<!-- 生成实体类 ToString和get/set 方法-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.6</version>
    <scope>provided</scope>
</dependency>

<!--【数据库】数据库连接池,阿里巴巴开发的连接池,支持JDBC规范、多数据源、SQL防注入、监控等功能-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

可以使用MyBatis Generator来自动生成Java代码和MyBatis映射文件

资源配置

基于YAML格式来进行配置

application.yml,注意严格缩进!!!

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/jdbc?useSSL=false&autoReconnect=true&characterEncoding=utf8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 12345678
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 8
      max-active: 16
      min-idle: 1
      max-wait: 60000

mybatis:
  check-config-location: true
  config-location: "classpath:mybatis/mybatis-config.xml"
  # Mapper XML文件存放路径
  mapper-locations: "classpath:mybatis/mapper/*.xml"
  type-aliases-package: "com.example.ideaspringboot.entity"
基于xml配置文件配置

resource/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>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="60"/>
        <setting name="mapUnderscoreToCamelCase" value="false"/>
    </settings>
</configuration>

基于注解进行配置
// 实体类
public class User {
    private Long id;
    private String username;
    private Integer age;
    // getter、setter方法省略
}

// Dao接口
@Mapper
public interface UserDao {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findById(Long id);

    @Insert("INSERT INTO user(username, age) VALUES (#{username}, #{age})")
    int save(User user);

    @Update("UPDATE user SET username = #{username}, age = #{age} WHERE id = #{id}")
    int update(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    int deleteById(Long id);
}

// 配置类
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));

        return sessionFactory.getObject();
    }
}

mapper与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.example.demo.mapper.UserMapper">
    <!-- 查询操作 -->
    <!-- parameterType表示参数类型,resultType表示返回值类型 -->
    <select id="findById" parameterType="Long" resultType="User">
        SELECT *
        FROM user
        WHERE id = #{id}
    </select>

    <!-- 插入操作 -->
    <insert id="save" parameterType="User">
        INSERT INTO user(username, age)
        VALUES (#{username}, #{age})
    </insert>

    <!-- 更新操作 -->
    <update id="update" parameterType="User">
        UPDATE user SET
        username = #{username},
        age = #{age}
        WHERE id = #{id}
    </update>

    <!-- 删除操作 -->
    <delete id="deleteById" parameterType="Long">
        DELETE FROM user
        WHERE id = #{id}
    </delete>
</mapper>

文章来源:https://blog.csdn.net/weixin_40970987/article/details/131962333
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。