1.勾选mybatis技术,勾选数据库驱动。
2.数据连接信息转换为配置信息
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/boot_zhaopin?serverTimezone=UTC username: root password: root
3.编写数据库映射
public interface UserDao {
@Select("select * from user where id = #{id}")
public User getById(Integer id);
}
4.将dao接口类注入到Spring,能够让其他类进行引用;
@Mapper
public interface UserDao {
@Select("select * from user where id = #{id}")
public User getById(Integer id);
}
//@Mapper的作用:扫描项目中的Dao层,将dao接口类注入到Spring,能够让其他类进行引用;
//
//@Mapper:在dao接口类中,添加此注解;麻烦的在于,每个dao接口类都必须添加此注解;
//@MapperScan:可以指定要扫描的dao接口类的路径,可以在启动类中添加此注解,可替代@Mapper注解(此模块内dao接口类不用都添加@Mapper注解)
5.测试是否可以使用
@SpringBootTest class DemoMybatisApplicationTests { @Autowired private UserDao userDao; @Test void contextLoads() { System.out.println(userDao.getById(1)); }