如何通过jpa spring找出电子邮件是否已经存在并向前端发送一些错误消息

Gre*_*reg 5 java spring hibernate jpa spring-mvc

所以我有一个简单的 UsersDao

public interface UserDao extends JpaRepository<User, Long> {

}
Run Code Online (Sandbox Code Playgroud)

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

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

    }

}
Run Code Online (Sandbox Code Playgroud)

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

不清楚的东西还在后面。我在 jpa 上做了一个小教程,但他们使用:

实体管理器、实体交易

注意:使用 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
Run Code Online (Sandbox Code Playgroud)

或者我不需要在 springboot 中使用这些

很抱歉所有这些问题。我真的很想进入春天,但在这一点上还有点不清楚;)

小智 8

您可以执行以下操作:

假设User有一个属性email,在接口中定义一个方法是这样生成动态查询的:

public interface UserDao extends JpaRepository<User, Long> {
    public User findByEmail(String email);
}
Run Code Online (Sandbox Code Playgroud)

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

public class User {

    ....

    @Column(unique=true)
    String email;

}
Run Code Online (Sandbox Code Playgroud)


asm*_*dey 5

您有 2 个选择:

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