SpringBoot 集成 Mybatis(三)

1.增加持久化层

		<dependency>
			<groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.5</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>

2.Mapper相关

实体类

public class Emp {
	
	private Integer empId; private String empName; private Integer empAge;

数据库表

CREATE TABLE `table_emp` (
`emp_id`  int NOT NULL AUTO_INCREMENT ,
`emp_name`  varchar(100) NULL ,
`emp_age`  int NULL ,
PRIMARY KEY (`emp_id`)
)

Mapper配置文件

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springboot.mappers.EmpMapper">
	<select id="selectAll" resultType="com.atguigu.springboot.bean.Emp">
		select emp_id empId, emp_name empName, emp_age empAge
		from table_emp
	</select>
</mapper>

Mapper接口

public interface EmpMapper {
	
	List<Emp> selectAll(); }

Service接口

@Transactional
public interface EmpService { List<Emp> getAll(); }

Service 接口实现

@Service
public class EmpServiceImpl implements EmpService { @Autowired private EmpMapper empMapper; @Override public List<Emp> getAll() { return empMapper.selectAll(); } }

Handler调用

@Autowired
	private EmpService empService;
	
	@ResponseBody
	@RequestMapping("/getAll") public List<Emp> getAll() { return empService.getAll(); }

3.增加application.yml配置

spring:
  datasource:
    name: mydb
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/sb_db
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath*:/mybatis/*Mapper.xml

4.在主启动类上使用注解扫描Mapper

@MapperScan("com.webcode.springboot.mappers")

猜你喜欢

转载自www.cnblogs.com/wushaopei/p/11979349.html