springboot[4]_配置mybatis
在springboot中使用mybatis
1. 建表
在test库中,建立一张animal表,并存入三条数据。
CREATE TABLE `test`.`animal` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
INSERT INTO `test`.`animal`(`id`, `name`) VALUES (1, 'dog');
INSERT INTO `test`.`animal`(`id`, `name`) VALUES (2, 'cat');
INSERT INTO `test`.`animal`(`id`, `name`) VALUES (3, 'pig');
2. 导入依赖
导入mybatis 和 mysql 依赖,因为springboot有指定mysql的版本,所以我就没写版本。
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3. yml配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8
username: root
password: 1234
driver-class-name: com.mysql.cj.jdbc.Driver
4. entity,mapper和service
AnimalMapper: (注解方式,当然也可以使用xml配置)
@Mapper
public interface AnimalMapper {
@Select("select * from animal")
List<Animal> selectAll();
@Select("select * from animal where id = #{id}")
Animal selectByKey(Integer id);
/**
* 因为是自增id,所有加上@Options注解
*/
@Insert("insert into animal(`id`,`name`) values (#{id}, #{name}) ")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertOne(Animal animal);
}
IAnimal:
public interface IAnimal {
/**
* 查找所有
*/
List<Animal> selectAll();
/**
* 按主键查找
*/
Animal selectByKey(Integer id);
/**
* 添加一个元素
*/
void insertOne(Animal animal);
}
AnimalImpl
@Service
public class AnimalImpl implements IAnimal {
@Resource
private AnimalMapper animalMapper;
@Override
public List<Animal> selectAll() {
return animalMapper.selectAll();
}
@Override
public Animal selectByKey(Integer id) {
return animalMapper.selectByKey(id);
}
@Override
public void insertOne(Animal animal) {
animalMapper.insertOne(animal);
}
}
Animal:
public class Animal {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5. 控制层
AnimalController
@RestController
public class AnimalController {
@Resource
private IAnimal iAnimal;
@GetMapping("/getAll")
public List<Animal> getAll() {
return iAnimal.selectAll();
}
@GetMapping("/getOne")
public Animal getOne(@RequestParam("id") Integer id) {
return iAnimal.selectByKey(id);
}
@PostMapping("/insertOne")
public void insertOne(@RequestBody Animal animal) {
iAnimal.insertOne(animal);
}
}
6. 测试
- 查所有数据
- 条件查询
- 新增数据