基础环境
java8、springboot2.2.13、mybatis、mysql5.x、oracle
项目配置
1.application.yml- spring:
- datasource:
- mysql1:
- username: abc
- password: 123456
- url: jdbc:mysql://127.0.0.1:3306/panda?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false
- driver-class-name: com.mysql.cj.jdbc.Driver
- # 使用druid数据源
- type: com.alibaba.druid.pool.DruidDataSource
- oracle1:
- url: jdbc:oracle:thin:@127.0.0.1:1521:oracle
- username: default
- password: 123456
- driver-class-name: oracle.jdbc.driver.OracleDriver
- # 使用druid数据源
- type: com.alibaba.druid.pool.DruidDataSource
复制代码 2.数据源配置
有三个注意点,其一是 @Primary 作用是标记哪个是主数据源(默认不指定数据源时会调用的数据源);其二是 basePackages 配置的是实际mapper路径,不同数据源路径不能混淆;其三是 setMapperLocations 配置的路径要加上 “classpath:” 前缀,才能找到对应包下的 .xml 文件。3.启动类配置
不需要再添加 @MapperScan- @SpringBootApplication(
- exclude = {
- DataSourceAutoConfiguration.class, // 排除默认数据源配置
- DataSourceTransactionManagerAutoConfiguration.class, // 排除默认事务管理器
- MybatisAutoConfiguration.class // 排除 MyBatis 默认配置
- }
- )
复制代码 4.mapper 定义示例- // 映射对象定义
- import lombok.AllArgsConstructor;
- import lombok.Builder;
- import lombok.Data;
- import lombok.NoArgsConstructor;
- import lombok.experimental.Accessors;
- import java.time.LocalDate;
- import java.time.LocalDateTime;
- @Data
- @Builder
- @Accessors(chain = true)
- @NoArgsConstructor
- @AllArgsConstructor
- public class DriverInfo {
- private Long id;
- private String driverName;
-
- }
- import org.apache.ibatis.annotations.Mapper;
- import java.util.List;
- @Mapper
- public interface DriverInfoMapper {
- List<DriverInfo> queryAll();
- List<DriverInfo> queryByCellphone(String cellphone);
- }
复制代码 对应 DriverInfoMapper.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.emmp.safedriving.dao.mapper.ds2.DriverInfoMapper">
- <resultMap id="entity" type="com.emmp.safedriving.dao.entity.DriverInfo">
- <result property="id" column="ID"/>
- <result property="driverName" column="DRIVERNAME"/>
- </resultMap>
- <select id="queryAll" resultMap="entity">
- SELECT * FROM DRIVER_INFO
- </select>
- <select id="queryByCellphone" resultMap="entity">
- SELECT * FROM DRIVER_INFO
- WHERE CELLPHONE = #{cellphone}
- ORDER BY ID DESC
- </select>
- </mapper>
复制代码 来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除 |