有了Mybatis独立项目的经验,Mybatis整合Springboot会变得非常容易。

SpringBoot整合Mybatis就更简单了,因为有一部分工作SpringBoot框架为我们完成了!
我们之前写单独项目的时候,是不是要写一个核心xml,就是这个xml让爷爷(SqlSessionFactoryBuilder)可以生出来爸爸(SqlSessionFactory),在SpringBoot中当然可以这样做,写一个xml,然后将这个xml告诉SpringBoot,不过想在我们有一个更简单的方式,通过springboot的配置文件和注解,我们告诉springboot mybatis的配置在哪里,这样就不用创建xml了
在springboot的application.yml中添加如下配置:
spring: datasource: url: jdbc:mysql://localhost:3306/blog username: root password: AaA19980818 driver-class-name: com.mysql.jdbc.Driver mybatis: typeAliasesPackage: com.example.demo.entity mapperLocations: classpath:mapper/*.xml server: port: 8081在springboot的启动类添加如下注解:
@SpringBootApplication @MapperScan("com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }yml文件中的mapperLocations告诉springboot所有的XXXMapper.xml文件在哪里,启动类的注解告诉SpringBoot所有的XXXDao接口在哪里,这样所有的接口和实现类都在Springboot的掌握之中。
接下来我们就不用生成爷爷(SqlSessionFactoryBuilder)、爸爸(SqlSessionFactory)和儿子(SqlSession)了,这些SpringBoot都为我们解决了。只需要写出User、UserDao和UserDao.xml就可以了
User.java
@Data public class User { private Long id; private String nickname; private String username; private String password; private String email; private String avatar; private Integer type; private Date create_time; private Date update_time; }最后我们编写一个controller验证一下吧!
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserDao userDao; @RequestMapping("/getUserById") public User getUserById(){ return userDao.getUserById((long)1); } }
