java - 如何使用 jpa spring 查明电子邮件是否已经存在并向前端发送一些错误消息

标签 java spring hibernate spring-mvc jpa

所以我有一个简单的UsersDao

public interface UserDao extends JpaRepository<User, Long> {

}

在我的用户 Controller 中,我想做这样的事情:
@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 上做了一个小教程,但他们在那里使用:

实体管理器,
实体交易

注意:使用 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中使用这些

对不起所有这些问题。我真的很想进入 Spring ,但目前还有些不清楚;)

最佳答案

您可以执行以下操作:

假设 User有一个属性 email ,在接口(interface)中定义一个方法来生成动态查询:

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

然后您可以通过电子邮件找到用户。如果 null返回时,不存在具有给定电子邮件的用户。此外,在 User 内实体类,可以定义一个注解来保证email像这样独一无二:
public class User {

    ....

    @Column(unique=true)
    String email;

}

关于java - 如何使用 jpa spring 查明电子邮件是否已经存在并向前端发送一些错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801008/

相关文章:

Spring Security 执行顺序

java - @RequestMapping 在 Spring 版本 1.5.2.RELEASE 中不起作用

hibernate - 为什么 JPA CriteriaQuery 不提供更新查询?

java - 将 foursquare http 响应转换为 JSON for java

java - 同步访问 int 数组中的特定索引

java - "java.security.cert.CertificateException: No name matching localhost found"无法在 Ubuntu 16.04 LTS 上解析

java - 覆盖同一工具的多个方法

java - 使用 java 8 和服务注入(inject)的策略模式

java - NonUniqueObjectException 和 IdentifierGenerationException - 无法更新表

java - 如何调试结合 hsqldb 处理 hibernate.hbm2ddl.import_files 值?