一、编程步骤
1、引入依赖
springboot相关依赖(略)、mybatis-spring-boot-starter、mysql、druid、lombook
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
2、整合mybatis
1)建表
2)实体类:使用lombook
@Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor public class User { private Integer id; private String name; private Integer age; private String email; }
3)DAO接口:接口抽象:BaseDao
//BaseDao public interface BaseDao<T> { List<T> getAll(); void insert(T t); } //UserDao @Repository public interface UserDao extends BaseDao<User> { }
4)Mapper配置文件
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.icucoder.learn.dao.UserDao"> <select id="getAll" resultType="user"> select id, name, age, email from user; </select> <insert id="insert" parameterType="user"> insert into user values (#{id}, #{name}, #{age}, #{email}); </insert> </mapper>
5)Service接口
public interface UserService { List<User> getAll(); void insert(User t); }
6)Service接口实现类
@Service @Transactional public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Override public List<User> getAll() { return userDao.getAll(); } @Override public void insert(User user) { System.out.println("insert success"); userDao.insert(user); int i =1/0; } }
7)配置相关属性
(1)配置dao扫描位置
在入口类上加上注解:@MapperScan("com.icucoder.learn.dao")//指定dao接口扫描位置
@SpringBootApplication @MapperScan("com.icucoder.learn.dao")//指定dao接口扫描位置 public class LearnApplication { public static void main(String[] args) { SpringApplication.run(LearnApplication.class, args); } }
(2)在application.properties中配置数据源和Mapper文件位置
#数据源 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot?characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=xroot #Mapper文件位置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.icucoder.learn.entity
8)编写Controller测试
@RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @RequestMapping("/all") public List<User> all() { return userService.getAll(); } @RequestMapping("/insert") public String insertOne() { User user = new User(7, "mayun", 29, "admin@qq.com"); userService.insert(user); return "insert success"; } }
9)服务器附属并访问测试
http://127.0.0.1:8080/user/all