在CRUDRepository中更新或保存更新 [英] Update or saveorUpdate in CRUDRepository

查看:1147
本文介绍了在CRUDRepository中更新或保存更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以前已经回答过类似的问题,但是我的问题是在接口中有3种方法的同时实现了带有更新的保存. 我目前在我的项目中使用以下方法,并且不知道如何在其中进行saveOrUpdate. 以下是我的课程:

I know there's already a similar question answered previously, but my problem is implementing save with update while there are 3 methods in the interface. I'm currently using the following methods in my project and don't know how to make saveOrUpdate in this. The following are my classes:

   public interface CompanyRepository extends CrudRepository<Company,Long>{
   Company findByCompanyName (String companyName);
   List<Company> findAll();
   Company findById(Long id);
   }

以下是我的公司课程的一部分

The following is part of my Company Class

@Entity
public class Company extends BaseEntity{
 @NotNull
@Size(min = 2, max = 16)
private String companyName;
@Length(max = 60)
private String desc;
//TODO max: add LOGO class later for pic saving
@OneToMany
private List<MobileModel> mobileModels;

public Company()
{
  super();
  mobileModels = new ArrayList<>();
  }

//Getters n setters
 }

以下是我的baseEntity类别

The following is my baseEntity clas

@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy =  GenerationType.AUTO)
protected final Long id;

@Version
private Long version;  
//Getters n setters
}

先谢谢了. 我到处都读了5个小时,尝试了很多东西. 我只希望CompanyRepository实现所有3种方法,而无需在其他类中重写它们,但是如果我也这样做,请解释一下原因,因为我的部分代码依赖于CompanyRepository.我只想在更新中添加保存,请就我的代码进行解释.

Thanks in advance. I read everywhere and tried so many things for 5 hours. I just want CompanyRepository to implement all 3 methods without me overriding them in some other class but if I have too then explain how because part of my code is dependent on CompanyRepository. I just wish to add save with update, please explain with respect to my code.

推荐答案

CrudRepository仅具有save,但它也充当update.

CrudRepository has only save but it acts as update as well.

  • 对空的id实体执行save时,将执行save.
  • 当您对具有现有id的实体执行save时,它将执行update,这意味着例如在使用findById并更改了对象中的某些内容之后,您可以在此对象上调用save它实际上会执行update,因为在findById之后,您将获得一个包含填充的id的对象,该对象已存在于数据库中.
  • CrudRepository中的
  • save可以接受单个实体或您的实体类型的Iterable.
  • When you do save on entity with empty id it will do a save.
  • When you do save on entity with existing id it will do an update that means that after you used findById for example and changed something in your object, you can call save on this object and it will actually do an update because after findById you get an object with populated id that exist in your DB.
  • save in CrudRepository can accept a single entity or Iterable of your entity type.

这篇关于在CRUDRepository中更新或保存更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