So i have a simple UsersDao
public interface UserDao extends JpaRepository<User, Long> {
}
And inside my user controller i want to do something like this :
@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);
}
}
I also have some extra questions on this topic:
Somethings that are not clear are following. I have done a small tutorial on jpa but there they use:
EntityManager, EntityTransaction
Note : when using EntityManagerFactory it goes as follow :
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
Or do i not need to use these in springboot
Sorry for all these question. I really want to get into spring but somethings are still a bit unclear at this point ;)
You can do the following:
Assuming User
has an attribute email
, define a method in the interface like this to generate a dynamic query:
public interface UserDao extends JpaRepository<User, Long> {
public User findByEmail(String email);
}
Then you can find a user by email. If null
is returned, no user with the given email exists. Also, within the User
entity class, you can define an annotation to ensure that email
is unique like this:
public class User {
....
@Column(unique=true)
String email;
}
You have 2 options:
User findByEmail(String email);
in repository interface.@Query("SELECT COUNT(u.id) FROM User u WHERE u.email=:email) Long
countUsersWithEmail(String email);
Than it's obvious how to use rusults of these queries. I would use 2nd choice because of smaller overhead.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With