Home > front end >  How to check if one user have already column with same value
How to check if one user have already column with same value

Time:12-14

I have a two tables: User and Wallet

User have: id Wallet have: userId, walletName

Now, I want to avoid that so user cant have two wallets with same name.

I create something but it applies to all users, so if user with id 1 create a wallet with name walletSaving no-one can create wallet with that name, while I want to avoid that, I want to create something to check whether the user with id 1 have already wallet with that name.

So far I have this:

if (walletRepository.existsByWalletName(walletRequest.getWalletName())) {
        return ResponseEntity.badRequest().body(new MessageResponse("You already have wallet with that name, choose another!"));
    }

After some help I tried with something like this:

  @PostMapping("/user/{user_id}/wallets")
public ResponseEntity<?> createWallet(@PathVariable(value = "user_id") Long user_id,
                                      @RequestBody Wallet walletRequest, User user) {


    if (walletRepository.existsByUserIdAndWalletName(user.getId(), walletRequest.getWalletName())) {
        return ResponseEntity.badRequest()
                .body(new MessageResponse("You already have wallet with that name, choose another!"));
    }

Its still creating wallets with same name.

Just to provide more info.

User entity

    @Entity
    @Table(name = "users",
       uniqueConstraints = {
           @UniqueConstraint(columnNames = "username"),
           @UniqueConstraint(columnNames = "email")
       })
public class User {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotEmpty
  @Size(min = 3, max = 20)
  private String username;

  @NotEmpty
  @Size(max = 50)
  @Email
  private String email;

  @NotEmpty
  @Size(min = 6)
  private String password;

  @NotEmpty(message = "Please, insert a first name")
  private String firstName;

  @NotEmpty(message = "Please, insert a last name")
  private String lastName;

  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "user_roles", 
             joinColumns = @JoinColumn(name = "user_id"),
             inverseJoinColumns = @JoinColumn(name = "role_id"))
  private Set<Role> roles = new HashSet<>();

  public User() {
  }

  public User(String username, String email, String password, String firstName, String lastName) {
    this.username = username;
    this.email = email;
    this.password = password;
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public Set<Role> getRoles() {
    return roles;
  }

  public void setRoles(Set<Role> roles) {
    this.roles = roles;
  }
}

Wallet entity

    @Entity
    @Table(name = "wallet")
    public class Wallet {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty(message = "Please, insert a wallet name")
    private String walletName;

    private double initialBalance;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "user_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private User user;

    public Wallet() {
    }

    public Wallet(String walletName, double initialBalance) {
        this.walletName = walletName;
        this.initialBalance = initialBalance;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getWalletName() {
        return walletName;
    }

    public void setWalletName(String walletName) {
        this.walletName = walletName;
    }

    public double getInitialBalance() {
        return initialBalance;
    }

    public void setInitialBalance(double initialBalance) {
        this.initialBalance = initialBalance;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Wallet Repository

boolean existsByUserIdAndWalletName(Long userId, String walletName);

CodePudding user response:

You need to include the userId in your query:

final long userId = getUserId(); // get the currently authenticated user's id
if (walletRepository.existsByUserIdAndWalletName(userId, walletRequest.getWalletName())) {
    return ResponseEntity.badRequest()
        .body(new MessageResponse("You already have wallet with that name, choose another!"));
}

CodePudding user response:

existsByUserIdAndWalletName(userId, walletName);

or

findByUserIdAndWalletName(userId, walletName);

If id of the user and walletName is provided, it will check only for that user if it has that wallet name or not, and if in that situation returns something (true or result>0), that will mean that for that specific user the wallet name is already taken.

https://www.baeldung.com/spring-data-derived-queries#multiple-condition-expressions

  • Related