如何找出jpa spring已存在的电子邮件,并向前端发送一些错误消息

时间:2015-09-26 19:16:27

标签: java spring hibernate spring-mvc jpa

所以我有一个简单的UsersDao

public interface UserDao extends JpaRepository<User, Long> {

}

在我的用户控制器中,我想做这样的事情:

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

    }

}

我还有一些关于这个主题的额外问题:

不清楚的事情如下。我已经完成了一个关于jpa的小教程,但他们使用了:

的EntityManager, EntityTransaction

注意:使用EntityManagerFactory时,如下所示:

    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

或者我不需要在springboot中使用它们

对不起这些问题。我真的很想进入春天,但有些事情在这一点上仍然有点不清楚;)

3 个答案:

答案 0 :(得分:4)

您有两个选择:

  1. 在存储库界面中使用方法User findByEmail(String email);
  2. 使用方法如 @Query("SELECT COUNT(u.id) FROM User u WHERE u.email=:email) Long countUsersWithEmail(String email); 显而易见,如何使用这些查询的结果。我会使用第二选择,因为开销较小。

答案 1 :(得分:3)

您可以执行以下操作:

假设User有一个属性email,请在界面中定义一个方法,以生成动态查询:

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

然后您可以通过电子邮件找到用户。如果返回null,则不存在具有给定电子邮件的用户。此外,在User实体类中,您可以定义注释以确保email是唯一的,如下所示:

public class User {

    ....

    @Column(unique=true)
    String email;

}

答案 2 :(得分:0)

这实际上可以通过两种不同的方式来完成。尽管@ufuoma 的解决方案是有效的,但 spring 具有更灵活的 exists 和 Optional。我将给出每个的代码示例。 在存储库接口中,我们会有这些方法

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

然后在您的服务类中我们将有

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

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

然后在控制器类中,我们将有

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

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

exist 方法是首选,因为它更快