java如何通过jpa spring发现电子邮件是否已经存在,并向前端发送一些错误消息
所以我有一个简单的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的小教程,但他们使用了:
实体管理器, 实体事务
注意:使用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中使用这些
很抱歉问了这么多问题。我真的很想进入春天,但现在有些事情还不太清楚;)
# 1 楼答案
您有两种选择:
User findByEmail(String email);
李>@Query("SELECT COUNT(u.id) FROM User u WHERE u.email=:email) Long countUsersWithEmail(String email);
很明显,如何使用这些查询的结果。我会使用第二选择,因为开销较小李># 2 楼答案
您可以执行以下操作:
假设
User
有一个属性email
,在接口中定义如下方法以生成动态查询:然后你可以通过电子邮件找到一个用户。如果返回
null
,则不存在具有给定电子邮件的用户。另外,在User
实体类中,您可以定义注释以确保email
是唯一的,如下所示:# 3 楼答案
这实际上可以通过两种不同的方式来实现。尽管@ufuoma的解决方案是有效的,但是spring具有更灵活的exists和Optional。我将给出每种方法的代码示例。 在存储库界面中,我们将使用以下方法
那么在你的服务课上我们会有
然后在控制器类中,我们将
或
exist方法最受欢迎,因为它速度更快