以下是在 Java Spring Boot 框架中创建一个访问数据库的接口代码的示例:
在您的项目中添加数据库连接依赖(以 MySQL 为例):
xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
创建一个包含必要方法的数据访问对象(DAO):
@Repository
public class UserDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> getAllUsers() {
String sql = "SELECT * FROM users";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
return jdbcTemplate.query(sql, rowMapper);
}
public int addUser(User user) {
String sql = "INSERT INTO users (name, age, email) VALUES (?, ?, ?)";
return jdbcTemplate.update(sql, user.getName(), user.getAge(), user.getEmail());
}
public int updateUser(User user) {
String sql = "UPDATE users SET name=?, age=?, email=? WHERE id=?";
return jdbcTemplate.update(sql, user.getName(), user.getAge(), user.getEmail(), user.getId());
}
public int deleteUser(int userId) {
String sql = "DELETE FROM users WHERE id=?";
return jdbcTemplate.update(sql, userId);
}
}
在您的控制器类中注入 DAO 并将其用于处理请求:
java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserDAO userDAO;
@GetMapping("")
public List<User> getAllUsers() {
return userDAO.getAllUsers();
}
@PostMapping("")
public ResponseEntity<?> addUser(@RequestBody User user) {
int result = userDAO.addUser(user);
if (result == 1) {
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
@PutMapping("/{id}")
public ResponseEntity<?> updateUser(@PathVariable int id, @RequestBody User user) {
user.setId(id);
int result = userDAO.updateUser(user);
if (result == 1) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable int id) {
int result = userDAO.deleteUser(id);
if (result == 1) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
上述代码创建了一个 RESTful 风格的 UserController 控制器,其中包含访问数据库的 GET、POST、PUT 和 DELETE 方法。请注意,我们在控制器中使用 @Autowired 注解来注入 DAO 对象,并将其用于处理请求。