Spring Data: Override save method
Didn't get this to work nicely so I put my required logic into a service class and left the repositories save method untouched.
Override spring data save method
As described in my comment overriding 'save' won't achieve your goal. JPA might throw exceptions all over your code. This is one of the problems of JPA.
I guess you could overwrite some central method of Spring to achieve your goal but that really isn't how Spring works.
In stead you basically register your exception handling so, it gets invoked by Spring as desired.
There is an article about this by Baeldung, which looks promising and is valued high by Google.
Spring boot overiding save Method in JpaRepository interface
First make an interface for your generic repo:
@NoRepositoryBean
public interface GenericRepository<T extends BaseModel, Long> extends JpaRepository<T, Long> {}
Then create your implementation:
public class GenericRepositoryImpl<T extends BaseModel> extends SimpleJpaRepository<T, Long> implements GenericRepository<T, Long> {
@Override
public <S extends T> S save(S baseModel) {
long timeStamp = System.currentTimeMillis();
if (baseModel.createdTimeStamp == 0) {
baseModel.createdTimeStamp = timeStamp;
baseModel.updatedTimeStamp = timeStamp;
} else {
baseModel.updatedTimeStamp = timeStamp;
}
save(baseModel);
return baseModel;
}
}
Lastly, tell Spring to use this as the base class for your repositories. Somewhere in your configuration..
@Configuration
@EnableJpaRepositories(repositoryBaseClass = GenericRepositoryImpl.class)
Then you can use it like so:
public interface MyEntityRepository extends GenericRepository<MyEntity> {}
Some bean:
@Autowired
private MyEntityRepository myEntityRepository;
Override default save Entity on Spring Data Rest
Found a solution:
@BasePathAwareController
@RequestMapping("/users")
public class RestApiController implements ResourceProcessor<Resource<User>>{
@Autowired
private EntityLinks entityLinks;
@RequestMapping(method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<Resource<User>> saveUser(@Param("name") String name) {
// Testing
System.out.println(name);
Resource<User> resource = new Resource<>(new User());
return new ResponseEntity<>(resource , HttpStatus.OK);
}
@Override
public Resource<User> process(Resource<User> resource) {
LinkBuilder lb = entityLinks.linkFor(User.class);
resource.add(new Link(lb.toString()));
return resource;
}
}
The CrudRepository save is still set as exported=false as in my question.
How can I implement a Save Or Update function using Spring Data Jpa?
Update::
Ok, thanks for the comments, I've decided to add a separate update method! I think this is looking better!
@Override
public void updateOrder(Order order) {
long id = orderRepository.findByOrderId(order.get().getId());
order.setId(id);
orderRepository.save(order);
}
A good point was made about Spring Data JPA's save(..) method doing an upsert by default. But, unfortunately in the project I'm working on the primary keys are autogenerated. This means that whenever save(..) is executed on an existing record to update it, a new record is created instead! That's why I explicitly set the id here to avoid that happening!
I've also added and eclipse-link library @Index annotation to the orderId column (not primary key) in the entity class to speed up the update method's findByOrderId!
Related Topics
Convert Arraylist into 2D Array Containing Varying Lengths of Arrays
Meaning of Delta or Epsilon Argument of Assertequals for Double Values
"File Not Found" When Running New Libgdx Project
How to Copy File Inside Jar to Outside the Jar
Printing in Java to Label Printer
Why Does It Compile When Casting to an Unrelated Interface
How to Manually Set an Authenticated User in Spring Security/Springmvc
Hibernate: Flush() and Commit()
Check and Extract a Number from a String in Java
Is It Better Practice to Use String.Format Over String Concatenation in Java
Does Java Support Inner/Local/Sub Methods
How to Do an Integer.Parseint() for a Decimal Number