1.如果是maven 构建的项目 先加入pom.xml配置文件
<!-- Spring Boot JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.在application.properties写入配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/ncdg
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3.新建user.java
import java.io.Serializable;
/**
*
* @author lili
*/
public class User implements Serializable{
private int id;
private String username;
private String position;
private String account;
private String userImg;
//这里省略了getter,setter
}
4.建一个UserService.java
import com.mycompany.springbootdemo.dao.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
/**
*
* @author lili
*/
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> getList() {
String sql = "SELECT id,username,position,account, userImg FROM ncdg_user";
return (List<User>) jdbcTemplate.query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User stu = new User();
stu.setId(rs.getInt("id"));
stu.setUsername(rs.getString("username"));
stu.setPosition(rs.getString("position"));
stu.setAccount(rs.getString("account"));
stu.setUserImg(rs.getString("userImg"));
return stu;
}
});
}
}
5.新建一个UserController.java
import com.mycompany.springbootdemo.dao.User;
import com.mycompany.springbootdemo.serverImpl.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author lili
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService UserService;
@RequestMapping("/list")
public List<User> getStus(){
return UserService.getList();
}
}
6.启动springBoot 访问 http://localhost:8080/user/list
就得到数据
[{"id":1,"username":"demo","position":"demo","account":"modede","userImg":null}]