本篇內(nèi)容主要講解“springboot集成mybatis的實(shí)例代碼”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“springboot集成mybatis的實(shí)例代碼”吧!
創(chuàng)新互聯(lián)建站-專(zhuān)業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性?xún)r(jià)比武穴網(wǎng)站開(kāi)發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式武穴網(wǎng)站制作公司更省心,省錢(qián),快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋武穴地區(qū)。費(fèi)用合理售后完善,十年實(shí)體公司更值得信賴(lài)。
本節(jié)我們來(lái)詳細(xì)說(shuō)一下mybatis如何集成到springboot環(huán)境中
org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3 org.springframework.boot spring-boot-starter-jdbc 2.3.3.RELEASE MySQL mysql-connector-java runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine
server: port: 8010 spring: application: name: demo-mybatis # 配置mysql數(shù)據(jù)庫(kù) datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/lagou username: root password: root mybatis: # 指定需要加載的mapper xml文件 mapper-locations: classpath:mapping/*Mapper.xml # 指定別名所在的包 type-aliases-package: com.example.mybatis.pojo
@MapperScan
,指定需要掃描的mapper包文件路徑@SpringBootApplication @MapperScan(value = "com.example.mybatis.mapper") public class DemoMybatisApplication { public static void main(String[] args) { SpringApplication.run(DemoMybatisApplication.class, args); } }
@Data @ToString public class User { private Integer id; private String username; private String password; }
@Repository
注解,表示注入spring@Repository public interface IUserMapper { ListgetUserList(); User getUserById(Integer id); void addUser(User user); void updateUser(User user); void deleteUser(Integer id); }
insert into users values(#{id}, #{username}, #{password}) update users set username=#{username}, password= #{password} where id = #{id} delete from users where id = #{id}
IUserMapper
中定義的接口是否可以正常使用@ExtendWith(SpringExtension.class) @SpringBootTest class IUserMapperTest { @Autowired private IUserMapper userMapper; @Test public void getUserList() { ListuserList = userMapper.getUserList(); for (User user : userList) { System.out.println(user); } } @Test void addUser() { User user = new User(); user.setId(3); user.setUsername("lalala"); user.setPassword("1qaz2wx"); userMapper.addUser(user); } @Test public void getUserById() { User user = userMapper.getUserById(3); System.out.println(user); } @Test void updateUser() { User user = userMapper.getUserById(3); user.setUsername("wudi"); userMapper.updateUser(user); } @Test void deleteUser() { userMapper.deleteUser(3); } }
好了,到這里我的springboot 已經(jīng)成功的集成了mybatis,接下來(lái)我們就可以使用mybatis來(lái)處理我們的持久層業(yè)務(wù)了
到此,相信大家對(duì)“springboot集成mybatis的實(shí)例代碼”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!