实现功能:查询出数据表中所有数据:
开发从底层往上层开发(先entity-mapper/dao-service-controller),调用,从上层往下层调用(controller-service-mapper/dao-entity)
注意:如果用mybatisplus代替mybatis,甚至连mapper.xml都不用写
准备数据:先是在数据库中新建一张表animal,里面有四个字段:id,name,age,email
在application.properties文件中(或者事application.yml)进行数据库信息的配置:
server:
port: 8089 #服务器端口
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #数据库驱动,固定的写法
#3306表示数据库的端口,mybatis_plus是数据库的名字
url: jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
mybatis:
mapper-locations:classpath: Mapper/*.xml
step1:新建有一个Entity包(或者事Dao包),将数据表映射成类
public class Animal
{
private int id;
private String name;
private int age;
private String email;
}
step2:创建Mapper包,在Mapper包里面创建AnimalMapper接口(注意这里也有人不取名为Mapper,而是取名为Dao包,然后在Dao包里面创建AnimalDao接口)
@Mapper
public interface AnimalMapper
{
public List find3();
}
同时在resources文件夹下新建一个Mapper包,在Mapper包下创建AnimalMapper.xml
将接口中的方法转化为sql语句:
<?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">
<!--命名空间是AnimalMapper接口的路径,选择这个接口中的哪个方法(通过id选择),返回类型是一个数据表映射的类的对象-->
<mapper namespace="com.example.springboot_test.Mapper.AnimalMapper">
<select id="find3" resultType="com.example.springboot_test.entity.Animal">
SELECT * FROM animal
</select>
</mapper>
step3:创建Service包,在Service包里面创建AnimalService类,在这个类本身的find2方法中调用AnimalMapper类的find3方法
@Autowired
private AnimalMapper animalMapper;
public List<Animal> find2()
{
return animalMapper.find3();
}
step4:创建Controller包,在Controller包里面创建AnimalController类,在这个类本身的find1方法中调用AnimalService类的find2方法
@Autowired
private AnimalService animalService;
@RequestMapping("/test")
public List<Animal> find1()
{
return animalService.find2();
}
最后启动服务器,在浏览器地址栏中输入:localhost:8080/test:
最后浏览器显示: