I have User class like this :
#Data
#Entity
public class User {
#Id #GeneratedValue Long userID;
String eMail;
String passwordHash;
}
And I have data like this :
[{"userID":1,"passwordHash":"asdasd","email":"admin#admin.com"},
{"userID":2,"passwordHash":"12345","email":"admin1asdasd#admin.com"}]
I have two method in my controller class, one - to get single user :
#GetMapping("/user/{id}")
User one(#PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
Other method to retrieve all user :
#GetMapping("/user")
List<User> all() {
return repository.findAll();
}
In my browser, going to this address - http://localhost:8080/user , I can see these data. And if I goto http://localhost:8080/user/id I can get a specific value.
Now my question is how can access data like http://localhost:8080/user/email/passwordHash? I am quite sure that it is not possible, because I haven't stored data in that way.
As my main target is to verify login, I have already written a #Query in my repository interface. Here it is :
public interface UserRepository extends JpaRepository<User, Long> {
#Query("select u from User u where u.eMail = ?1 and u.passwordHash = ?2")
List<User> listByLoginCredential(String emailAddress,String passwordHash);
}
Can Anyone tell me how can I do this,use this method of this interface?
I think you can can achieve what you want by adding the following method to the controller class:
#GetMapping("/user/{emailAddress}/{passwordHash}")
List<User> byMailAndPassword(#PathVariable String emailAddress, #PathVariable String passwordHash) {
return repository.listByLoginCredential(emailAddress, passwordHash)
}
On the other hand you say that your main goal is to verify login, so it looks like you are doing authentication. If you have time you should look into doing it with spring security https://spring.io/guides/gs/securing-web/#initial
Maybe this help https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.
Or you can also create procedure in Database and call stored procedure with Spring boot.
Login is related to security so ideally you should create a separate post method and use the repository method. Always make sure to follow the best practice.
Spring security is something you can utilize for better authentication and authorization.
So I have looked at various tutorials about JPA with Spring Data and this has been done different on many occasions and I am no quite sure what the correct approach is.
Assume there is the follwing entity:
package stackoverflowTest.dao;
import javax.persistence.*;
#Entity
#Table(name = "customers")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
public Customer(String name) {
this.name = name;
}
public Customer() {
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
We also have a DTO which is retrieved in the service layer and then handed to the controller/client side.
package stackoverflowTest.dto;
public class CustomerDto {
private long id;
private String name;
public CustomerDto(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.
Now I have to save this updated DTO to the database.
Unluckily currently there is no way to update an existing customer (except than deleting the entry in the DB and creating a new Cusomter with a new auto-generated id)
However as this is not feasible (especially considering such an entity could have hundreds of relations potentially) - so there come 2 straight forward solutions to my mind:
make a setter for the id in the Customer class - and thus allow setting of the id and then save the Customer object via the corresponding repository.
or
add the id field to the constructor and whenever you want to update a customer you always create a new object with the old id, but the new values for the other fields (in this case only the name)
So my question is wether there is a general rule how to do this?
Any maybe what the drawbacks of the 2 methods I explained are?
Even better then #Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)
Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);
Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in #Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.
In Spring Data you simply define an update query if you have the ID
#Repository
public interface CustomerRepository extends JpaRepository<Customer , Long> {
#Query("update Customer c set c.name = :name WHERE c.id = :customerId")
void setCustomerName(#Param("customerId") Long id, #Param("name") String name);
}
Some solutions claim to use Spring data and do JPA oldschool (even in a manner with lost updates) instead.
Simple JPA update..
Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);
This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.
If you need to work with DTOs rather than entities directly then you should retrieve the existing Customer instance and map the updated fields from the DTO to that.
Customer entity = //load from DB
//map fields from DTO to entity
So now assume the Customer wants to change his name in the webui -
then there will be some controller action, where there will be the
updated DTO with the old ID and the new name.
Normally, you have the following workflow:
User requests his data from server and obtains them in UI;
User corrects his data and sends it back to server with already present ID;
On server you obtain DTO with updated data by user, find it in DB by ID (otherwise throw exception) and transform DTO -> Entity with all given data, foreign keys, etc...
Then you just merge it, or if using Spring Data invoke save(), which in turn will merge it (see this thread);
P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary #DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.
P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's #Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.
I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.
Use RepositoryExtendJPA.save(entity). Example:
List<Person> person = this.PersonRepository.findById(0)
person.setName("Neo");
This.PersonReository.save(person);
this block code updated new name for record which has id = 0;
Use #Transactional from javax or spring framework. Let put #Transactional upon your class or specified function, both are ok. I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.
There is a method in JpaRepository
getOne
It is deprecated at the moment in favor of
getById
So correct approach would be
Customer customerToUpdate = customerRepository.getById(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);
I have a problem and I don't know how to solve it without making new column in DB. So I have a registration form with fields username, password, password2 (for verifying if both are matching) and other now not important fields. Also I have mapped class User with hibernate to my sql table and this method in controller which verifies the user input:
public ModelAndView addUser(#ModelAttribute("user") User user) {
if(userService.correctInput(user))
userService.addUser(user);
else ...
}
Let me show you my problem:
if i want to verify input there must be password2 field in the form, otherwise i can't acces to that value after submiting the form. But then i need to have an attribute password2 in my mapped class User, but not mapped to my table, only simple attribute, that's working fine, but the problem is that i cant save user to my database if i have non-mapped attribute password2. Something like this:
...
#Column(name = "password")
#Basic
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
...
if I want to save this, it throws an exceptions. I have 2 possible (but not smart) solutions for this: Althought first is smart, but I don't want to do it and it's already mentioned another column for password2 in my database, the second is another class (non-mapped) user with one more attribute for password2 and transforming from one to other - but that's wrong and very complicated practise. Do you have a good solution for this? without making new column in database?
Use the #Transient annotation to tell Hibernate that the password2 property shouldn't be persisted.
I'm using seam 2.1.2 security and I create a role using identitymanager by jsf richfaces GUI. in creation process I would add a "description" to role created in database , the creation of role is ok but the description field is not added, I must update the role (in other operation by GUI) to see the description field stored in database. the question is what have I to do to store the "description" filed in creation operation?
bellow is my code:
public boolean createRole(Role role) {
IdentityManager identityManager = IdentityManager.instance();
logger.info("creating role:" + role.getRoleName());
if (identityManager.roleExists(role.getRoleName())) {
return false;
}
if (identityManager.createRole(role.getRoleName())) {
completeRolePersistence(role);
return true;
}
return false;
}
and the completeRolePersistence method:
public void completeRolePersistence(Role role) {
logger.info("setting additional info to role...");
Query query = em.createNamedQuery("UPDT_ADDITIONALS");
query.setParameter("name", role.getRoleName())
.setParameter("description", role.getDescription())
.setParameter("level", role.getRoleLevel());
int updated = query.executeUpdate();
logger.info("roles updated with desc : " + updated);
}
it seem that the query is not executed , i print in log
roles updated with desc : 0
The reason your code does not work is because your update query is executing BEFORE the role is actually inserted into the database, thus it updates nothing.
My advice is to not use the role/user creation methods in IdentityManager. You're better off creating Home components to create/edit your roles and users than having IdentityManager do it for you.
If you however want to pursue this, you need to overwrite JpaIdentityStore, customize the createRole method and have it populate the entity as needed.
Well the question pretty much says everything. Using JPARepository how do I update an entity?
JPARepository has only a save method, which does not tell me if it's create or update actually. For example, I insert a simple Object to the database User, which has three fields: firstname, lastname and age:
#Entity
public class User {
private String firstname;
private String lastname;
//Setters and getters for age omitted, but they are the same as with firstname and lastname.
private int age;
#Column
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
private long userId;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public long getUserId(){
return this.userId;
}
public void setUserId(long userId){
this.userId = userId;
}
}
Then I simply call save(), which at this point is actually an insert into database:
User user1 = new User();
user1.setFirstname("john"); user1.setLastname("dew");
user1.setAge(16);
userService.saveUser(user1);// This call is actually using the JPARepository: userRepository.save(user);
So far so good. Now I want to update this user, say change his age. For this purpose I could use a Query, either QueryDSL or NamedQuery, whatever. But, considering I just want to use spring-data-jpa and the JPARepository, how do I tell it that instead of an insert I want to do an update?
Specifically, how do I tell spring-data-jpa that users with the same username and firstname are actually EQUAL and that the existing entity supposed to be updated? Overriding equals did not solve this problem.
Identity of entities is defined by their primary keys. Since firstname and lastname are not parts of the primary key, you cannot tell JPA to treat Users with the same firstnames and lastnames as equal if they have different userIds.
So, if you want to update a User identified by its firstname and lastname, you need to find that User by a query, and then change appropriate fields of the object your found. These changes will be flushed to the database automatically at the end of transaction, so that you don't need to do anything to save these changes explicitly.
EDIT:
Perhaps I should elaborate on overall semantics of JPA. There are two main approaches to design of persistence APIs:
insert/update approach. When you need to modify the database you should call methods of persistence API explicitly: you call insert to insert an object, or update to save new state of the object to the database.
Unit of Work approach. In this case you have a set of objects managed by persistence library. All changes you make to these objects will be flushed to the database automatically at the end of Unit of Work (i.e. at the end of the current transaction in typical case). When you need to insert new record to the database, you make the corresponding object managed. Managed objects are identified by their primary keys, so that if you make an object with predefined primary key managed, it will be associated with the database record of the same id, and state of this object will be propagated to that record automatically.
JPA follows the latter approach. save() in Spring Data JPA is backed by merge() in plain JPA, therefore it makes your entity managed as described above. It means that calling save() on an object with predefined id will update the corresponding database record rather than insert a new one, and also explains why save() is not called create().
Since the answer by #axtavt focuses on JPA not spring-data-jpa
To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER
Spring-data-jpa supports update operation.
You have to define the method in Repository interface.and annotated it with #Query and #Modifying.
#Modifying
#Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
void setUserInfoById(String firstname, String lastname, Integer userId);
#Query is for defining custom query and #Modifying is for telling spring-data-jpa that this query is an update operation and it requires executeUpdate() not executeQuery().
You can specify the return type as int, having the number of records being updated.
Note: Run this code in a Transaction.
You can simply use this function with save() JPAfunction, but the object sent as parameter must contain an existing id in the database otherwise it will not work, because save() when we send an object without id, it adds directly a row in database, but if we send an object with an existing id, it changes the columns already found in the database.
public void updateUser(Userinfos u) {
User userFromDb = userRepository.findById(u.getid());
// crush the variables of the object found
userFromDb.setFirstname("john");
userFromDb.setLastname("dew");
userFromDb.setAge(16);
userRepository.save(userFromDb);
}
As what has already mentioned by others, the save() itself contains both create and update operation.
I just want to add supplement about what behind the save() method.
Firstly, let's see the extend/implement hierarchy of the CrudRepository<T,ID>,
Ok, let's check the save() implementation at SimpleJpaRepository<T, ID>,
#Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
As you can see, it will check whether the ID is existed or not firstly, if the entity is already there, only update will happen by merge(entity) method and if else, a new record is inserted by persist(entity) method.
spring data save() method will help you to perform both: adding new item and updating an existed item.
Just call the save() and enjoy the life :))
Using spring-data-jpa save(), I was having same problem as #DtechNet. I mean every save() was creating new object instead of update. To solve this I had to add version field to entity and related table.
This is how I solved the problem:
User inbound = ...
User existing = userRepository.findByFirstname(inbound.getFirstname());
if(existing != null) inbound.setId(existing.getId());
userRepository.save(inbound);
With java 8 you can use repository's findById in UserService
#Service
public class UserServiceImpl {
private final UserRepository repository;
public UserServiceImpl(UserRepository repository) {
this.repository = repository;
}
#Transactional
public void update(User user) {
repository
.findById(user.getId()) // returns Optional<User>
.ifPresent(user1 -> {
user1.setFirstname(user.getFirstname);
user1.setLastname(user.getLastname);
repository.save(user1);
});
}
}
public void updateLaserDataByHumanId(String replacement, String humanId) {
List<LaserData> laserDataByHumanId = laserDataRepository.findByHumanId(humanId);
laserDataByHumanId.stream()
.map(en -> en.setHumanId(replacement))
.collect(Collectors.toList())
.forEach(en -> laserDataRepository.save(en));
}
Specifically how do I tell spring-data-jpa that users that have the
same username and firstname are actually EQUAL and that it is supposed
to update the entity. Overriding equals did not work.
For this particular purpose one can introduce a composite key like this:
CREATE TABLE IF NOT EXISTS `test`.`user` (
`username` VARCHAR(45) NOT NULL,
`firstname` VARCHAR(45) NOT NULL,
`description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`username`, `firstname`))
Mapping:
#Embeddable
public class UserKey implements Serializable {
protected String username;
protected String firstname;
public UserKey() {}
public UserKey(String username, String firstname) {
this.username = username;
this.firstname = firstname;
}
// equals, hashCode
}
Here is how to use it:
#Entity
public class UserEntity implements Serializable {
#EmbeddedId
private UserKey primaryKey;
private String description;
//...
}
JpaRepository would look like this:
public interface UserEntityRepository extends JpaRepository<UserEntity, UserKey>
Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.
As mentioned by others answer, method save() is dual function. It can both do save or update, it's automatically update if you provide the id.
for update method in controller class I suggested to use #PatchMapping. below is the example.
#Save method POST
{
"username": "jhon.doe",
"displayName": "Jhon",
"password": "xxxyyyzzz",
"email": "jhon.doe#mail.com"
}
#PostMapping("/user")
public void setUser(#RequestBody User user) {
userService.save(user);
}
#Update method PATCH
{
"id": 1, // this is important. Widly important
"username": "jhon.doe",
"displayName": "Jhon",
"password": "xxxyyyzzz",
"email": "jhon.doe#mail.com"
}
#PatchMapping("/user")
public void patchUser(#RequestBody User user) {
userService.save(user);
}
Maybe you're wondering where the id's come from. It comes from the database of course, you want to update the existing data right?
If your primary key is autoincrement then, you have to set the value for the primary key.
for the save(); method to work as a update().else it will create a new record in db.
if you are using jsp form then use hidden filed to set primary key.
Jsp:
<form:input type="hidden" path="id" value="${user.id}"/>
Java:
#PostMapping("/update")
public String updateUser(#ModelAttribute User user) {
repo.save(user);
return "redirect:userlist";
}
also look at this:
#Override
#Transactional
public Customer save(Customer customer) {
// Is new?
if (customer.getId() == null) {
em.persist(customer);
return customer;
} else {
return em.merge(customer);
}
}
Use #DynamicUpdate annotation. it is cleaner and you don't have to deal with querying the database in order to get the saved values.
You can see the example below:
private void updateDeliveryStatusOfEvent(Integer eventId, int deliveryStatus) {
try {
LOGGER.info("NOTIFICATION_EVENT updating with event id:{}", eventId);
Optional<Event> eventOptional = eventRepository.findById(eventId);
if (!eventOptional.isPresent()) {
LOGGER.info("Didn't find any updatable notification event with this eventId:{}", eventId);
}
Event event = eventOptional.get();
event.setDeliveryStatus(deliveryStatus);
event = eventRepository.save(event);
if (!Objects.isNull(event)) {
LOGGER.info("NOTIFICATION_EVENT Successfully Updated with this id:{}", eventId);
}
} catch (Exception e) {
LOGGER.error("Error :{} while updating NOTIFICATION_EVENT of event Id:{}", e, eventId);
}
}
Or Update Using Native Query:
public interface YourRepositoryName extends JpaRepository<Event,Integer>{
#Transactional
#Modifying
#Query(value="update Event u set u.deliveryStatus = :deliveryStatus where u.eventId = :eventId", nativeQuery = true)
void setUserInfoById(#Param("deliveryStatus")String deliveryStatus, #Param("eventId")Integer eventId);
}
I did this for my Entity UserModel:
In the Controller:
#PutMapping("/{id}")
public Optional<UserModel> update(#RequestBody UserModel user, #PathVariable Long id) {
return this.userService.update(user, id);
}
And in the Service:
public Optional<UserModel> update(UserModel req, Long id){
Optional<UserModel> user = userRepository.findById(id);
if (user != null) {
userRepository.save(req);
}
return user;
}
Example with postman:
Postman method PUT example