在上面给出的代码能够添加能够使用JDBC模块JDBCTemplate访问数据库完成添加、修改、删除、查询用户功能的完整代码
时间: 2024-11-04 11:15:15 浏览: 20
在上述代码中,已经包含了基本的数据库操作功能。然而,为了提供一个完整的例子,我将展示如何在`MyUser`类中添加一些字段,以及如何使用这些方法来实现添加、修改、删除和查询用户的具体操作。假设`MyUser`类如下:
```java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class MyUser {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private String email;
// getters and setters...
}
```
现在我们可以在业务逻辑层中使用`TestDaoImpl`:
```java
@Service
public class UserService {
@Autowired
private TestDao testDao;
public void addUser(MyUser user) {
int rowsAffected = testDao.update("INSERT INTO users (name, email) VALUES (?, ?)", user.getName(), user.getEmail());
if (rowsAffected > 0) {
System.out.println("User added successfully");
}
}
public void updateUser(MyUser newUser, Long userId) {
String updateUserSql = "UPDATE users SET name=?, email=? WHERE id=?";
int rowsAffected = testDao.update(updateUserSql, newUser.getName(), newUser.getEmail(), userId);
if (rowsAffected > 0) {
System.out.println("User updated successfully");
}
}
public List<MyUser> getUsers(int page, int pageSize) {
String getUsersSql = "SELECT * FROM users LIMIT ?, ?";
return testDao.query(getUsersSql, page, pageSize);
}
// 可能还需要一个方法来删除用户,例如:
public void deleteUser(Long userId) {
String deleteUserSql = "DELETE FROM users WHERE id=?";
int rowsAffected = testDao.update(deleteUserSql, userId);
if (rowsAffected > 0) {
System.out.println("User deleted successfully");
}
}
}
```
阅读全文