Spring JPA:在数据库中保存一个实体对象

Spring JPA : Saving an entity Object in database

我有一个实体 CandidateTransactionCandidateTransactionRepository 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

我正在使用 CrudRepository 的保存方法来保存上述实体的对象。 当实体没有行时,它会创建一个自动生成的键并将其插入到 ID 列中,而无需来自 java end.

的干预。

并且由于 CrudRepository 的 save() 方法检查实体是否是新的,如果是新的,它会保存数据,否则它会调用合并方法来更新同一行。

理想情况下,它应该处理这种情况,但在我的情况下,我必须专门检查具有特定值的行是否存在,如果存在,则在现有对象中设置更新的值,然后保存它。

有什么办法解决这个问题吗

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

            candidate = prepareTransactionProgressObjectToSave(candidateId, transactionType, transactionStatus);

            savedInstance = candidateTransactionRepository.save(candidate);

此外,如果我必须保存同一​​实体的集合怎么办。

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.

主键 (属性 "ID") 在您的 table 中是唯一的。如果一个实体在保存时没有设置主键(IDnull),那么 CrudRepository 会认为该实体之前没有保存并在数据库中创建一个新行。

您在保存前进行查找的技术很常见。您通常使用查找器方法 (CrudRepository.findByPROPERTYNAME(...)) 按其他 properties/columns 查找实体。 finder 方法返回的实体将具有非 null.

ID

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

CrudRepository.saveAll() 是您的最佳选择,因为集合是 Iterable,因为方法需要作为参数。