添加相关依赖信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
在application.properties中配置数据源信息
spring.datasource.url=jdbc:mysql://localhost:3306/db?characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
编写数据库操作业务接口
public interface UserService {
// 获取全部用户数据
public List<User> getUserList();
}
编写数据库操作业务实现类
@Service
public class UserServiceImpl implements UserService {
// SpringBoot提供的数据库操作类
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<User> getUserList() {
return jdbcTemplate.query("select * from tab_user", new BeanPropertyRowMapper(User.class));
}
}
编写Controller
@RestController
@RequestMapping("/users")
public class UserControllerDb {
@Autowired
private UserService userService;
/**
* 获取全部用户信息
*
* @return
*/
@GetMapping("/")
public List<User> getUserList() {
return userService.getUserList();
}
}