SpringBoot integrates MyBatis and MyBatis-Plus

Summary of Java knowledge points: If you want to see it, you can enter it from here

2.10. Integrate MyBatis

  1. Import the MyBatis launcher

    <!--mybatis的启动器-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    
  2. Configure Mybatis properties in the yml file (you can import the XML configuration file of mybatis)

    <?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>
        <!--setting设置-->
        <settings>
            <!--日志STDOUT_LOGGING和LOG4J-->
            <setting name="logImpl" value="LOG4J"/>
        </settings>
        <!--设置别名 -->
        <typeAliases>
            <package name="com.yu.springbootproject.pojo"/>
        </typeAliases>
        
    </configuration>
    
    # mybatis的配置
    mybatis:
      config-location: classpath:mybatis/mybatis.xml  #mybatis配置文件的位置
      mapper-locations: classpath:mapping/*.xml   #mapper的映射文件xml的位置,如果配置文件中配置了mappers,这里就不能配置了,会产生冲突
      #type-aliases-package: ***.mapper   扫描mapper接口,可以在启动类指定
      #configuration:
        #map-underscore-to-camel-case: true       默认开启驼峰命名法和 config-location 有冲突,只能写一个
    
  3. Starts scanning for class add-ons

    @SpringBootApplication
    @MapperScan("xxxx.项目名.mapper")
    public class SpringbootprojectApplication {
          
          
        public static void main(String[] args) {
          
          
            SpringApplication.run(SpringbootprojectApplication.class, args);
        }
    }
    
  4. Add log4j log

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
    log4j.rootLogger=DEBUG,console,file
    #控制台输出的相关设置
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target=System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] [%c] [%p] -%m%n
    #文件输出的相关设置
    #log4j.appender.file = org.apache.log4j.RollingFileAppender
    #log4j.appender.file.File=
    #log4j.appender.file.MaxFileSize=10mb
    #log4j.appender.file.Threshold=DEBUG
    #log4j.appender.file.layout=org.apache.log4j.PatternLayout
    #log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] [%c] [%p] -%m%n
    #日志输出级别
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.ResultSet=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    
  5. interface scan

    1. Add the annotation @Mapper to the mapper interface

      @Mapper
      public interface UserMapper {
              
              
          User selectByPrimaryKey(Integer userId);
      }
      
    2. Mapping xml file

      <?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.yu.springbootproject.mapper.UserMapper">
      
        <resultMap id="BaseResultMap" type="com.yu.springbootproject.pojo.User">
          <id column="user_id" jdbcType="INTEGER" property="userId" />
          <result column="username" jdbcType="VARCHAR" property="username" />
          <result column="password" jdbcType="VARCHAR" property="password" />
          <result column="deleted" jdbcType="BIT" property="deleted" />
        </resultMap>
      
        <sql id="Base_Column_List">
          user_id, username, `password`, deleted
        </sql>
      
        <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
          select 
          <include refid="Base_Column_List" />
          from `user`
          where user_id = #{userId,jdbcType=INTEGER}
        </select>
      </mapper>
      
    3. Write a Service and test it

      public interface UserService {
              
              
       	User selectByPrimaryKey(Integer userId);
      }
      public class UserServiceImpl implements UserService {
              
              
          @Autowired
          private UserMapper userMapper;
          @Override
          public User selectByPrimaryKey(Integer userId) {
              
              
              return userMapper.selectByPrimaryKey(userId);
          }
      }
      
      @Resource
      private UserService userService;
      @Test
      public void userMapperTest(){
              
              
          User user = userService.selectByPrimaryKey(1);
          System.out.println(user.toString());
      }
      
    image-20220923152906081

2.11、MyBatis-Plus

MyBatis-Plus is a tool based on Mybatis. It is an enhancement to MyBatis. On the basis of it, only enhancements are made without changes. It is developed to simplify the development of MyBatis and improve efficiency.

Integrating MyBatis-Plus requires removing the dependencies of MyBatis.

  1. Import the starter of MyBatis-Plus (remove the original mybatis)

    <!--mybatis-plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.2</version>
    </dependency>
    
  2. Configure mybatis-plus in the yml file

    # mybatis-plus的配置
    mybatis-plus:
      type-aliases-package: com.yu.springboot.entity  #实体类路径
      mapper-locations: classpath:mapping/*.xml    # mappee接口映射的xml文件路径
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #开启sql打印日志
        map-underscore-to-camel-case: true #将带有下划线的表字段映射为驼峰格式的实体类属性
    
  3. Start scanning for class-added packages (no change)

  4. interface scan

    1. Inherit BaseMapper<> in mapper interface

      public interface UserinfoMapper extends BaseMapper<Userinfo> {
              
              
      }
      
    2. Mapping xml file

      <mapper namespace="com.yu.springboot2test.mapper.UserinfoMapper">
        <resultMap id="BaseResultMap" type="com.yu.springboot2test.entity.Userinfo">
          <id column="id" jdbcType="BIGINT" property="id" />
          <result column="username" jdbcType="VARCHAR" property="username" />
          <result column="password" jdbcType="VARCHAR" property="password" />
          <result column="age" jdbcType="INTEGER" property="age" />
          <result column="is_deleted" jdbcType="BIT" property="isDeleted" />
          <result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate" />
          <result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified" />
        </resultMap>
          
        <sql id="Base_Column_List">
          id, username, `password`, age, is_deleted, gmt_create, gmt_modified
        </sql>
        
      </mapper>
      
    3. Write a Service and test it

      The service interface inherits IService, and the implementation class inherits ServiceImpl

      public interface UserinfoService extends IService<Userinfo> {
              
              
      }
      
      @Service
      public class UserinfoServiceImpl extends ServiceImpl<UserinfoMapper, Userinfo> implements UserinfoService {
              
              
      }
      
      @Resource
      private UserinfoMapper userinfoMapper;
      
      @Test
      public void test2(){
              
              
          Userinfo userinfo = userinfoMapper.selectById(1L);
          System.out.println(userinfo);
      }
      

      image-20230308174349798

Guess you like

Origin blog.csdn.net/yuandfeng/article/details/129709762