Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ;)

like image 966
Greg Avatar asked Sep 26 '15 19:09

Greg


2 Answers

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;

}
like image 90
ufuoma Avatar answered Oct 13 '22 11:10

ufuoma


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.
like image 32
asm0dey Avatar answered Oct 13 '22 12:10

asm0dey