1

控制器代码:

@GetMapping("/show/{id}")
public ResponseEntity<Student> findId(@PathVariable Student student) throws Exception {
    Student showId = studentService.findId(student);
    return new ResponseEntity<Student>(showId, HttpStatus.OK);
}

需要为路径返回一个对象id

存储库代码:

      public Student findId(Student student) throws Exception {
        Connection connect = null;
        Statement st = null;
        ResultSet rec = null;
        PreparedStatement pre = null;
        List<Student> userlist = new ArrayList<Student>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +"?user=root&password=root&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
            connect.setAutoCommit(false);

            st = connect.createStatement();

            String sql = "SELECT * FROM student WHERE studentid = ? ";

            pre = connect.prepareStatement(sql);
            pre.setLong(1, student.getId());
            pre.executeQuery();

        } catch (Exception e) {
            if (connect != null) {
                try {
                    st.close();
                    connect.rollback();
                } catch(SQLException e2) {
                    e2.printStackTrace();
                }
            }
        } finally {
            if (st != null) {
                try {
                    st.close();
                    connect.setAutoCommit(true);
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            connect.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return student;
    }
4

1 回答 1

0
ResultSet result = pre.executeQuery();

while (result.next()) {
   long id = resultSet.getLong("studentId");
   String name = resultSet.getString("name");
   // another fields
   return new Student(id, name);
}

对于控制器,如果只需要 id (@PathVariable Long id) 更轻。

Student response = studentService.findById(id);
return ResponseEntity.ok(response);
于 2019-12-20T09:55:17.150 回答