top of page
Search
ranulphgitter139mr

Hibernate save or update return id: デタッチドエンティティをアタッチする方法



The save() method is used make a TRANSIENT entity PERSISTENT by associating it with either an org.hibernate.Session. Before persisting the entity, it assigns a generated identifier to the ID field.


The save() method returns the generated identifier so it has to immediately execute the SQL INSERT statement (it does not matter if we are inside or outside of a transaction) because identifiers are generated by the database during the INSERT query execution only.




Hibernate save or update return id



Note that if we call save() outside the transaction then associated entities may not be inserted immediately because save() has to return the generated identifier only for the main entity. This can cause data inconsistency if we forget to flush the changes or some application error happens.


Hibernate Session is the interface between java application and hibernate framework. Today we will look into Session important methods for saving and updating data in tables - save, saveOrUpdate, persist, update and merge.


Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed. Hibernate saveOrUpdate adds the entity object to persistent context and track any further changes. Any further changes are saved at the time of committing transaction, like persist.


Notice that without transaction, only Employee gets saved and address information is lost. With transaction employee object is tracked for any changes, thats why in last call there is no update in Employee table even though the value was changed in between, final value remains same.


I am inserting my data into Oracle database using hibernate session.save() method but auto increment is provided by database side. In my bean class @Id showing me error how I can solve this problem???


The save method triggers a SaveOrUpdateEvent which is handled by the DefaultSaveOrUpdateEventListener Hibernate event listener. Therefore, the save method is equivalent to the update and saveOrUpdate methods.


The update method triggers a SaveOrUpdateEvent which is handled by the DefaultSaveOrUpdateEventListener Hibernate event listener. Therefore, the update method is equivalent to the save and saveOrUpdate methods.


The saveOrUpdate method triggers a SaveOrUpdateEvent which is handled by the DefaultSaveOrUpdateEventListener Hibernate event listener. Therefore, the update method is equivalent to the save and saveOrUpdate methods.


To persist an entity, you should use the JPA persist method. To copy the detached entity state, merge should be preferred. The update method is useful for batch processing tasks only. The save and saveOrUpdate are just aliases to update and you should not probably use them at all.


JDBC and relational databases do not require primary or unique keys for a table. While working with JDBC, we communicate with a database using its own language - native SQL queries. To obtain a dataset, developers run a select statement that returns corresponding tuples. To save or update data, we need to compose another insert or update statement. At this application-to-database level of communications, there is no direct link between objects in the application and records stored in the database. Usually, this mapping is managed manually as a part of the business logic.


JPA takes a different approach. It introduces entities - Java objects that are rigidly tied to their records in the database. Therefore, the JPA specification requires developers to define a field or a set of fields to establish the one-to-one association between an entity instance and a particular DB record. This way, developers can fetch JPA entities from the database, work with them and save them later without calling any insert or update statements. This is one of the key concepts allowing developers to focus mainly on the business logic, while most of the boilerplate operations are being handled by a JPA implementation itself, and IDs are a vital part of this process.


It is important to note that the returned instance is not the same as the instance passed to the save method. When a write operation is performed Micronaut Data will use a copy-constructor approach to populate the database identifier and return a new instance from the save method.


With Micronaut Data Azure Cosmos, you can use save method of the CrudRepository or manually implement an update method. You can define explicit update methods for updates in your repository. For example:


We are migrating application from oracle to Mariadb. Using container transactions and Spring transaction management. I am getting error for code where the one record is saved and updated in same transaction(Service bean method). Same code is working fine for Oracle database.


org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1


@Override @Target( ElementType.METHOD, ElementType.TYPE ) @Retention(RetentionPolicy.RUNTIME) @Transactional(readOnly = false, rollbackFor = Exception.class) public DealVO addNew(DealVO vo) Deal deal = new Deal(); vo.setEndDate(new Date()); deal = convertDealVOToDeal(vo, deal); dealDao.save(deal); Some other logic based on creation date setting some other deal properties dealDao.save(deal); original logger is removed as it contains sensitive deal info vo.setCreationDate(deal.getCreationDate()); vo.setCreationDateUserTz(deal.getCreationDateUserTz()); vo.setId(deal.getId()); return vo;


The POST method is simple. All you have to do is to call studentRepository.save(student). Note that we are using @RequestBody to map the student details from request to bean. We are also returning a ResponseEntity with a header containing the URL of the created resource.


With no cascade, you need to save/update the entity and the child entity everytime you make an action. Also, the parent and child entities will be readded to the managed context after a save/update (see #1).


void saveOrUpdate(object)->object must be attached to a hibernate session (including all sub objects within the object), and once save/update is done, the object reflects the updated changes (e.g. primary key if saving a new object)


Object merge(object)-> object does not have to be attached to a hibernate session. Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session.


This means you can create a copy of object from Service layer and just pass the object to your DAO. Hibernate takes care of MERGING the data to appropriate hibernate session attached object and saves the data.


The only downside of using MERGE is that the object passed does not reflect the changed information. So, if you need to use the updated object, you must get it from the returned object, not the parameter object.


You might be surprised to see that the post was saved with an ID of 3! The reason for this is because the defaulthibernate_sequence will be shared between multiple entity types and consequently, any entities that are persisted willincrement the sequence for any other entity types as well.


Transactional persistent instances (ie. objects loaded, saved, created or queried by the ISession) may be manipulated by the application and any changes to persistent state will be persisted when the ISession is flushed (discussed later in this chapter). So the most straightforward way to update the state of an object is to Load() it, and then manipulate it directly, while the ISession is open:


NHibernate users have requested a general purpose method that either saves a transient instance by generating a new identifier or update the persistent state associated with its current identifier. The SaveOrUpdate() method now implements this functionality.


The last case can be avoided by using Merge(Object o). This method copies the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. The method returns the persistent instance. If the given instance is unsaved or does not exist in the database, NHibernate will save it and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session. In most applications with detached objects, you need both methods, SaveOrUpdate() and Merge().


Mapping an association (many-to-one, one-to-one or collection) with cascade="all" marks the association as a parent/child style relationship where save/update/deletion of the parent results in save/update/deletion of the child(ren). Furthermore, a mere reference to a child from a persistent parent will result in save / update of the child. The metaphor is incomplete, however. A child which becomes unreferenced by its parent is not automatically deleted, except in the cases of and associations that have been mapped with cascade="all-delete-orphan" or cascade="delete-orphan". The precise semantics of cascading operations are as follows:


NHibernate does not fully implement "persistence by reachability", which would imply (inefficient) persistent garbage collection. However, due to popular demand, NHibernate does support the notion of entities becoming persistent when referenced by another persistent object. Associations marked cascade="save-update" behave in this way. If you wish to use this approach throughout your application, it's easier to specify the default-cascade attribute of the element. 2ff7e9595c


1 view0 comments

Recent Posts

See All

Comments


bottom of page