您好,登錄后才能下訂單哦!
本篇文章為大家展示了mybatisPlus與多數據源怎么在springboot中使用,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
項目結構:
CREATE TABLE user ( id VARCHAR(32) NOT NULL COMMENT '主鍵ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', age INT(11) NULL DEFAULT NULL COMMENT '年齡', email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱', PRIMARY KEY (id) ); INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
1.引入依賴
pom.xml
<?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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mybatisplus-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mybatisplus-springboot</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <mysql.version>6.0.6</mysql.version> <mybatisplus.boot.version>3.1.0</mybatisplus.boot.version> <druid.version>1.1.10</druid.version> <dynamic.datasource.boot.version>2.5.4</dynamic.datasource.boot.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatisplus.boot.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>${dynamic.datasource.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.編寫配置
application.yml
spring: autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 為了某些版本的springboot @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) 無法生效 datasource: dynamic: primary: master #設置默認的數據源或者數據源組,默認值即為master,如果讀者只是單數據源只需要注釋掉slave相關配置即可,這里為了方便演示master與slave保持相同 datasource: master: url: jdbc:mysql://localhost:3306/test?serverTimezone=Hongkong&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false # serverTimezone=Hongkong 需要填上時區 username: root password: 111111 driverClassName: com.mysql.cj.jdbc.Driver slave: url: jdbc:mysql://localhost:3306/test?serverTimezone=Hongkong&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false # serverTimezone=Hongkong 需要填上時區 username: root password: 111111 driverClassName: com.mysql.cj.jdbc.Driver initial-size: 10 # 以下是連接池配置 max-active: 100 min-idle: 10 max-wait: 60000 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 #validation-query: SELECT 1 test-while-idle: true test-on-borrow: false test-on-return: false stat-view-servlet: enabled: true url-pattern: /druid/* login-username: druid login-password: 123456 filter: stat: log-slow-sql: true slow-sql-millis: 1000 merge-sql: false wall: config: multi-statement-allow: true #mybatis plus mybatis-plus: mapper-locations: classpath:mapper/**/*.xml #實體掃描,多個package用逗號或者分號分隔 typeAliasesPackage: com.example.mybatisplus.entity check-config-location: true configuration: #是否開啟自動駝峰命名規則(camel case)映射 map-underscore-to-camel-case: true #全局地開啟或關閉配置文件中的所有映射器已經配置的任何緩存 cache-enabled: false call-setters-on-nulls: true #配置JdbcTypeForNull, oracle數據庫必須配置 jdbc-type-for-null: 'null' #MyBatis 自動映射時未知列或未知屬性處理策略 NONE:不做任何處理 (默認值), WARNING:以日志的形式打印相關警告信息, FAILING:當作映射失敗處理,并拋出異常和詳細信息 auto-mapping-unknown-column-behavior: warning global-config: banner: false db-config: #主鍵類型 0:"數據庫ID自增", 1:"未設置主鍵類型",2:"用戶輸入ID (該類型可以通過自己注冊自動填充插件進行填充)", 3:"全局唯一ID (idWorker), 4:全局唯一ID (UUID), 5:字符串全局唯一ID (idWorker 的字符串表示)"; id-type: UUID #字段驗證策略 IGNORED:"忽略判斷", NOT_NULL:"非NULL判斷", NOT_EMPTY:"非空判斷", DEFAULT 默認的,一般只用于注解里(1. 在全局里代表 NOT_NULL,2. 在注解里代表 跟隨全局) field-strategy: NOT_EMPTY #數據庫大寫下劃線轉換 capital-mode: true #邏輯刪除值 logic-delete-value: 0 #邏輯未刪除值 logic-not-delete-value: 1 server: port: 7000
3.修改啟動類
MybatisplusSpringbootApplication.java
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) //去掉springboot 默認的數據源配置 @MapperScan("com.example.mybatisplus.mapper") //掃描mapper的包,或者讀者可以在對應的mapper上加上@Mapper的注解 public class MybatisplusSpringbootApplication { public static void main(String[] args) { SpringApplication.run(MybatisplusSpringbootApplication.class, args); } }
4.編寫實體
4.1 user.java
import lombok.Data; /** * user 實體類 */ @Data public class User { private String id; private String name; private Integer age; private String email; }
注:讀者請自行在開發工具安裝lombok插件,或者去掉@data注解換成setter getter方法即可
4.2 UserMapper.java
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mybatisplus.entity.User; /** * 用戶mapper */ @DS("slave") //這里是配置數據源注解,默認是master public interface UserMapper extends BaseMapper<User> { }
import com.example.mybatisplus.entity.User; import com.example.mybatisplus.mapper.UserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; /** * 簡單的測試增刪改查 */ @RunWith(SpringRunner.class) @SpringBootTest public class MybatisplusSpringbootApplicationTests { @Autowired private UserMapper userMapper; @Test public void addUser() { User user = new User(); user.setAge(200); user.setEmail("belonghuang@outlook.com"); user.setName("belongHuang"); userMapper.insert(user); } @Test public void updateUser() { User user = userMapper.selectById(1); user.setAge(300); int i = userMapper.updateById(user); if (i>0) { System.out.println("修改成功"); }else { System.out.println("修改失敗"); } } @Test public void deleteUser() { int i = userMapper.deleteById(1); if (i>0) { System.out.println("刪除成功"); }else { System.out.println("刪除失敗"); } } @Test public void selectUser() { List<User> users = userMapper.selectList(null); users.stream().map(User::getName).forEach(System.out::println);//打印出所用用戶名字 } }
上述內容就是mybatisPlus與多數據源怎么在springboot中使用,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。