Make field insertable but not updatable in Spring Data REST + MongoDB - jackson

With Spring Data REST and Spring Data Mongo, I want to make a domain field (field username of domain User in my example) insertable when create but un-updatable when update. In other words an equivalent of JPA #Column(insertable = true, updatable = false).
I try a few approach but not work.
In my github project, domain class and repository are put in /src/main/java/*/*/User.java and UserRepository.java. The test is put in /src/test/java/*/*UserTest.java.
1. Spring Data annotation #ReadOnlyProperty and #Transient
The field is un-insertable when save to DB. See package readonlyproperty and transient_ in the project.
2. Jackson annotation #JsonProperty(access=READ_ONLY)
The field is un-insertable when create via POST request, because the JSON property is ignored when initiate an object. See package jsonpropertyreadonly in the project.
3. #JsonCreator on constructor and #JsonIgnore on setter
If the un-updatable field username is contained in json body of PUT or PATCH request, and username value changes, username get updated, which is unexpected. See package jsoncreator in the project.
4. Do not write a setter
same as 3. See package nosetter in the project.
5. Toggle on/off feature
spring.jackson.deserialization.fail-on-ignored-properties=false
spring.jackson.deserialization.fail-on-unknown-properties=false
spring.jackson.mapper.infer-property-mutators=false
not help
Spring Data REST PUT and PATCH Internal Implementation
PUT: it uses Jackson ObjectMapper.readerFor(Class) to initiate a new object
PATCH: it uses Jackson ObjectMapper.readerForUpdating(objectToUpdate).readValue(json), which use setter to update the objectToUpdate. Seems readerForUpdating doesn't see the #JsonIgnore on setter.
The only solution I know is implementing the setter in below way
void setUsername(String usernameToSet) {
if (null == this.username)
this.username = usernameToSet;
}
And disable PUT method, only use PATCH to update. See package setterchecknull.
Is there a better way? Thank you very much!!

Related

bytebuddy apply advice to interface methods - specifically spring data jpa

I am trying to LOG all methods that are invoked in my Springboot application using byte-buddy based java agent.
I am able to log all layers except Spring data JPA repositories, which are actually interfaces. Below is agent initialization:
new AgentBuilder.Default()
.type(ElementMatchers.hasSuperType(nameContains("com.soka.tracker.repository").and(ElementMatchers.isInterface())))
.transform(new AgentBuilder.Transformer.ForAdvice()
.include(TestAgent.class.getClassLoader())
.advice(ElementMatchers.any(), "com.testaware.MyAdvice"))
.installOn(instrumentation);
any hints or workaround that I can use to log when my repository methods are invoked. Below is a sample repository in question:
package com.soka.tracker.repository;
.....
#Repository
public interface GeocodeRepository extends JpaRepository<Geocodes, Integer> {
Optional<Geocodes> findByaddress(String currAddress);
}
Modified agent:
new AgentBuilder.Default()
.ignore(new AgentBuilder.RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader().or(isExtensionClassLoader())))
.ignore(new AgentBuilder.RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.")
.and(not(ElementMatchers.nameStartsWith(NamingStrategy.SuffixingRandom.BYTE_BUDDY_RENAME_PACKAGE + ".")))
.or(nameStartsWith("sun.reflect."))))
.type(ElementMatchers.nameContains("soka"))
.transform(new AgentBuilder.Transformer.ForAdvice()
.include(TestAgent.class.getClassLoader())
.advice(any(), "com.testaware.MyAdvice"))
//.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(instrumentation);
I see my advice around controller and service layers - JPA repository layer is not getting logged.
By default, Byte Buddy ignores synthetic types in its agent. I assume that Spring's repository classes are marked as such and therefore not processed.
You can set a custom ignore matcher by using the AgentBuilder DSL. By default, the following ignore matcher is set to ignore system classes and Byte Buddy's own types:
new RawMatcher.Disjunction(
new RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader().or(isExtensionClassLoader())),
new RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.")
.and(not(ElementMatchers.nameStartsWith(NamingStrategy.SuffixingRandom.BYTE_BUDDY_RENAME_PACKAGE + ".")))
.or(nameStartsWith("sun.reflect."))
.<TypeDescription>or(isSynthetic())))
You would probably need to remove the last condition.
for anybody visiting this question / problem - I was able to go around the actual problem with logging actual queries invoked during execution - Bytebuddy is awesome and very powerful - for ex- in my case I am simply advice'ing on my db connection pool classes and gathering all required telemetry -
.or(ElementMatchers.nameContains("com.zaxxer.hikari.pool.HikariProxyConnection"))

Save or Merge Patch Entity

I want following functionality in spring data rest.
If I post to a collection resource end point, server should check if the object exists. if it exists already it should perform the same functionality as it does with merge-patch on item resource. If object does not exist already it should create it.
Is this achievable in spring data rest. If so then how?
If it is possible in your use case, you might want to use PUT instead of POST, as PUT should work as you expected.
Solution with POST
You can achieve the desired behavior with Spring Data REST Event handlers.
Just create a Handler method which accepts your entity and annotate it with #HandleBeforeCreate. In this method, you can implement your behavior, i.e. check if the object exists and update it manually or just do nothing and let the Spring Data REST handle the entity creation.
#RepositoryEventHandler
public class EntityEventHandler {
#Autowired
private EntityService entityService;
#HandleBeforeCreate
public void handleEntityCreate(Entity e) {
if (entityService.exists(e)) {
entityService.update(e);
}
}
}
EDIT:
I just realized that you would also need to stop the create event after your update. You might try throwing a custom Exception and Handling it to return 200 and the updated entity.

jackson-dataformat-csv: cannot serialize LocalDate

When I try to serialize object containing Local date, I get following error:
csv generator does not support object values for properties
I have JSR-310 module enabled, with WRITE_DATES_AS_TIMESTAMPS and I can convert the same object to JSON without problem.
For now I resorted to mapping the object to another, string only object, but it's decadent and wasteful.
Is there a way for Jackson csv mapper to acknowledge localDates? Should I somehow enable JSR-310 specifically for csv mapper?
I had the same problem because of configuring mapper after schema. Make sure you are using the latest verson of jackson and its modules. This code works for me:
final CsvMapper mapper = new CsvMapper();
mapper.findAndRegisterModules();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //Optional
final CsvSchema schema = mapper.schemaFor(PojoWithLocalDate.class);
// Use this mapper and schema as you need to: get readers, writers etc.
No additional annotations needed in Pojo class.

Sylius - How to implement a custom EntityRepository

I'm getting a bit frustrated trying to override the repository of my own Entity.
I need to create a custom repository method to get a list of my entities with special way. One queryBuilder with Having and OrderBy.
Te question is how can I setup my config to say Sylius, take my custom repositor, not the default.
I try this:
sylius_resource:
resources:
dinamic.category:
classes:
model: App\Bundle\SyliusBlogBundle\Entity\PostCategory
repository: App\Bundle\SyliusBlogBundle\Repository\PostCategoryRepository
This is my Repository:
<?php
namespace App\Bundle\SyliusBlogBundle\Repository;
use Doctrine\ORM\EntityRepository;
class PostCategoryRepository extends EntityRepository
{
public function findCategoriesMenu()
{
$queryBuilder = $this->createQueryBuilder('c');
return $queryBuilder
->addSelect('COUNT(p.id) as totalPosts')
->leftJoin('c.posts', 'p')
->andWhere('p.published = true')
->having('totalPosts > 0')
->addGroupBy('p.id')
;
}
}
When I try to use this method, Symfony throws me this error:
An exception has been thrown during the rendering of a template ("Undefined method 'findCategoriesMenu'. The method name must start with either findBy or findOneBy!")
Well you aren't subclassing the correct repository. The ResourceController expects a repository based on the Sylius\Component\Resource\Repository\RepositoryInterface. Since you are subclassing from Doctrine\ORM\EntityRepository that won't be the case.
Your repository should inherit from Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository (or implement the interface yourself).
I answer to the post to paste correctly the response of app/console debug:container dinamic.repository.category
Information for Service "dinamic.repository.category"
=====================================================
------------------ -------------------------------------------------------------------
Option Value
------------------ -------------------------------------------------------------------
Service ID dinamic.repository.category
Class Dinamic\Bundle\SyliusBlogBundle\Repository\PostCategoryRepository
Tags -
Scope container
Public yes
Synthetic no
Lazy no
Synchronized no
Abstract no
Autowired no
Autowiring Types -
------------------ -------------------------------------------------------------------
Since here all it's ok.
When i try to access to Posts list this error appears:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Argument 4 passed to Sylius\Bundle\ResourceBundle\Controller\ResourceController::__construct() must implement interface Sylius\Component\Resource\Repository\RepositoryInterface, instance of Dinamic\Bundle\SyliusBlogBundle\Repository\PostCategoryRepository given, called in /Applications/XAMPP/xamppfiles/htdocs/rosasinbox-sylius/app/cache/dev/appDevDebugProjectContainer.php on line 2767 and defined")
The error of main post appears when the repository config wasn't set. Then my first post was wrong, on config.yml repository value wasn't set.
Now i set it another time and i got this error.
Sorry for the confusion.

How to save and then update same class instance during one request with NHibernate?

I'm relatively new to NHibernate and I've got a question about it.
I use this code snippet in my MVC project in Controller's method:
MyClass entity = new MyClass
{
Foo = "bar"
};
_myRepository.Save(entity);
....
entity.Foo = "bar2";
_myRepository.Save(entity);
The first time entity saved in database succesfully. But the second time not a single request doesnt go to database. My method save in repository just does:
public void Save(T entity)
{
_session.SaveOrUpdate(entity);
}
What should I do to be able to save and then update this entity during one request? If I add _session.Flush(); after saving entity to database it works, but I'm not sure, if it's the right thing to do.
Thanks
This is the expected behavior.
Changes are only saved on Flush
Flush may be called explicitly or implicitly (see 9.6. Flush)
When using an identity generator (not recommended), inserts are sent immediately, because that's the only way to return the ID.
you should be using transactions.
a couple of good sources: here and here.
also, summer of nHibernate is how I first started with nHibernate. it's a very good resource for learning the basics.