Spring Data MongoDB BeforeSaveCallback not working - spring

I want to have similar functionality as I get with the JPA #PrePersist but in a mongodb database. Reading the spring data mongodb documentation I found the entity callbacks: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#entity-callbacks. They seem to work for what I need so I'm trying to implement some callbacks. I know there are some alternatives for what I'm doing (auditing annotations) but I want to keep with this for the moment.
This is how I register the callback, my entity definition and the repository:
#Configuration
public class BeforeSaveCallbackConfiguration {
#Bean
BeforeSaveCallback<Measurement> beforeSaveMeasurement() {
return (entity, document, collection) -> {
entity.setTimestamp(System.currentTimeMillis());
System.out.println("Before save, timestamp: " + entity.getTimestamp());
return entity;
};
}
}
public interface MeasurementRepository extends MongoRepository<Measurement, String> {
}
#Document
public class Measurement {
private String id;
private long timestamp;
private Float value1;
private Float value2;
// constructor, getters, setters ...
}
I save the entity using measurementRepository.save method of the repository. I actually see the printed line from the callback with the timestamp. However the data saved in the mongodb collection always have timestamp set to 0. Does anyone have any hint?

You implement BeforeConvertCallback interface can work for you:
#Component
public class TestCallBackImpl implements BeforeConvertCallback<Measurement> {
#Override
public Measurement onBeforeConvert(Measurement entity, String collection) {
entity.setTimestamp(System.currentTimeMillis());
return entity;
}
}

Related

Spring boot REST API best way to choose in client side which field to load

