简体   繁体   中英

Spring JPA : Saving an entity Object in database

I have an entity CandidateTransaction and CandidateTransactionRepository extending CrudRepository

@Repository
public interface CandidateTransactionRepository extends CrudRepository<CandidateTransaction,Long>{
  //find methods 


}

    @Entity
    @Table(name = "ONB_CANDIDATE_TRANS")
    public class CandidateTransaction implements Serializable {

        private static final long serialVersionUID = 3615632069112078119L;

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer ID;
//other columns

I am using save method of CrudRepository to save object of the mentioned entity. When there is no row present for the entity, it is quite straight forward that it will create an auto generated key and insert it into ID column with no interventions from java end.

And Since CrudRepository's save() method checks if the entity is new or not and if it is new it saves the data else it calls merge method to update the same row.

Ideally it should handle such case but in my case I have to specifically check whether the row with particular value exists or not, if yes then set the updated values in the existing object and then save it.

Is there any way to sort this out.

if (candidateTransactionRepository.existsByCandidateIdAndTransactionType(candidateId, transactionType))
                candidate = candidateTransactionRepository.findByCandidateIdAndTransactionType(candidateId,transactionType);

            candidate = prepareTransactionProgressObjectToSave(candidateId, transactionType, transactionStatus);

            savedInstance = candidateTransactionRepository.save(candidate);

Also What if I have to save Collection of the same entity.

Ideally it should handle such case but in my case I have to specifically check whether the row with particular value exists or not, if yes then set the updated values in the existing object and then save it.

The primary key (property "ID") is unique in your table. If an entity has no set primary key ( ID is null ) when save()ing, then CrudRepository will think the entity was not saved before and create a new row in the database.

Your technique with the lookup before the save is quite common. You usually look up entities by their other properties/columns with finder methods ( CrudRepository.findByPROPERTYNAME(...) ). Entities returned by finder methods will have an ID that is non- null .

Also What if I have to save Collection of the same entity.

CrudRepository.saveAll() is your best choice, because a collection is an Iterable as the method demands as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM