springboot整合mybatis
环境:jdk1.8,idea,MySQL 8.0.16
1. 新建一个springboot项目
2. 添加pom依赖
添加相关依赖,就可以连接数据库了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
3. 在application.yml中配置数据源和mybatis
spring:
#数据源
datasource:
username: root
password: 123
url: jdbc:mysql://localhost:3306/ccc?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
# 就不用单独写一个mybatis-config.xml文件了,也可以单独写一个
mybatis:
# mapper-locations: classpath:mapping/*.xml,mapper接口的实现都在这
# 实体类的别名
type-aliases-package: com.example.demo.entity
# spring boot集成mybatis的方式打印sql
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
实体类和mapper接口
用了lombok
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
private int collection;
}
mapper接口
@Repository
public interface TeacherMapper {
@Select("SELECT * FROM teachers")
List<Teacher> selectAll();
@Select("select * from teachers where name=#{name}")
Teacher selectByName(String name);
@Select("select * from teachers where id=#{id}")
Teacher selectById(int id);
}
application启动类中添加@MapperScan注解,扫描mapper接口,或者在每个mapper接口上添加@Mapper
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4. 项目结构
5. service层调用接口
可以直接用@Autowired自动注入teacherMapper,也可用构造函数
@Service
public class TeacherServiceImpl implements TeacherService {
final TeacherMapper teacherMapper;
public TeacherServiceImpl(TeacherMapper teacherMapper) {
this.teacherMapper = teacherMapper;
}
@Override
public List<Teacher> selectAll() {
List<Teacher> list = teacherMapper.selectAll();
return list;
}
@Override
public Teacher selectByName(String name) {
return teacherMapper.selectByName(name);
}
@Override
public Teacher selectById(int id) {
return teacherMapper.selectById(id);
}
}