本篇文章為大家展示了使用springboot如何實(shí)現(xiàn)對(duì)mybatis集成,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)基于分布式IDC數(shù)據(jù)中心構(gòu)建的平臺(tái)為眾多戶提供川西大數(shù)據(jù)中心 四川大帶寬租用 成都機(jī)柜租用 成都服務(wù)器租用。
在pom文件中添加mybatis的依賴:
org.mybatis.spring.boot mybatis-spring-boot-starter 1.2.0
添加MySQL驅(qū)動(dòng):
mysql mysql-connector-java
添加druid和fastjson依賴,使用阿里巴巴druid連接池
com.alibaba druid 1.0.28 com.alibaba fastjson 1.2.30
配置數(shù)據(jù)源,在application.yml中:
spring: datasource: name: test url: jdbc:mysql://127.0.0.1:3306/test username: root password: 111111 # 使用druid數(shù)據(jù)源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20
設(shè)置mybatis的mapper和model掃描路徑:
mybatis: mapperLocations: classpath:mapper/*.xml typeAliasesPackage: com.yingxinhuitong.demo.model #更多配置請(qǐng)參見(jiàn):http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
接下來(lái)我們新建userMapper.xml,UserEntity以及UserDao:
UserEntity.class
package com.yingxinhuitong.demo.model; /** * Created by jack on 2017/4/20. */ public class UserEntity { private Long id; private String username; private String password; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UserDao
package com.yingxinhuitong.demo.dao; import com.yingxinhuitong.demo.model.UserEntity; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * Created by jack on 2017/4/20. */ @Mapper public interface UserDao { ListsearchAll(); }
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
創(chuàng)建一個(gè)控制器,注入U(xiǎn)serDao,測(cè)試一下可不可以查詢數(shù)據(jù)了:
@RestController public class TestController { @Resource UserDao userDao; @RequestMapping("/getusers") public String test() { Listusers = userDao.searchAll(); String usersJson = JSON.toJSONString(users); return usersJson; } }
運(yùn)行Application.class,啟動(dòng)成功后訪問(wèn):http://localhost:9000/demo/getusers,輸出內(nèi)容如下:
至此,springboot已完成對(duì)mybatis的集成。
上述內(nèi)容就是使用springboot如何實(shí)現(xiàn)對(duì)mybatis集成,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。