Spring Boot integrated MyBatis three ways! --turn

Source: Internet
Author: User

https://github.com/spring-projects/spring-boot/issues/5400

First, the use of Mybatis-spring-boot-starter
1. Add dependencies

Org.mybatis.spring.boot
Mybatis-spring-boot-starter
1.0.0

2. Import the specified SQL (application.properties) at startup
Spring.datasource.schema=import.sql
3. Annotation form
@springbootapplication
@mapperscan ("Sample.mybatis.mapper")
public class Samplemybatisapplication implements Commandlinerunner {

@Autowiredprivate CityMapper cityMapper;public static void main(String[] args) {    SpringApplication.run(SampleMybatisApplication.class, args);}@Overridepublic void run(String... args) throws Exception {    System.out.println(this.cityMapper.findByState("CA"));}

}
4. XML mode
Mybatis-config.xml

Application.properties

Spring.datasource.schema=import.sql
Mybatis.config=mybatis-config.xml
Mapper

@component
public class Citymapper {

@Autowiredprivate SqlSessionTemplate sqlSessionTemplate;public City selectCityById(long id) {    return this.sqlSessionTemplate.selectOne("selectCityById", id);}

}
Second, manual integration
1, annotation way
@configuration
@mapperscan ("Com.xixicat.modules.dao")
@propertysources ({@propertysource (value = "Classpath:application.properties", Ignoreresourcenotfound = True), @ Propertysource (value = "File:./application.properties", Ignoreresourcenotfound = True)})
public class Mybatisconfig {

@Value ("${name:}") private string name; @Value ("${database.driverclassname}") private string Driverclass; @Value ("${ Database.url} ") private string Jdbcurl; @Value (" ${database.username} ") private string DbUser; @Value (" ${ Database.password} ") private String dbpwd; @Value (" ${pool.minpoolsize} ") private int minpoolsize; @Value (" ${ Pool.maxpoolsize} ") private int maxpoolsize; @Beanpublic Filter characterencodingfilter () {Characterencodingfilter    Characterencodingfilter = new Characterencodingfilter ();    Characterencodingfilter.setencoding ("UTF-8");    Characterencodingfilter.setforceencoding (TRUE); return characterencodingfilter;}    @Bean (Destroymethod = "close") public DataSource DataSource () {hikariconfig hikariconfig = new Hikariconfig ();    Hikariconfig.setdriverclassname (Driverclass);    Hikariconfig.setjdbcurl (Jdbcurl);    Hikariconfig.setusername (DbUser);    Hikariconfig.setpassword (DBPWD);    Hikariconfig.setpoolname ("SPRINGHIKARICP");    Hikariconfig.setautocommit (FALSE); Hikariconfig.adDdatasourceproperty ("Cacheprepstmts", "true");    Hikariconfig.adddatasourceproperty ("Prepstmtcachesize", "250");    Hikariconfig.adddatasourceproperty ("Prepstmtcachesqllimit", "2048");    Hikariconfig.adddatasourceproperty ("Useserverprepstmts", "true");    Hikariconfig.setminimumidle (minpoolsize);    Hikariconfig.setmaximumpoolsize (maxpoolsize);    Hikariconfig.setconnectioninitsql ("SELECT 1");    Hikaridatasource DataSource = new Hikaridatasource (hikariconfig); return dataSource;} @Beanpublic Platformtransactionmanager TransactionManager () {return new Datasourcetransactionmanager (DataSource ());} @Beanpublic sqlsessionfactory sqlsessionfactory () throws Exception {Sqlsessionfactorybean sessionfactory = new sqlsess    Ionfactorybean ();    Sessionfactory.setdatasource (DataSource ());    Sessionfactory.setfailfast (TRUE);    Sessionfactory.setconfiglocation (New Classpathresource ("Mybatis-config.xml")); return Sessionfactory.getobject ();}

}
Comments

This approach is a bit awkward, and can not be configured for interception of transaction interception, only the use of annotations declaration, some redundant

2. XML mode
Data source

