1.若是是maven 構建的項目 先加入pom.xml配置文件java
<!-- 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寫入配置文件mysql
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.javaweb
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.javaspring
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.javasql
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/listjson
就獲得數據springboot
[{"id":1,"username":"demo","position":"demo","account":"modede","userImg":null}]