springboot学习之四(整合mybatis)
springboot整合mybatis
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.29</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
数据库及mybatis的配置
server.port=8080 #mysql配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=89757 #mybaits配置 #mybatis的为实体其别名 mybatis.type-aliases-package=com.cc8w.entity #映射文件路径 mybatis.mapper-locations=classpath:mappers/*.xml #日志控制台输出 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
数据库 (略)
实体类 (略)
1.mapper文件开发 (需配置mapper映射文件路径)
controller:
@Autowired private TeacherService teacherService; @RequestMapping("/teacher") public String teacher(){ List<TeacherEntity> teachers = teacherService.getTeacherAll(); System.out.println(teachers); return teachers.toString(); }
service:
@Service public class TeacherService { @Autowired public TeacherMapper teacherMapper; public List<TeacherEntity> getTeacherAll(){ List<TeacherEntity> teacherList = teacherMapper.queryOneTeacher(1); return teacherList; } }
dao:
@Mapper @Repository public interface TeacherMapper { public List<TeacherEntity> queryOneTeacher(int id); }
mapper文件(放在source下):
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cc8w.dao.TeacherMapper"> <select id="queryOneTeacher" resultType="com.cc8w.entity.TeacherEntity"> select * from teacher where id = #{id} </select> </mapper>
2.纯注解开发 (不用再配置文件配置任何参数)
纯注解开发,其实和注解的 controller,service ,都一致,不同的是 没有了接口和mapper.xml文件的对应(去掉了mapper.xml文件),直接在接口中写sql语句.
dao:
@Mapper @Repository public interface TeacherAnnoMapper { @Select("select * from teacher where 1") public List<TeacherEntity> queryTeachers(); }
https://www.cnblogs.com/fps2tao/p/13821490.html