當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot_数据访问-整合MyBatis(二)-注解版MyBatis
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot_数据访问-整合MyBatis(二)-注解版MyBatis
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前面已經(jīng)創(chuàng)建數(shù)據(jù)表和JAVABEAN,如何用mybatis來對數(shù)據(jù)進行增刪改查,我們先說mybatis注解版的使用,我來寫上一個mapper,操作我們這個數(shù)據(jù)庫,我們放在mapper包下,我們操作department表的,Mybatis我們只需要一個interface,來寫一個接口就行了,首先要用一個注解,@Mapper,注解來告訴mybatis,指定這是一個操作數(shù)據(jù)庫的一個mapper就行了,那接下來我們就來定義方法,我們來查出一個部門,我們按照一個id來查一個部門,我們可以直接把SQL語句寫在方法上,增刪改查我們用注解的方式寫上來了,我們來寫一個Controller來測一測
package com.learn.mapper;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import com.learn.entities.Department;// 指定這是一個操作數(shù)據(jù)庫的mapper
@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")public Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);@Options(useGeneratedKeys=true,keyProperty="id")@Insert("insert into department(deptName) values(#{deptName})")public int insertDept(Department department);@Update("update department set deptName=#{deptName} where id=#{id}")public int updateDept(Department department);}
CREATE TABLE `department` (`id` int(11) NOT NULL AUTO_INCREMENT,`deptName` varchar(20) DEFAULT NULL,`principal` varchar(20) DEFAULT NULL,`functional` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
我們就叫DeptController,我就直接寫一個@RestController,不返回頁面,直接返回JSON數(shù)據(jù),我們先返回一個department,我們使用mapper查詢就行了,我們不寫service層了,id以請求參數(shù)的方式傳過來,帶上部門id,我們用占位符的方式,@PathVariable路徑變量,我們以占位符的方式取出id,查出這個內(nèi)容,讓他返回數(shù)據(jù),包括再來插入一條數(shù)據(jù),插入還是返回department,我們把所有的數(shù)據(jù)封裝成Department對象,我們來測試一下能不能進行工作http://localhost:8080/dept/1
package com.learn.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;import com.learn.entities.Department;
import com.learn.mapper.DepartmentMapper;@RestController
public class DeptController {@AutowiredDepartmentMapper departmentMapper;@GetMapping("/dept/{id}")public Department getDepartment(@PathVariable("id") Integer id) {return departmentMapper.getDeptById(id);}@GetMapping("/dept")public Department insertDept(Department department) {departmentMapper.insertDept(department);return department;}}
http://localhost:8080/dept?deptName=AA{"id":4,"deptName":"AA","principal":null,"functional":null}我們發(fā)現(xiàn)他確實插入進去了,如果想用Mybatis,想用注解版就非常簡單,只需要寫一個mapper,Mapper注解加進來就行,注解版的使用,我們不需要做任何配置,我們來搜索MybatisAutoConfiguration,包括SqlSessionFactory要用的各種屬性,MybatisProperties有各種前綴,前綴就是mybatispublic static final String MYBATIS_PREFIX = "mybatis";但是注解版什么都不用配置,我們再來插入一個BB,發(fā)現(xiàn)沒有部門id,我們想要獲取到自增id,我們可以在insert上給他設置一下,@Options(useGeneratedKeys=true,keyProperty="id")
@Insert("insert into department(deptName) values(#{deptName})")
public int insertDept(Department department);@Options里面有一個屬性,就和我們以前寫xml一樣,useGeneratedKeys,是不是使用自動生成的主鍵,寫一個true,包括告訴人家,哪個屬性是封裝主鍵的,我們用keyProperty,Department中的id屬性是用來封裝主鍵的,當插入以后主鍵會自動封裝進來,我們Controller會再次用到department,就有主鍵了,是不是我們插入的東西就能獲取到主鍵呢,發(fā)現(xiàn)自增主鍵就有了,那我們再來查詢一下,查詢也是沒問題的,這就是我們使用注解版,在不做任何配置的情況下,我們就寫我們的mapper就行了,沒什么問題,但是我們再來考慮一個小問題,給我們?nèi)萜鲃?chuàng)建SqlSessionFactory的時候,有一個configuration,就是我們配置的相關配置,@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
Configuration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {configuration = new Configuration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {for (ConfigurationCustomizer customizer : this.configurationCustomizers) {customizer.customize(configuration);}
}
factory.setConfiguration(configuration);
if (this.properties.getConfigurationProperties() != null) {factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {factory.setMapperLocations(this.properties.resolveMapperLocations());
}return factory.getObject();
}而這個相關的配置呢,這一塊還有一個ConfigurationCustomizer,就是來幫我們定制的,那我們想要改我們mybatis的相關規(guī)則,MyBatisConfig,我們也給容器中加一個ConfigurationCustomizer,這是一個接口,我們就直接來new一個ConfigurationCustomizer,沒有實現(xiàn)的方法就在內(nèi)部類里面來實現(xiàn),有一個setMapUnderscoreToCamelCase,駝峰命名發(fā)規(guī)則,這個要起作用,我們要把它return,而且還要加載容器中,我們把它@Bean,加在容器中,我們把這個配置類@org.springframework.context.annotation.Configuration,來告訴他這個是一個配置類,接下來我們來看這個配置類能不能生效
package com.learn.config;import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;@org.springframework.context.annotation.Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer() {return new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);} };}
}
這個注解用的是全類名,由于Mybatis的Configuration已經(jīng)導進來了,你就啟動一下,看我們自定義的駝峰命名規(guī)則能不能起作用,我們發(fā)現(xiàn)數(shù)據(jù)就查出來了,我們可以使用這種方式,來自定義mybatis的配置規(guī)則,我們就叫自定義mybatis的配置規(guī)則,只要把它自定義配置的源碼,大概瞅一瞅就知道該怎么做了,給容器中添加一個ConfigurationCustomizer組件就行了,跟我們以前Customer一樣,另外我們再來擴展一下,如果我們Mapper特別多的情況下,我們給每一個Mapper上標注Mapper注解,如果不標記Mapper注解,肯定是沒用的,Mapper就找不到了,就直接報錯了,自動裝配就會有問題,所以Mapper注解不可少,但是我們后來的Mapper非常多,每一個類上都來加Mapper,太麻煩了,我們來加上一個注解,叫做@MapperScan@MapperScan(value="com.learn.mapper")這里我們可以指定一個basePackages,/**
* Base packages to scan for MyBatis interfaces. Note that only interfaces
* with at least one method will be registered; concrete classes will be
* ignored.
*/
String[] basePackages() default {};寫value值也是一樣的,我們就來指定com.learn.mapper,mapper下的類相當于都加上了Mapper注解,我來重新啟動,我們這個能不能使用呢,我們啟動的時候不會報錯,然后我們在這查詢http://localhost:8080/dept/2也能查出來{"id":2,"deptName":"實施部","principal":"張經(jīng)理","functional":"負責公司軟件維護工作"}
package com.learn.mapper;import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import com.learn.entities.Department;// 指定這是一個操作數(shù)據(jù)庫的mapper
//@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")public Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);@Options(useGeneratedKeys=true,keyProperty="id")@Insert("insert into department(deptName) values(#{deptName})")public int insertDept(Department department);@Update("update department set deptName=#{deptName} where id=#{id}")public int updateDept(Department department);}
package com.learn;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @SpringBootApplication 來標注一個主程序類,說明這是一個Sprint Boot應用* @author Leon.Sun**/
//@ImportResource(locations= {"classpath:beans.xml"})
@MapperScan(value="com.learn.mapper")
@SpringBootApplication
public class SpringBoot02ConfigApplication {public static void main(String[] args) {// Spring應用啟動起來SpringApplication.run(SpringBoot02ConfigApplication.class,args);}}
可以使用MapperScan批量掃描,所有的Mapper接口,這就是我們使用的注解版的mybatis,非常簡單,只需要寫一個mapper就行了,如果想自定義,寫一個Customer,如果想要批量掃描就用@MapperScan
?
總結
以上是生活随笔為你收集整理的SpringBoot_数据访问-整合MyBatis(二)-注解版MyBatis的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot_数据访问-整合My
- 下一篇: SpringBoot_数据访问-整合My