配置

mysql的配置

spring:
  datasource:
    url: jdbc:mysql://10.9.66.37:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: admin
    password: admin
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      connection-test-query: SELECT 1
      connection-init-sql: SELECT 1
      idle-timeout: 600000
      maximum-pool-size: 10
      minimum-idle: 10

mybatis的配置

mybatis:
  mapper-locations: classpath:/mapper/*.xml
  #config-location: classpath:/mybatis-config/*.xml
  type-aliases-package: {你的包路径}.mybatis.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    jdbc-type-for-null: "NULL"
    map-underscore-to-camel-case: true
    lazy-loading-enabled: true

其中type-aliases-package配置是指实体类,需要带上完整的包路径
mapper-locations配置是指xml映射文件,classpath:指的是resources目录下

SQL映射代码编写

实体类

@Data
public class UserTest {

    private String id;
    private String name;
    private Integer age;
    private String birthday;

}

@Data是lombok插件,作用是实现属性的get、set方法。不用lombok的话可以自己实现get、set,效果是一样的

mapper接口类

这是一个接口类,不是xml文件,根据业务的要求,实现不同的增删改查,需要与mapper.xml文件配合使用,代码示例

@Repository
public interface UserTestMapper {

    /**
     * 查询到对象列表
     * @return 对象集合
     */
    List<UserTest> findUserTestList();

}

这是查询sql中的所有数据

mapper.xml的sql映射

<?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.xw.demo.mybatis.mapper.UserTestMapper">

    <select id="findUserTestList" resultType="com.xw.demo.mybatis.entity.UserTest">
        SELECT id,name,age,birthday FROM user_test
    </select>

</mapper>

<mapper namespace ... > 这个标签的namespace 的值是填写mapper接口类的路径