<context:property-placeholder ignore-unresolvable= "true"/><bean id= "Hikariconfig" class= " Com.zaxxer.hikari.HikariConfig "> <property name=" poolname "value=" SPRINGHIKARICP "/> <property name=" con Nectiontestquery "value=" Select 1 "/> <property name=" datasourceclassname "value=" ${ Database.datasourceclassname} "/> <property name=" maximumpoolsize "value=" ${pool.maxpoolsize} "/> <prope Rty name= "IdleTimeout" value= "${pool.idletimeout}"/> <property name= "datasourceproperties" > <props&            Gt            <prop key= "url" >${database.url}</prop> <prop key= "user" >${database.username}</prop> <prop key= "password" >${database.password}</prop> </props> &LT;/PROPERTY&GT;&LT;/BEAN&G t;<!--HIKARICP configuration--><bean id= "DataSource" class= "Com.zaxxer.hikari.HikariDataSource" destroy-method= "Close" > <constructor-arg ref= "hikariconfig"/&GT;&LT;/bean><bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "DataSource" ref= "DataSource"/> <!--configuration MyBatis configuration file Location--<property name= "configlocation" value= "Classpa Th:mybatis-config.xml "/> <property name=" typealiasespackage "value=" Com.xixicat.domain "/> <!--configuration Scan Mapp ER XML Location--<property name= "mapperlocations" value= "Classpath:com/xixicat/modules/dao/*.xml"/></bean ><!--Configure the package path to scan the Mapper interface--><bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > < Property Name= "Sqlsessionfactorybeanname" value= "sqlsessionfactory"/> <property name= "basePackage" value= " Com.xixicat.repository.mapper "/></bean><bean id=" sqlsessiontemplate "class=" Org.mybatis.spring.SqlSessionTemplate "> <constructor-arg ref=" sqlsessionfactory "/></bean><bean Id= "TransactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactiOnmanager "p:datasource-ref=" DataSource "/><aop:aspectj-autoproxy expose-proxy=" true "proxy-target-class=" True "/><tx:advice id=" Txadvice "transaction-manager=" TransactionManager "> <tx:attributes> <t        X:method name= "start*" propagation= "REQUIRED"/> <tx:method name= "submit*" propagation= "REQUIRED"/>        <tx:method name= "clear*" propagation= "REQUIRED"/> <tx:method name= "create*" propagation= "REQUIRED"/> <tx:method name= "activate*" propagation= "REQUIRED"/> <tx:method name= "save*" propagation= "REQUIRED"/&        Gt        <tx:method name= "insert*" propagation= "REQUIRED"/> <tx:method name= "add*" propagation= "REQUIRED"/> <tx:method name= "update*" propagation= "REQUIRED"/> <tx:method name= "delete*" propagation= "REQUIRED"/&gt        ;        <tx:method name= "remove*" propagation= "REQUIRED"/> <tx:method name= "execute*" propagation= "REQUIRED"/> < Tx:method name= "del*" propagation= "REQUIRED"/> <tx:method name= "*" read-only= "true"/> </tx:attribut Es></tx:advice><aop:config proxy-target-class= "true" expose-proxy= "true" > <aop:pointcut id= "PT" expression= "Execution (public * com.xixicat.service.*.* (..))"/> <aop:advisor order= "$" pointcut-ref= "PT" advice-ref= "Txadvice"/></aop:config>

AOP Dependency

    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-aop</artifactId>    </dependency>

Mybatis-spring and other dependencies

    <dependency> <groupId>org.mybatis</groupId> &LT;ARTIFACTID&GT;MYBATIS&LT;/ARTIFACTID&G        T <version>3.3.0</version> <scope>compile</scope> </dependency> <dependency&gt        ; <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> &LT;VERSION&G t;1.2.2</version> <scope>compile</scope> </dependency> <dependency> < Groupid>mysql</groupid> <artifactId>mysql-connector-java</artifactId> <version>5. 1.6</version> </dependency> <!--<dependency>--> <!--<groupid>org.hsqldb</ Groupid>--> <!--<artifactId>hsqldb</artifactId>--> <!--<scope>runtime</s      cope>--> <!--</dependency>--> <dependency> <groupId>com.zaxxer</groupId>  <artifactId>HikariCP-java6</artifactId> <version>2.3.8</version> </dependency> 

Specifying an XML configuration file

@configuration
@componentscan (basepackages = {"Com.xixicat"})
@importresource ("Classpath:applicationcontext-mybatis.xml")
@enableautoconfiguration
public class Appmain {

// 用于处理编码问题@Beanpublic Filter characterEncodingFilter() {    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();    characterEncodingFilter.setEncoding("UTF-8");    characterEncodingFilter.setForceEncoding(true);    return characterEncodingFilter;}//文件下载@Beanpublic HttpMessageConverters restFileDownloadSupport() {    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();    return new HttpMessageConverters(arrayHttpMessageConverter);}public static void main(String[] args) throws Exception {    SpringApplication.run(AppMain.class, args);}

}
Comments

Integration with traditional methods is the most straightforward, and transaction configuration is easier to get started

Spring Boot integrated mybatis three ways! --Go to

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.