所以我有一个简单的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/