springboot访问数据库以json形式输出
pojo中Test
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Test {
private Integer id;
private String name;
private Boolean gender;
private Integer age;
private Date birth;
}
TestMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gsj.mapper.TestMapper">
<select id="queryTest" resultType="com.gsj.pojo.Test">
select * from test
</select>
<select id="queryTestByID" resultType="com.gsj.pojo.Test">
select * from test where id=#{testID}
</select>
</mapper>
Test.mapper
public interface TestMapper {
Test queryTestByID(@Param("testID") Integer testID);
List<Test> queryTest();
}
application.yml配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/springboot02?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
server:
port: 8080
servlet:
context-path: /
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
xxxxApplication添加
@MapperScan(basePackages = "com.gsj.mapper")
TestService
public interface TestService {
Test queryTestByID(@Param("testID") Integer testID);
List<Test> queryTest();
}
TestServiceImpl
@Service
public class TestServiceImpl implements TestService {
private TestMapper testMapper;
@Autowired(required=false)
public void setTestMapper(TestMapper testMapper) {
this.testMapper = testMapper;
}
@Override
public Test queryTestByID(Integer testID) {
return testMapper.queryTestByID(testID);
}
@Override
public List<Test> queryTest() {
return testMapper.queryTest();
}
}
TestController
@RestController
public class TestController {
@Autowired
private TestService testService;
// @ResponseBody
@RequestMapping("/queryTest")
private List<Test> queryTest(){
List<Test> testList = testService.queryTest();
return testList;
}
依赖有
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>