Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a read-only property with Spring Data?

This should be a simple thing to do! But I've been unable to find an answer so far. Either I'm missing something obvious, or else I'm missing something obvious...

I have a class, say Person. With three fields - "id", "name" and "reputation". Let's say that I am willing to take updates to "name" but not to "reputation". I'd like Spring Data to fetch the value of "reputation" when retrieving from DB, but ignore it when I'm saving the bean.

@Transient annotation is there, but then Spring completely ignores the field and doesn't populate it at all. Ideally, I'm looking for something like @ReadOnly annotation.

More details

  • I'm using Spring Data for Neo4j, but I believe this would apply to any Spring Data flavor.
  • This is a backend for Jersey/Jackson-based RESTful service. ** When I satisfy the GET request, I'd like to serve the "reputation" value. But when I receive a PUT update I don't want to take it. ** So far I could use Jackson features. But I'd like to be able to update the DB without having to fetch the existing Person object first.
  • The only way I can figure for making this work is to define two classes - one with "reputation" field and one without. But this seems really clunky. Isn't there something simpler?
like image 866
Dmitry Serebrennikov Avatar asked Mar 30 '13 00:03

Dmitry Serebrennikov


People also ask

Do we need @transactional for read-only?

Generally, we use @Transactional(readOnly = true) for search or retrieval operation to make sure we can only perform the read-only operation. We can override readOnly behavior using @Modifying annotation.

How do I make my JPA entity read-only?

In your entity add an EntityListener like this: @Entity @EntityListeners(PreventAnyUpdate. class) public class YourEntity { // ... } This will create a bullet proof safety net for your entity with JPA lifecycle listeners.

What is readOnly transaction spring?

Spring @Transactional annotationThe readOnly attribute can further be used by Spring to optimize the underlying data access layer operations. Prior to Spring 5.1, when using Hibernate, the readOnly attribute of the @Transactional annotation was only setting the current Session flush mode to FlushType.

What does @transactional annotation do?

The @Transactional annotation is the metadata that specifies the semantics of the transactions on a method. We have two ways to rollback a transaction: declarative and programmatic. In the declarative approach, we annotate the methods with the @Transactional annotation.


Video Answer


1 Answers

You can use a transient property without a setter. That transient property would return the db property value that is to be protected.

like image 59
jagra Avatar answered Sep 23 '22 11:09

jagra