很久不發博客了,寫博文的一個好處是能讓心靜下來,整理下以前學習過的一些知識一塊兒分享,大神路過~java
MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。傳統的 JDBC代碼一般存在以下問題:mysql
1. 頻繁對數據庫進行鏈接和關閉,形成資源浪費,性能降低。web
2. SQL代碼、preparedStatement參數、佔位符號等硬編碼到代碼中,不方便維護。spring
3. 遍歷結果集數據時,硬編碼解析表字段成java屬性,不方便維護。sql
MyBatis 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集。數據庫
MyBatis 可使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。tomcat
mybatis的核心類與會話流程以下:springboot
Configuration:讀取mybatis配置文件(SqlMapConfig.xml、mapper.xml等)->mybatis
SqlSessionFactory:根據配置文件建立會話工廠->app
SqlSession:API接口,表示和數據庫交互時的會話,定義增刪改查->
Executor:MyBatis 核心執行器,負責SQL語句的生成->
MappedStatement:負責輸入輸出的封裝。
更詳細的流程可參考其它資料。
Idea: File->new->project->Spring initializr->Next 依次輸入maven座標信息,Dependencies選擇Mysql、Mybatis。在File->Setting->Maven中配置本地Maven安裝目錄和setting.xml配置文件路徑,完成。
習慣用yml了,將application.properties改成application.yml。在 mybatis 開發包裏面,會將 druid 的配置的數據庫鏈接池變爲所須要的 DataSource 數據源對象。下文junit Test中會用到。
<dependencies> <!--mybatis 開發包--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--druid 的數據源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.31</version> </dependency> </dependencies>
CREATE DATABASE mybatis_test; USE mybatis_test; CREATE TABLE t_user( id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL , password VARCHAR(255) NOT NULL , phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
後面要進行druid 的數據源的配置,需在pom.xml文件中添加druid 依賴包。
<!--druid 的數據源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.31</version> </dependency>
yml配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
dbcp2:
min-idle: 5
initial-size: 5
max-total: 5
max-wait-millis: 200
pom中的<plugins>添加mybatis generator 自動生成代碼插件
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自動生成代碼插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build>
新增/src/main/resources/generatorConfig.xm配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 數據庫驅動:選擇你的本地硬盤上面的數據庫驅動包--> <classPathEntry location="C:\Users\hjwu\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--數據庫連接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis_test?characterEncoding=utf8" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.itpsc.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="com.itpsc.mapper.xml" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.itpsc.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <table tableName="t_user" domainObjectName="User"></table> </context> </generatorConfiguration>
運行插件生成CRUD代碼,自動生成代碼能夠提升咱們的開發效率。
可見自動生成user實體類、Mapper文件、xxxMapper.xml
啓動SpringbootMybatisDemoApplication測試
問題1
o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.itpsc]' package. Please check your configuration.
解決辦法:在SpringbootMybatisDemoApplication中註解@MapperScan("com.itpsc.mapper*")
問題2:
Unregistering JMX-exposed beans on shutdown
解決辦法:
pom.xml添加下面兩個依賴包
<!--嵌入tomcat--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <!--springboot web模塊支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
啓動成功
添加mybatis plus插件。Mybatis-Plus(簡稱MP)是一個 Mybatis 的加強工具,在 Mybatis 的基礎上只作加強不作改變,爲簡化開發、提升效率而生。
<!-- mybatis --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.7</version> </dependency>
//User.java @TableName("t_user") public class User { private Long id; private String name; private String password; private String phone; ...... } //UserMapper.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.itpsc.mapper.UserMapper" > </mapper> //UserMapper.java public interface UserMapper extends BaseMapper<User>{ } //UserService.java public interface UserService { boolean insert(User user); User query(Integer id); boolean update(User user); int delete(Integer id); } //UserServiceImpl.java @Service public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{ @Override public boolean insert(User entity) { return super.insert(entity); } @Override public User query(Integer id) { return super.selectById(id); } @Override public boolean update(User user) { return super.updateById(user); } @Override public int delete(Integer id) { return 0; } }
//SpringbootMybatisDemoApplicationTests SpringbootMybatisDemoApplicationTests.java @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootMybatisDemoApplicationTests { @Resource private DataSource dataSource; @Resource private UserService userService; @Test public void contextLoads() { } @Test public void testConnection() throws Exception { System.out.println(this.dataSource); } @Test public void testInsertUser() { User user = new User(); //user.setId(2L); user.setName("name3"); user.setPassword("123456"); user.setPhone("138777888888"); System.out.println(userService.insert(user)); } @Test public void testQueryUser() { System.out.println(userService.query(1)); } @Test public void testUpdateUser() { User user = new User(); user.setId(1L); user.setName("update name1 tow times"); user.setPassword("98764"); user.setPhone("13877711111"); System.out.println(userService.update(user)); } }
從上面能夠看出,咱們的UserMapper.xml中不用寫crud語句,Mybatis-Plus幫咱們封裝了基本的curd。下面咱們重點學習mybatis的基礎語法。
下篇預告
mybatis基礎系列(二)——(增刪改查語法、別名、輸入映射、輸出映射)