How to find out if an email already exist with jpa spring and sending some error messag to the front end
Asked Answered
E

4

9

So i have a simple UsersDao

public interface UserDao extends JpaRepository<User, Long> {

}

And inside my user controller i want to do something like this :

@RequestMapping(value = "/register",method = RequestMethod.POST)
public void addUser(@RequestBody User user) {

    //How do i check if user already exist with email instead of id
    // i managed to do this but can i search on something else than the id
    User user1 = userDao.findOne(1);

    if (user.getEmail().equals(user1.getEmail()))
    {

        // And how should i give one error to the front end if the email 
       //already exist I'm using angular js

    }
    else {

        userDao.save(user);

    }

}

I also have some extra questions on this topic:

Somethings that are not clear are following. I have done a small tutorial on jpa but there they use:

EntityManager, EntityTransaction

Note : when using EntityManagerFactory it goes as follow :

    EntityManagerFactory emf = null,

    //Then they use EntityManagerFactory

        emf = Persistence.createEntityManagerFactory("SomeValue")
    //where can i get "someValue" When using application .properties 

//because in the example they use xml but can't find the right properties in application.properties

Or do i not need to use these in springboot

Sorry for all these question. I really want to get into spring but somethings are still a bit unclear at this point ;)

Esse answered 26/9, 2015 at 19:16 Comment(0)
E
13

You can do the following:

Assuming User has an attribute email, define a method in the interface like this to generate a dynamic query:

public interface UserDao extends JpaRepository<User, Long> {
    public User findByEmail(String email);
}

Then you can find a user by email. If null is returned, no user with the given email exists. Also, within the User entity class, you can define an annotation to ensure that email is unique like this:

public class User {

    ....

    @Column(unique=true)
    String email;

}
Easley answered 26/9, 2015 at 19:37 Comment(3)
Hi i tried what you said but @column unique true is not working, I can still add multiple users with email. And for some reason if i do something like User user1 = userDao.findByEmail(user.getEmail()); if(user1.getEmail().equals(user.getEmail())) i get NullPointerException any ideas how to approach thisEsse
Ok i got it working But for some reason unique=true does not work and i have to catch this in the databaseEsse
For the NullPointerException, check if user1 is null before checking the email equality. The @Column annotation is a directive for generating the ddl. If you are not automatically generating the ddl then it would not work.Easley
F
6

You have 2 options:

  1. Use method User findByEmail(String email); in repository interface.
  2. Use method like @Query("SELECT COUNT(u.id) FROM User u WHERE u.email=:email) Long countUsersWithEmail(String email); Than it's obvious how to use rusults of these queries. I would use 2nd choice because of smaller overhead.
Fogle answered 26/9, 2015 at 19:36 Comment(2)
there's technically a race condition there. It's better to try to save the user by email and catch a unique key violationSublime
findUserByEmail will throw a NonUniqueResultException exception if that email already existMucin
R
2

this can actually be done in two different ways. although @ufuoma's solution is valid, spring has the exists and Optional which are more flexible. i will give code examples of each. in the repository interface, we will have these methods

boolean existsByEmail(String email);
Optional<User> findByEmail(String email);

then in your Service class we will have

    public Optional<User> findByEmail(String email){
       return baseUserRepository.findByEmail(email);
    }

    public boolean exist(String email){
       return baseUserRepository.existsByEmail(email);
    }

then in the controller class, we will have

if(baseUserSevice.exists==true){
    return "User already  exist";
}

or

Optional<baseUserEntity> user=baseUserService.findByEmail(user.getEmail);
if(user.isPresent()){
   return "user already exists";
}

the exist method is most preferred since it's faster

Radial answered 23/6, 2021 at 16:9 Comment(0)
H
1

you can use any combination with exists keyword

public interface UserDao extends JpaRepository<User, Long> {
    public boolean existsByEmail(String email);
}
Hospital answered 19/9, 2022 at 5:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.