Skip to content
Snippets Groups Projects
Commit ae2d1e04 authored by Yibo Zhu's avatar Yibo Zhu
Browse files

userDao.java develpoe

parent e4faecd2
No related branches found
No related tags found
3 merge requests!48Resolve issue 70,!47Revert "Merge branch '26-as-a-user-i-want-to-see-the-rankings-of-each-member' into 'main'",!33Resolve "As a user, I want to view and edit my personal information on my profile page so that I can manage and update my details"
package uk.ac.cf.spring.demo.sports.Userdetail;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository // 标注为 Spring 管理的 Bean
public class userDao {
private final JdbcTemplate jdbcTemplate;
// 构造函数注入 JdbcTemplate
public userDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// 获取所有用户
public List<User> getAllUsers() {
// 查询所有用户的 SQL 语句
String sql = "SELECT id, email, username FROM information";
// 执行查询并将结果映射到 User 对象
return jdbcTemplate.query(sql, (rs, rowNum) -> new User(
rs.getLong("id"), // 获取 id
rs.getString("email"), // 获取 email
rs.getString("username") // 获取 username
));
}
// 根据 ID 获取单个用户
public User getUserById(Long id) {
// 查询单个用户的 SQL 语句
String sql = "SELECT id, email, username FROM information WHERE id = ?";
// 执行查询并返回唯一的 User 对象
return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> new User(
rs.getLong("id"), // 获取 id
rs.getString("email"), // 获取 email
rs.getString("username") // 获取 username
));
}
// 添加一个新用户
public int addUser(User user) {
// 插入用户的 SQL 语句
String sql = "INSERT INTO information (email, username) VALUES (?, ?)";
// 执行插入操作并返回受影响的行数
return jdbcTemplate.update(sql, user.getEmail(), user.getUsername());
}
// 更新用户信息
public int updateUser(User user) {
// 更新用户的 SQL 语句
String sql = "UPDATE information SET email = ?, username = ? WHERE id = ?";
// 执行更新操作并返回受影响的行数
return jdbcTemplate.update(sql, user.getEmail(), user.getUsername(), user.getId());
}
// 删除用户
public int deleteUser(Long id) {
// 删除用户的 SQL 语句
String sql = "DELETE FROM information WHERE id = ?";
// 执行删除操作并返回受影响的行数
return jdbcTemplate.update(sql, id);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment