DAO pattern interface declaration

Report a typo

Suppose you have the User class:

class User {
    public String name;
    public int id;

    // constructor
    // getters and setters
    // toString
}

Use the DAO pattern and create the UserDao interface which implements the following methods:

  • add which gets User and returns void

  • get which gets int and returns User

  • update which gets User and returns void

  • delete which gets int and return void

Do not change the provided code of the classes. You only need to fix the lines marked by comments /* write your code here */.

Sample Input 1:

0
John
1
Jack
0
Jim

Sample Output 1:

User : id 0, name : John, added
User : id 0, name : John, found
User : id 1, name : Jack, added
User : id 1, name : Jack, found
User : id 10, not found
User : id 0, name : John, found
User : id 0, name : Jim, updated
User : id 0, name : Jim, found
User : id 0, name : Jim
User : id 1, name : Jack
User : id 0, name : Jim, deleted
Write a program in Java 17
interface UserDao {
// write your code here
}

/* Do not change code below */
class UserDaoImpl implements UserDao {
private final List<User> users;

public UserDaoImpl() {
users = new ArrayList<>();
}

@Override
public void add(User user) {
users.add(user);
System.out.println(user + ", added");
}

@Override
public User get(int id) {
User found = findById(id);
if (found == null) {
System.out.println("User : id " + id + ", not found");
return null;
}
System.out.println(found + ", found");
return new User(found.getId(), found.getName());

}

@Override
public void update(User user) {
User found = findById(user.getId());
if (found != null) {
found.setName(user.getName());
System.out.println(found + ", updated");
___

Create a free account to access the full topic