Hi I have implemented a mock solution to my problem and I'm pretty sure something better already exist.
Here's that I want to achieve :
I have created a point to load categories with or without subCategories
/api/categories/1?fields=subCategories
returns
{
"id":"1",
"name":"test",
"subCategories":[{
"id":"1",
"name":"test123"
}]
}
/api/categories/1
returns
{
"id":"1",
"name":"test"
}
My entities
#Entity
class Category{
#Id
private String id;
private String name;
private Set<SubCategory> subCategories;
}
#Entity
class SubCategory{
#Id
private String id;
private String name;
}
I have removed services since this is not the point.
I've created CategoryDTO and SubCategoryDTO classes with the same fields as Category and SubCategory
The converter
class CategoryDTOConverter{
CategoryDTO convert(Category category,String fields){
CategoryDTO dto=new CategoryDTO();
dto.setName(category.getName());
if(StringUtils.isNotBlank(fields) && fields.contains("subCategories"){
category.getSubCategories().forEach(s->{
dto.getSubcategories().add(SubCategoryDTOConverter.convert(s));
}
}
}
}
I used com.cosium.spring.data.jpa.entity.graph.repository to create an EntityGraph from a list of attribute path
#Repository
interface CategoryRepository extends EntityGraphJpaRepository<Category, String>{
Optional<T> findById(String id,EntityGraph entityGraph);
}
Controller
#RestController
#CrossOrigin
#RequestMapping("/categories")
public class CategoryController {
#GetMapping(value = "/{id}")
public ResponseEntity<CategoryDTO> get(#PathVariable("id") String id, #RequestParam(value="fields",required=false) String fields ) throws Exception {
Optional<Category> categOpt=repository.findById(id,fields!=null?EntityGraphUtils.fromAttributePaths(fields):null);
if(categOpt.isEmpty())
throws new NotFoundException();
return ResponseEntity.ok(categoryDTOConverter.convert(categOpt.get(),fields);
}
}
This is a simple example to illustrate what I need to do
I don't want to load fields that clients doesn't want to use
How could I do this in a better way ?
Take a look at GraphQL since it is a perfect match for your use case. With GraphQL it is the client that decides which attributes it wants to receive by providing in the POST request body exactly which attributes are needed to be included in the response. This is way more manageable than trying to handle all this on your own.
Spring Boot recently added its own Spring GraphQL library, so it is quite simple to integrate it in your Spring Boot app.

How to make Set using spring-data-aerospike

Environment:
spring-boot v2.0.4 RELEASE
spring-data-aerospike v2.0.1.RELEASE
java - 8
Here are my application code and properties.
// application.properties
aerospike.hosts=xxx:3000
aerospike.namespace=test
// aerospike configuration class
#Configuration
#RequiredArgsConstructor
#EnableConfigurationProperties(AerospikeConfiguration.AerospikeConfigurationProperties.class)
#EnableAerospikeRepositories(basePackageClassses = TestAeroRepository.class)
public class AerospikeConfiguration extends AbstractAerospikeDataConfiguration {
private final AerospikeConfigurationProperties aerospikeConfigurationProperties;
#Override
protected Collection<Host> getHosts() {
return Host.parseServiceHosts(aerospikeConfigurationProperties.getHosts());
}
#Override
protected String nameSpace() {
return aerospikeConfigurationProperties.getNamespace();
}
#Data
#Validate
#ConfigurationProperties("aerospike")
public static class AerospikeConfigurationProperties {
#NotEmpty
String hsots;
#NotEmpty
String namespace;
}
}
# Entity class
#Value
#Document
#Builder(toBuilder = true)
#AllArgsConstructor
public class testEntity() {
#Id
int id;
#Field
String name;
#Field
String timestamp;
}
#Repository
public interface TestAeroRepository extends AerospikeRepository<TestEntity, Integer> {
}
public interface TestAeroService {
void save();
}
#Service
#RequiredArgsConstructor
public class TestAeroServiceImpl implements TestAeroService {
private final TestAeroRepository testAeroRepository;
#Override
public void save(TestEntity entity) {
testAeroRepository.save(entity);
}
}
I checked Aerospike client connection has no problem.
But error is occurred when save() method is executed.
org.springframework.cglib.core.ReflectUtils.defineClass(Ljava/lang/String;[BLjava/lang/ClassLoader;Ljava/security/ProtectionDomain;Ljava/lang/Class;)Ljava/lang/Class;
Have to make sets before execute the application? I didn't make sets.
Any problem with my code?
You’re using an old version of spring-data-aerospike (2.0.1.RELEASE was released on April 2019) is there any chance you can upgrade to the latest version? 2.4.2.RELEASE
You can see how to setup a simple spring data aerospike application here: https://medium.com/aerospike-developer-blog/simple-web-application-using-java-spring-boot-aerospike-database-and-docker-ad13795e0089
Please share the entire project’s code and the entire exception.
I would look into:
The configuration class (The Aerospike Beans creation).
The content of the testEntity class - are you using #Id annotation on the primary key field?
Extending the repository class with specifying the testEntity object (… extends AerospikeRepository<testEntity, Object> {) you can see an example in the link I added.
The set is automatically created and takes the name of your object class, which is testEntity in your case. For example, based on your code, if you do not specify a collection in the #Document annotation a set named "testEntity" will automatically be created. I added the #Document(collection = "testEntitys") annotation and all I did was create two set. Once you insert your first record, run the "SHOW SETS" aql command and it will be there. So that's one way to do it.

mapping entity to DTO with nested DTO

I have a relationnal (heavy) database model with a lot of table dependencies and foreign keys.
We have choosen to use DTOs in order to simplify data representation ton front and hide database mode complixity.
But we have DTO with nested DTO. And we have Mapper implementation classes to set data with small business/functional logic.
The question is if it is a good pratice that a mapper class calls mapper (etc.) or is it a best way to have a main class handling all mapper classes ? (Example 1 or2)
Example 1 :
#Component
public class ActorMapperImpl implements ActorMapper {
#Autowired
private InsurerMapper insurerMapper;
#Autowired
private PersonMapper personMapper;
#Autowired
private CorrespondentMapper correspondentMapper;
....
#Override
public ActorDto mapToDto(Acteur actor) {
final ActorDto actorDto;
if (actor != null) {
....
actorDto.setPerson(personMapper.personneToPersonDto(actor.getPersonne()));
if (actor.getInsurer() != null) {
actorDto.setInsurer(insurerMapper.entityToDto(actor.getInsurer()));
} else if (actor.getCorrespondantAssureur() != null) {
actorDto.setInsurer(correspondentMapper.correspondentToInsurerDto(actor.getCorrespondantAssureur()));
}
....
// intermediate
final Intermediaire intermediate = actor.getIntermediaire();
if (intermediate != null) {
.....
if (person != null) {
intermediateDto = personMapper.personneToPersonDto(person);
intermediateDto.setQuality(quality);
}
.....
}
.....
Example 2 :
#Service
public class FinancialSlipOrchestratorImpl implements FinancialSlipOrchestrator {
.....
#Autowired
private FinancialSlipMapper financialSlipMapper;
#Autowired
private PersonMapper personMapper;
..... some public / private methods
private FinancialSlipDto fullMapToDto(FinancialSlip financialSlip) {
.....
// Financial slip
var financialSlipDto = financialSlipMapper.mapToDto(financialSlip);
// person
financialSlipDto.setIssuerPerson(personMapper.personneToPersonDto(financialSlip.getIssuerPerson()));
....
// RIB
financialSlipDto.setRib(ribMapper.mapToDto(financialSlip.getRib()));
return financialSlipDto;
}
I would say that it's ok for one mapper to call another and think this is a perfect use case for Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
#EntityView(Acteur.class)
public interface ActorDto {
#IdMapping
Long getId();
String getName();
PersonDto getPerson();
default InsurerDto getInsurer() {
return getMainInsurer() != null ? getMainInsurer(): getCorrespondantAssureur();
}
#Mapping("insurer")
InsurerDto getMainInsurer();
InsurerDto getCorrespondantAssureur();
IntermediaireDto getIntermediaire();
#EntityView(Person.class)
interface PersonDto {
#IdMapping
Long getId();
String getName();
}
#EntityView(Insurer.class)
interface InsurerDto {
#IdMapping
Long getId();
String getName();
}
#EntityView(Intermediaire.class)
interface IntermediaireDto {
#IdMapping
Long getId();
String getName();
Integer getQuality();
PersonDto getPerson();
}
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
ActorDto a = entityViewManager.find(entityManager, ActorDto.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
The best thing about this is, it will only fetch the data that is actually necessary.
If you use DTOs for flushing back changes as well, you will be delighted to hear that Blaze-Persistence Entity-Views also supports that in a very efficient manner. This will allow you to get rid of all those manually written mappers :)

Spring Data Jpa custom repository no property found

I'm trying to create a repository that has a method which doesn't fit the usual JpaRepository with #Query annotations.
I've created a custom repository interface:
public interface CustomVoteRepository {
List<VoteCountResult> countVotesForSession();
}
And the implementation:
#Repository
public class CustomVoteRepositoryImp implements CustomVoteRepository {
private JdbcTemplate jdbcTemplate;
public CustomVoteRepositoryImp(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Override
public List<VoteCountResult> countVotesForSession() {
return jdbcTemplate.query("SELECT video_id, COUNT(votes.id) FROM votes WHERE session_id=2 GROUP BY video_id",
new CustomRowMapper());
}
}
However, this gives me this error:
No property countVotesForSession found for type Vote!
I don't understand why it's trying to map a property on the Vote class. I understand it does this for the "auto-generated" method names, but this is supposed to be a custom one.
I've come across this article: https://www.mkyong.com/spring-data/spring-data-add-custom-method-to-repository/ which explains what I'm doing, and yet it's trying to map a property of the model for a custom repository.
I'm sure I missed something stupid.
Thanks!
Edit:
Here's the VoteCountResult dto:
#Data
#AllArgsConstructor
public class VoteCountResult {
private String count;
private String title;
private String url;
}
What if you change your custom method name to votesForSessionCount ? I think this way you won't face with method name conflict.

Java 8 Date Time api in JPA

What is the best way how to integrate Java 8 Date Time api in jpa?
I have added converters:
#Converter(autoApply = true)
public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate localDate) {
return Date.valueOf(localDate);
}
#Override
public LocalDate convertToEntityAttribute(Date date) {
return date.toLocalDate();
}
}
and
#Converter(autoApply = true)
public class LocalDateTimePersistenceConverter implements AttributeConverter<LocalDateTime, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(LocalDateTime entityValue) {
return Timestamp.valueOf(entityValue);
}
#Override
public LocalDateTime convertToEntityAttribute(Timestamp databaseValue) {
return databaseValue.toLocalDateTime();
}
}
Everything seems fine, but how should I use JPQL for querying? I am using Spring JPARepository, and goal is to select all entities where date is the same as date given, only difference is that it is saved in entity as LocalDateTime.
So:
public class Entity {
private LocalDateTime dateTime;
...
}
And:
#Query("select case when (count(e) > 0) then true else false end from Entity e where e.dateTime = :date")
public boolean check(#Param("date") LocalDate date);
When executing it just gives me exception, which is correct.
Caused by: java.lang.IllegalArgumentException: Parameter value [2014-01-01] did not match expected type [java.time.LocalDateTime (n/a)]
I have tried many ways, but it seems that none is working, is that even possible?
Hibernate has an extension library, hibernate-java8 I believe, which natively supports many of the time types.
You should use it before writing converters.
in hibernate 5.2 you won't need this additional library, it is part of core.
To query temporal fields you should use the #Temporal Anotation in the temporal fields, add the converters to persistence.xml and also be sure you are using the java.sql.Date,java.sql.Time or java.sql.Timestamp in the converters. (Sometimes i imported from the wrong package)
for example thats works for me:
#Temporal(TemporalType.TIMESTAMP)
#Convert(converter = InstantPersistenceConverter.class)
private Instant StartInstant;
#Temporal(TemporalType.TIME)
#Convert(converter = LocalTimePersistenceConverter.class)
private LocalTime StartTime;
and my Instant converter:
#Converter(autoApply = true)
public class InstantPersistenceConverter implements AttributeConverter <Instant,java.sql.Timestamp>{
#Override
public java.sql.Timestamp convertToDatabaseColumn(Instant entityValue) {
return java.sql.Timestamp.from(entityValue);
}
#Override
public Instant convertToEntityAttribute(java.sql.Timestamp databaseValue) {
return databaseValue.toInstant();
}
}
Did you add LocalDatePersistenceConverter and LocalDateTimePersistenceConverter in persistence.xml placed in 'class' element ?

Resources