I use play framework 1.2.5.3 (with Hibernate 3.6.10), postgreSql 9.2.9.
I have table requests with column uid that I want to generate by custom rules described in my postgreSql trigger (before insert trigger set uid value).
I want to use generated value in my code. I have following models:
#Entity
#Table(name = "requests")
...
public class Request extends GenericModel {
...
#Column(name = "uid", length = Domains.SHORT_STRING)
public String uid;
...
}
The complexity associated with inheritance models
#Entity
#Table(name = "kindergartenrequests")
#PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class KindergartenRequest extends Request {
...
private static KindergartenRequest create(...) {
KindergartenRequest request = new KindergartenRequest(...); // put null uid
request._save();
Logger.debug(request.uid); // uid is still null here
...
}
}
I tried following:
Defining getter on uid field:
public String getUid() {
if (this.uid == null) {
this.refresh();
}
return this.uid;
}
Defining post persist callback:
#PostPersist
private void afterSave() {
if (this.uid == null) {
this.uid = Request.em()
.createNativeQuery("SELECT uid FROM requests WHERE id = :id")
.setParameter("id", this.id)
.getSingleResult()
.toString();
}
}
But there is no effect in the KindergartenRequest class.
And I don't want to refresh it manually on each request creation. Like that:
request._save();
request.refresh();
Well actually #PostPersist method works fine. Probably play must be full-restarted after some changes.
Related
After searching for quite a long time I'm wondering if my code is wrong or if it's simply impossible in Hibernate.
I'll use a fake example to explain my problem. Let's say I have three tables in my database, post, posttag and tag. A post can have multiple tags and a tag can be used my multiple posts, so it's a many-to-many association but there's also extra columns in the table between (posttag).
example entity relationship diagram
So, in my code, I have 3 entity and one more class for the composite key of posttag.
PostEntity:
#Entity
#Table(name = "post", catalog = "fakeExample")
public class PostEntity implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "IDPOST", nullable = false)
private Integer idpost;
#OneToMany(mappedBy = "post", targetEntity = PostTagEntity.class, cascade = CascadeType.ALL, orphanRemoval = true)
private List<PostTagEntity> listOfPostTag = new ArrayList<>();
public void setIdpost(Integer idpost)
{
this.idpost = idpost;
}
public Integer getIdpost()
{
return this.idpost;
}
public void setListOfPostTag(List<PostTagEntity> listOfPostTag)
{
if (listOfPostTag != null)
{
this.listOfPostTag.clear();
this.listOfPostTag.addAll(listOfPostTag);
}
}
public List<PostTagEntity> getListOfPostTag()
{
return this.listOfPostTag;
}
}
TagEntity:
#Entity
#Table(name = "tag", catalog = "fakeExample")
public class TagEntity implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "IDTAG", nullable = false)
private Integer idtag;
#OneToMany(mappedBy = "tag", targetEntity = PostTagEntity.class, cascade = CascadeType.ALL, orphanRemoval = true)
private List<PostTagEntity> listOfPostTag = new ArrayList<>();
public void setIdtag(Integer idtag)
{
this.idtag = idtag;
}
public Integer getIdtag()
{
return this.idtag;
}
public void setListOfPostTag(List<PostTagEntity> listOfPostTag)
{
if (listOfPostTag != null)
{
this.listOfPostTag.clear();
this.listOfPostTag.addAll(listOfPostTag);
}
}
public List<PostTagEntity> getListOfPostTag()
{
return this.listOfPostTag;
}
}
PostTagEntity:
#Entity
#Table(name = "posttag", catalog = "fakeExample")
public class PostTagEntity implements Serializable
{
#EmbeddedId
private PostTagEntityKey compositePrimaryKey = new PostTagEntityKey();
#Column(name = "EXTRACOLUMN")
private Integer extraColumn;
#ManyToOne
#JoinColumn(name = "IDPOST", referencedColumnName = "IDPOST", nullable = false)
#MapsId("idpost")
private PostEntity post;
#ManyToOne
#JoinColumn(name = "IDTAG", referencedColumnName = "IDTAG", nullable = false)
#MapsId("idtag")
private TagEntity tag;
public void setIdpost(Integer idpost)
{
this.compositePrimaryKey.setIdpost(idpost);
}
public Integer getIdpost()
{
return this.compositePrimaryKey.getIdpost();
}
public void setIdtag(Integer idtag)
{
this.compositePrimaryKey.setIdtag(idtag);
}
public Integer getIdtag()
{
return this.compositePrimaryKey.getIdtag();
}
public void setExtraColumn(Integer extraColumn)
{
this.extraColumn = extraColumn;
}
public Integer getExtraColumn()
{
return this.extraColumn;
}
public void setPost(PostEntity post)
{
this.post = post;
}
public PostEntity getPost()
{
return this.post;
}
public void setTag(TagEntity tag)
{
this.tag= tag;
}
public TagEntity getTag()
{
return this.tag;
}
}
PostTagEntityKey:
#Embeddable
public class PostTagEntityKey implements Serializable
{
#Column(name = "IDPOST", nullable = false)
private Integer idpost;
#Column(name = "IDTAG", nullable = false)
private Integer idtag;
public PostTagEntityKey()
{
}
public PostTagEntityKey(Integer idpost, Integer idtag)
{
this.idsalle = idsalle;
this.idequipement = idequipement;
}
public void setIdpost(Integer value)
{
this.idpost = value;
}
public Integer getIdpost()
{
return this.idpost;
}
public void setIdtag(Integer value)
{
this.idtag = value;
}
public Integer getIdtag()
{
return this.idtag;
}
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.getClass() != obj.getClass())
{
return false;
}
PostTagEntityKey other = (PostTagEntityKey) obj;
if (this.idpost == null ? other.idpost != null : !this.idpost.equals((Object) other.idpost))
{
return false;
}
if (this.idpost == null ? other.idpost != null
: !this.idtag.equals((Object) other.idtag))
{
return false;
}
return true;
}
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((idpost == null) ? 0 : idpost.hashCode());
result = prime * result + ((idtag == null) ? 0 : idtag.hashCode());
return result;
}
}
Also, I am using Spring, so here are the few class involved when I do an insert or something else. I don't think the problem come from here but just in case.
PostService:
public interface PostService
{
public List<PostEntity> findAll();
public Optional<PostEntity> findById(int var1);
public PostEntity save(PostEntity var1);
public void deleteById(int var1);
}
PostImpl:
#Service
public class PostImpl implements PostService
{
#Autowired
private PostRepository repository;
#Override
public List<PostEntity> findAll()
{
return this.repository.findAll();
}
#Override
public Optional<PostEntity> findById(int id)
{
return this.repository.findById(id);
}
#Override
public PostEntity save(PostEntity toSave)
{
return (PostEntity) this.repository.save(toSave);
}
#Override
public void deleteById(int id)
{
this.repository.deleteById(id);
}
}
PostRepository:
#Repository
public interface PostRepository extends JpaRepository<PostEntity, Integer>, JpaSpecificationExecutor<PostEntity>, PagingAndSortingRepository<PostEntity, Integer>
{
}
So when I need to insert a post, I just use something like this:
#Autowired
PostService postService;
public PostEntity createPost(PostEntity post)
{
return this.postService.save(post);
}
For me, the expected behaviour of Hibernate would be:
when I insert a post, to insert the post and insert every postTag in listOfPostTag
when I update a post, to remove every missing postTag in listOfPostTag, to add every new postTag in listOfPostTag, to update the change postTag in listOfPostTag and to update the post
when I delete a post, to delete every postTag in listOfPostTag and to delete the post
However, when I try to insert a post, I have an error. And from the many tests I've done, it seems that Hibernate insert the post successfully and then tries to insert the postTags, but fails because the idPost in PostTagEntityKey is still null. I would have expected that Hibernate updated it with the id from the inserted post.
So my question is can hibernate do that in the case I described? Or do I have to do it by hand (by not using the cascade mode for insert/update)?
The explanation might be that it's impossible with composite keys, bidirectional, something else or that it's just not something hibernate is supposed to do. I'd like to know if it's possible and if it is, what did I do wrong?
If it's not possible, I wonder what is the point of inserting things in cascade if you can't even do it for a thing as common as an intermediary table.
I haven't tried to code this fake example but I believe it would have the same result as I changed almost nothing from the original. Also I skipped the part where I create the postEntity because in my case it's parsed from JSON. I used the debugger and tried different things, so I'm almost sure the problem doesn't come from here. Every field is filled, even the idTag in PostTagEntityKey. It's just the idPost in PostTagEntityKey that is null because the post hasn't been inserted yet. And hibernate doesn't update it after inserting the post. I start to believe there's no way for the cascade mode to update it and maybe it's the case.
EDIT :
So, thanks to the comment of #a.ghavidel, I realised I've never tried to set the post in posttag.
So I've changed the function setListOfPostTag in post entity like this :
public void setListOfPostTag(List<PostTagEntity> listOfPostTag)
{
if (listOfPostTag != null)
{
this.listOfPostTag.clear();
for(PostTagEntity postTag : listOfPostTag)
{
postTag.setPost(this);
this.listOfPostTag.add(postTag);
}
}
}
and the problem has changed as well. Before that modification, it was telling me that it couldn't insert postTag because idPost was null. And now it's telling me "org.hibernate.PersistentObjectException: detached entity passed to persist: com.fakeexample.TagEntity".
So I think, to retreive the primary key, the entity postTag needed the variable Post to be set. The List listOfPostTag in Post wasn't enough. So my original problem is now fixed I think.
My new problem is that hibernate seems to consider that the tag in postTag is "detached" and I'm not sure what that mean.
In my case, the tag in postTag doesn't come from a function of hibernate, it has been parsed from json so maybe that's why. However I don't need it to be persisted, in theory I just need its id to insert the postTag and there is no cascade in postTag.
I've tried replacing CascadeType.All with CascadeType.Merge cause some people said it worked for them but when I do this it just doesn't insert any postTag when I insert a post. However it seems to work very well when I update a post.
I think I'm very close to the solution. I'm going to try a few things and I will edit this post if I find the answer.
EDIT 2 :
So, I've tried a few things and made some progress. The object is detached because it hasn't been created by hibernate. There is no problems during a merge but it can't be persisted.
A solution might be to do everything by hand in the create function...
But the proper solution would be to use the function getReference() from entityManager. It doesn't generate any unwanted select or update, it just create a proxy object and only require the id in parameter.
However the entityManager is not accessible in spring I think, but we can use the function getOne() from a repository which is mapped to the getReference() method. Basically, if I understood correctly, the function getOne() is supposed to be using lazy loading, so the object isn't loaded as long as we don't need it to be loaded.
I tried to use this function and indeed my code is now working correctly.
But the problem is : the function getOne() is deprecated.
The function has been replaced by getById() but I'm really not sure it use lazy loading too because I'm already using this function a lot and not to create proxy object at all. Also, I know the attribute "fetch = FetchType.LAZY" cant be put in #OneToMany, so, if I didn't put it in my code I suppose I'm not using lazy loading and it will do a lot of unwanted select. Also I don't think I should be using lazy loading all the time neither, I heard it can be troublesome by sometime generating one select for each entity of a collection instead of a single select with lazy loading...
So I still need to make some research to know how to do it with non derprecated function.
EDIT 3 :
Okay so no, the function I was using was findById and not getById. So getById is probably the solution to my problem. I'm gona check the doc to confirm and test it out.
FINAL EDIT :
Well it's working for the insert but I have now a problem during the update. Basically it tells me the posttag already exists in the DB. Probably because I replace the listOfPostTag from the findById with a list I created myself by parsing it. The solution is probably to edit the objects in this list. Now that I understand how the things work in hibernate I need to review the entirety of my code to apply these principles.
In the end, it seems that hibernate is not very friendly restful apis and we have to process every object so hibernate can recognize them.
To summerize, my problems were :
first : consistency. I didn't set the post in postTag object.
Second : attach and detach objects. I didn't used getById function to create an Object recognized by hibernate for the Taf Object.
Third : updating. When I updated a post, I didn't update the objects in listOfPostTag, I just replaced it with another list, with only objects not recognized by hibernate. I should have updated the list Object by Object I guess.
You should use this method in PostEntity when you are creating one
private void addPostTag(PostTagEntity postTag){
postTag.setPost(this);
this.listOfPostTag.add(postTag);
}
I think this will fix your problem
In our spring boot application, I am trying to save an aggregate, that consists of a root entity (ParentEntity) and a Set of child entities (ChildEntity).
The intention is, that all operations are done through the aggreate. So there is no need for a repository for ChildEntity, as the ParentEntity is supposed to manage all save or update operations.
This is how the Entities look like:
#Entity
#Table(name = "tab_parent", schema = "test")
public class ParentEntity implements Serializable {
#Id
#Column(name = "parent_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer parentId;
#Column(name = "description")
private String description;
#Column(name = "created_datetime", updatable = false, nullable = false)
#ColumnTransformer(write = "COALESCE(?,CURRENT_TIMESTAMP)")
private OffsetDateTime created;
#Column(name = "last_modified_datetime", nullable = false)
#ColumnTransformer(write = "COALESCE(CURRENT_TIMESTAMP,?)")
private OffsetDateTime modified;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "ParentEntity")
private Set<ChildEntity> children;
// constructor and other getters and setters
public void setChildren(final Set<ChildEntity> children) {
this.children = new HashSet<>(children.size());
for (final ChildEntity child : children) {
this.addChild(child);
}
}
public ParentEntity addChild(final ChildEntity child) {
this.children.add(child);
child.setParent(this);
return this;
}
public ParentEntity removeChild(final ChildEntity child) {
this.children.add(child);
child.setParent(null);
return this;
}
}
#Entity
#DynamicUpdate
#Table(name = "tab_child", schema = "test")
public class ChildEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "child_id")
private Integer childId;
#Column(name = "language_id")
private String languageId;
#Column(name = "text")
private String text;
#Column(name = "created_datetime", updatable = false, nullable = false)
#ColumnTransformer(write = "COALESCE(?,CURRENT_TIMESTAMP)")
public OffsetDateTime created;
#Column(name = "last_modified_datetime", nullable = false)
#ColumnTransformer(write = "COALESCE(CURRENT_TIMESTAMP,?)")
public OffsetDateTime modified;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "parent_id", updatable = false)
private ParentEntity parent;
// constructor and other getters and setters
public ParentEntity getParent() {
return this.parent;
}
public void setParent(final ParentEntity parent) {
this.parent = parent;
}
}
This is the store method to save or update the entities:
public Integer merge(final ParentDomainObject parentDomainObject) {
final ParentEntity parentEntity =
this.mapper.toParentEntity(parentDomainObject);
final ParentEntity result = this.entityManager.merge(parentEntity);
this.entityManager.flush();
return result.getParentId();
}
And this is the store method to retrieve the aggregate by id:
public Optional<ParentDomainObject> findById(final Integer id) {
return this.repo.findById(id).map(this.mapper::toParentDomainObject);
}
As you can see our architecture strictly separates the store from the service layer. So the service only knows about domain objects and does not depend on Hibernate Entites at all.
When updating either the child or the parent, firstly the parent is loaded. In the service layer, the domain object is updated (fields are set, or a child is added/removed).
Then the merge method (see code snippet) of the store is called with the updated domain object.
This works, but not completely as we want to. Currently every update leads to the parent and EVERY chhild entity being saved, even if all field remained the same. We added the #DynamicUpdate annotaton. Now we saw, that the "modified" field is the problem.
We use a #ColumnTransformer to have the database set the date. Now even if you call the services update method without changing anything, Hibernate generates a update query for EVERY object, which updates only the modified field.
The worst thing about that is, as every object is saved, every modified date changed as well to the current date. But we need information about exactly which object really changed and when.
Is there any way to tell hibernate, that this column should not be taken into account when deciding what to update. However of course, if a field changed, the update operation should indeed update the modified field.
UPDATE:
My second approach after #Christian Beikov mentioned the use of #org.hibernate.annotations.Generated( GenerationTime.ALWAYS )
is the following:
Instead of #Generated (which uses #ValueGenerationType( generatedBy = GeneratedValueGeneration.class )),
I created my own annotations, which use custom AnnotationValueGeneration implementations:
#ValueGenerationType(generatedBy = CreatedTimestampGeneration.class)
#Retention(RetentionPolicy.RUNTIME)
public #interface InDbCreatedTimestamp {
}
public class CreatedTimestampGeneration
implements AnnotationValueGeneration<InDbCreatedTimestamp> {
#Override
public void initialize(final InDbCreatedTimestamp annotation, final Class<?> propertyType) {
}
#Override
public GenerationTiming getGenerationTiming() {
return GenerationTiming.INSERT;
}
#Override
public ValueGenerator<?> getValueGenerator() {
return null;
}
#Override
public boolean referenceColumnInSql() {
return true;
}
#Override
public String getDatabaseGeneratedReferencedColumnValue() {
return "current_timestamp";
}
}
#ValueGenerationType(generatedBy = ModifiedTimestampGeneration.class)
#Retention(RetentionPolicy.RUNTIME)
public #interface InDbModifiedTimestamp {
}
public class ModifiedTimestampGeneration
implements AnnotationValueGeneration<InDbModifiedTimestamp> {
#Override
public void initialize(final InDbModifiedTimestamp annotation, final Class<?> propertyType) {
}
#Override
public GenerationTiming getGenerationTiming() {
return GenerationTiming.ALWAYS;
}
#Override
public ValueGenerator<?> getValueGenerator() {
return null;
}
#Override
public boolean referenceColumnInSql() {
return true;
}
#Override
public String getDatabaseGeneratedReferencedColumnValue() {
return "current_timestamp";
}
}
I use these annotations in my entities instead of the #ColumnTransformer annotations now.
This works flawlessly when I insert a new ChildEntity via addChild(), as now not all timestamps of all entities of the aggregate are updated anymore. Only the timestamps of the new child are set now.
In other words, the InDbCreatedTimestamp works as it should.
Sadly, the InDbModifiedTimestamp does not. Because of GenerationTiming.ALWAYS, I expected the timestamp to be generated on db level, everytime an INSERT OR UPDATE is issued. If I change a field of a ChildEntity and then save the aggregate, an update statement is generated only for this one database row, as expected. However, the last_modified_datetime column is not updated, which is surprising.
It seems that this is unfortunately still an open bug. This issue describes my problem precisely: Link
Can someone provide a solution how to get this db function executed on update as well (without using db triggers)
You could try to use #org.hibernate.annotations.Generated( GenerationTime.ALWAYS ) on these fields and use a database trigger or default expression to create the value. This way, Hibernate will never write the field, but read it after insert/update.
Overall this has a few downsides though (need the trigger, need a select after insert/update), so I 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/domain model for your use case could look like the following with Blaze-Persistence Entity-Views:
#EntityView(ParentEntity.class)
#UpdatableEntityView
public interface ParentDomainObject {
#IdMapping
Integer getParentId();
OffsetDateTime getModified();
void setModified(OffsetDateTime modified);
String getDescription();
void setDescription(String description);
Set<ChildDomainObject> getChildren();
#PreUpdate
default preUpdate() {
setModified(OffsetDateTime.now());
}
#EntityView(ChildEntity.class)
#UpdatableEntityView
interface ChildDomainObject {
#IdMapping
Integer getChildId();
String getName();
}
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
ParentDomainObject a = entityViewManager.find(entityManager, ParentDomainObject.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
Page<ParentDomainObject> findAll(Pageable pageable);
The best part is, it will only fetch the state that is actually necessary! It also supports writing/mapping back to the persistence model in an efficient manner. Since it does dirty tracking for you, it will only flush changes if the object is actually dirty.
public Integer merge(final ParentDomainObject parentDomainObject) {
this.entityViewManager.save(this.entityManager, parentDomainObject);
this.entityManager.flush();
return parentDomainObject.getParentId();
}
When I pass data by POST request to my TodoItem model, only the columns specified by #column get filled in, but the #JoinColumn column is null even if I use the column name in the JSON I'm sending over. My GET request API work just fine however, so I omitted them from controller code.
TodoItem.java
#Entity
#Table(name = "todo_item")
public class TodoItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "todo")
private String todo;
#Column(name = "completed")
private boolean completed;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
public TodoItem() {
}
public TodoItem(String todo, boolean completed) {
this.todo = todo;
this.completed = completed;
}
// setters and getters
}
My constructor doesn't mention user_id, don't think it needs it though, but I may be wrong.
TodoController.java
#RestController
#RequestMapping("/api")
public class TodoController {
#Autowired
private UserRepository userRepository;
#Autowired
private TodoRepository todoRepository;
#PostMapping("/addItem")
public TodoItem addTodoItem(#RequestBody TodoItem todoItem) {
return this.todoRepository.save(todoItem);
}
}
I send POST to http://localhost:8080/api/addItem
Request:
{
"todo": "finish portfolio",
"completed": false,
"user_id": 1
}
However in my MySQL workbench, todo and completed get populated properly but user_id says null
In spring data (using hibernate or JPA), when saving entity which has reference to another entity . you must first fetch the referenced object first by id and then set it using setter in persistence entity. after that you can save and get (FK column) to be saved.
for example you first must use user repository and call
User user = userRepository.findById(userId);
and then
todoItem.setUser(user);
after that you can save item and FK column will get populated.
I think this the way to save reference entity. you can not relay on int id only.
also your request body JSON must be like this :
{
"todo": "finish portfolio",
"completed": false,
"user": {
"user_id":1
}
}
also it best practice to define and use DTO object instead of entity itself.
I'm trying to use JPA (with Hibernate) to save 2 entities. Spring data is providing the interface but I don't think it matters here.
I have a main entity called 'Model'. This model has many 'Parameter' entities linked. I'm writing a method to save a model and its parameters.
This is the method:
private void cascadeSave(Model model) {
modelRepository.save(model);
for (ParameterValue value : model.getParameterValues()) {
parameterValueRepository.save(value);
}
}
This is the problem:
When I load a Model that already existed before, add some new parameters to it and then call this method to save both of them something strange happens:
Before the first save (modelRepository.save) this is what the model's data looks like when debugging:
The model has 2 parameters, with filled in values (name and model are filled).
Now, after saving the model the first save in my method, this happens. Note that the object reference is a different one so Hibernate must have done something magical and recreated the values instead of leaving them alone:
For some reason hibernate cleared all the attributes of the parameters in the set.
Now when the saving of the new parameters happens in the following code it fails because of not null constraints etc.
My question: Why does hibernate clear all of the fields?
Here are the relevant mappings:
ParameterValue
#Entity
#Table(name = "tbl_parameter_value")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "PARAMETER_TYPE")
public abstract class ParameterValue extends AbstractBaseObject {
#Column(nullable = false)
#NotBlank
private String name;
private String stringValue;
private Double doubleValue;
private Integer intValue;
private Boolean booleanValue;
#Enumerated(EnumType.STRING)
private ModelType modelParameterType;
#Column(precision = 7, scale = 6)
private BigDecimal bigDecimalValue;
#Lob
private byte[] blobValue;
ParameterValue() {
}
ParameterValue(String name) {
this.name = name;
}
ModelParameterValue
#Entity
#DiscriminatorValue(value = "MODEL")
public class ModelParameterValue extends ParameterValue {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "model_id", foreignKey = #ForeignKey(name = "FK_VALUE_MODEL"))
private Model model;
ModelParameterValue() {
super();
}
ModelParameterValue(String name) {
super(name);
}
Model
#Entity
#Table(name = "tbl_model")
public class Model extends AbstractBaseObject implements Auditable {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "model")
private Set<ModelParameterValue> parameterValues = new HashSet<>();
EDIT
I was able to reproduce this with a minimal example.
If you replace everything spring data does this is what happened under the hood (em is a JPA EntityManager):
public Model simpleTest() {
Model model = new Model("My Test Model");
em.persist(model);
model.addParameter(new Parameter("Param 1"));
em.merge(model);
for (Parameter child : model.getParameters()) {
em.persist(child);
}
return model;
}
When the merge is executed, all of the attributes of the parameters are set to null. They are actually just replaced with completely new parameters.
I guess you are using Spring Data Jpa as your modelRepository. This indicates following consequences.
Spring Repository Save
S save(S entity)
Saves a given entity. Use the returned
instance for further operations as the save operation might have
changed the entity instance completely.
So it is normal behaviour which you had encountered.
Code should be changed to :
model = modelRepository.save(model);
for (ParameterValue value : model.getParameterValues()) {
parameterValueRepository.save(value);
}
EDIT:
I think that your saving function is broken in sense, that you do it backwards. Either you can use CascadeType on your relation or you have to save children first.
Cascade
Cascade works like that "If you save Parent, save Children, if you update Parent, update Children ..."
So we can put cascade on your relation like that :
#Entity
#Table(name = "tbl_model")
public class Model extends AbstractBaseObject implements Auditable {
#OneToMany(fetch = FetchType.LAZY, mappedBy = "model", cascade = CascadeType.ALL)
private Set<ModelParameterValue> parameterValues = new HashSet<>();
and then only save like this
private void cascadeSave(Model model) {
modelRepository.save(model);
//ParamValues will be saved/updated automaticlly if your model has changed
}
Bottom-Up save
Second option is just to save params first and then model with them.
private void cascadeSave(Model model) {
model.setParameterValues(
model.getParameterValues().stream()
.map(param -> parameterValueRepository.save(param))
.collect(Collectors.toSet())
);
modelRepository.save(model);
}
I haven't checked second code in my compiler but the idea is to first save children (ParamValues), put it into Model and then save Model : )
I'm using Spring Data's annotations to add auditing data to my entities when they are saved or updated. When I create the entity the createdBy, createdDate, lastModifiedBy and lastModifiedDate get set on the object returned by repository.save().
ResourceEntity(id=ebbe1f3d-3359-4295-8c83-63eab21c4753, createdDate=2018-09-07T21:11:25.797, lastModifiedDate=2018-09-07T21:11:25.797, createdBy=5855070b-866f-4bc4-a18f-26b54f896a4b, lastModifiedBy=5855070b-866f-4bc4-a18f-26b54f896a4b)
Unfortunately, when I call repository.save() to update an existing entity the object returned does not have the createdBy and createdDate set.
ResourceEntity(id=ebbe1f3d-3359-4295-8c83-63eab21c4753, createdDate=null, lastModifiedDate=2018-09-07T21:12:01.953, createdBy=null, lastModifiedBy=5855070b-866f-4bc4-a18f-26b54f896a4b)
All the fields are set correctly in the database and a call to repository.findOne() outside of my service class returns an object with all the fields set correctly.
ResourceEntity(id=ebbe1f3d-3359-4295-8c83-63eab21c4753, createdDate=2018-09-07T21:11:25.797, lastModifiedDate=2018-09-07T21:12:01.953, createdBy=5855070b-866f-4bc4-a18f-26b54f896a4b, lastModifiedBy=5855070b-866f-4bc4-a18f-26b54f896a4b)
But if I call repository.findOne() in the service right after calling repository.save() to update the entity I also get an object back with createdBy and createdDate set to null.
Here is my entity:
#Entity(name = "resource")
#EntityListeners(AuditingEntityListener.class)
#Table(name = "resource")
#Data
#EqualsAndHashCode(of = "id")
#Builder
#AllArgsConstructor
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ResourceEntity {
#Id
#org.hibernate.annotations.Type(type = "org.hibernate.type.PostgresUUIDType")
private UUID id;
#CreatedDate
#Column(nullable = false, updatable = false)
private LocalDateTime createdDate;
#LastModifiedDate
private LocalDateTime lastModifiedDate;
#CreatedBy
#Column(nullable = false, updatable = false)
#org.hibernate.annotations.Type(type = "org.hibernate.type.PostgresUUIDType")
private UUID createdBy;
#LastModifiedBy
#org.hibernate.annotations.Type(type = "org.hibernate.type.PostgresUUIDType")
private UUID lastModifiedBy;
}
Here is my service:
#Component
public class ResourceService {
#Autowired
private ResourceRepository resourceRepository;
public ResourceEntity createResource(ResourceEntity resourceEntity) {
return saveResource(resourceEntity);
}
public ResourceEntity updateResource(ResourceEntity resourceEntity) {
return saveResource(resourceEntity);
}
public ResourceEntity getResource(UUID resourceId) {
return resourceRepository.findOne(resourceId);
}
private ResourceEntity saveResource(ResourceEntity resourceEntity) {
ResourceEntity savedResourceEntity = resourceRepository.save(resourceEntity);
return savedResourceEntity;
}
}
Here is my test:
def "Test update"() {
given:
UUID id = aRandom.uuid()
Resource resource = aRandom.resource().id(id).build()
Resource savedResource = resourceClient.createResource(resource)
when:
Resource updatedResource = aRandom.resource().id(id).build()
updatedResource = resourceClient.updateResource(updatedResource)
then:
Resource result = resourceClient.getResource(id)
assert result.id == updatedResource.id
assert result.createdBy == updatedResource.createdBy
assert result.creationDate == updatedResource.creationDate
assert result.lastModifiedBy == updatedResource.lastModifiedBy
assert result.lastModifiedDate == updatedResource.lastModifiedDate
}
Years after the original question and it's still an issue.
While not a perfect solution, I ended up fetching (via findById()) the existing entity and manually setting the #CreatedBy and #CreatedDate fields on the new entity before performing the update. It's both surprising and frustrating that JPA's auditing framework doesn't automatically handle this or provide a better way to accomplish it.
I tried before like this when i need to add audit info.
I have a DataConfig class like this.
#Configuration
#EnableJpaAuditing
public class DataConfig {
#Bean
public AuditorAware<UUID> auditorProvider() {
return new YourSecurityAuditAware();
}
#Bean
public DateTimeProvider dateTimeProvider() {
return () -> Optional.of(Instant.from(ZonedDateTime.now()));
}
}
Now you need AuditorAware class to get audit info.
So this class will be like this ;
public class XPorterSecurityAuditAware implements AuditorAware<UUID> {
#Override
public Optional<UUID> getCurrentAuditor() {
//you can change UUID format as well
return Optional.of(UUID.randomUUID());
}
}
Hope this will help you.