CRUDRepository 中的 Update 或 saveorUpdate
我知道之前已经回答了一个类似的问题,但我的问题是在界面中有 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的对象. save可以接受单个实体或您的实体类型的Iterable.
CrudRepository 中的 - When you do
saveon entity with emptyidit will do asave. - When you do
saveon entity with existingidit will do anupdatethat means that after you usedfindByIdfor example and changed something in your object, you can callsaveon this object and it will actually do anupdatebecause afterfindByIdyou get an object with populatedidthat exist in your DB. saveinCrudRepositorycan accept a single entity orIterableof your entity type.
相关文章