在springboot中使用mybatis
-
建表
在test库中,建立一张animal表,并存入三条数据。
CREATE TABLEtest
.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 INTOtest
.animal
(id
,name
) VALUES (1, 'dog');
INSERT INTOtest
.animal
(id
,name
) VALUES (2, 'cat');
INSERT INTOtest
.animal
(id
,name
) VALUES (3, 'pig'); -
导入依赖
导入mybatis 和 mysql 依赖,因为springboot有指定mysql的版本,所以我就没写版本。
org.mybatis.spring.boot <artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
-
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 -
entity,mapper和service
AnimalMapper: (注解方式,当然也可以使用xml配置)
@Mapper
public interface AnimalMapper {
@Select("select * from animal")
ListselectAll(); @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 {
/* - 查找所有
*/
ListselectAll();
/**
- 按主键查找
*/
Animal selectByKey(Integer id);
/**
- 添加一个元素
*/
void insertOne(Animal animal);
}
AnimalImpl
@Service
public class AnimalImpl implements IAnimal {
@Resource
private AnimalMapper animalMapper;
@Override
public ListselectAll() {
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;
}
} - 因为是自增id,所有加上@Options注解
-
控制层
AnimalController
@RestController
public class AnimalController {
@Resource
private IAnimal iAnimal;@GetMapping("/getAll")
public ListgetAll() {
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);
}
} -
测试
● 查所有数据
● 条件查询
● 新增数据