SpringBoot之SpringBoot整合Mybatis
SpringBoot之SpringBoot整合Mybatis
添加Mybatis的场景启动器
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
记得添加数据库的驱动,上一章整合JdbcTemplate的时候已经添加过了,忘记的可以看一下《SpringBoot之SpringBoot整合JdbcTemplate》
添加配置
spring: datasource: url: jdbc:mysql://192.168.0.23:3306/springboot?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.jdbc.Driver
和上一章的一样
编写代码
新增加一个mapper包,并创建UserMapper.java
UserMapper.java
package com.springboot.demo.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * @author ZYGisComputer */ @Mapper public interface UserMapper { @Insert("insert into users value(null,#{username},#{age});") int insertUser(@Param("username")String username,@Param("age")Integer age); }
为了方便,我直接就写注解了,没有写xml
编写服务
package com.springboot.demo.service; import com.springboot.demo.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author ZYGisComputer */ @RestController public class UserService { /** * 注入Spring JDBC 模板 */ @Autowired private JdbcTemplate jdbcTemplate; @Autowired private UserMapper userMapper; @GetMapping("/user") public String insertUser(String username, Integer age) { int update = jdbcTemplate.update("insert into users value(null,?,?);", username, age); return update > 0 ? "success" : "error"; } @GetMapping("/user2") public String insertUser2(String username, Integer age) { return userMapper.insertUser(username, age) > 0 ? "success" : "error"; } }
新增了一个User2接口,来调用Mapper
启动项目测试
测试成功
作者:彼岸舞
时间:2021\01\21
内容关于:SpringBoot
本文来源于网络,只做技术分享,一概不负任何责任