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 }
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 }
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() to Update an Instance We can use the same save() method to update an existing entry in our database. Suppose we saved a MerchandiseEntity instance with a specific title: MerchandiseEntity pants = new MerchandiseEntity( "Pair of Pants", 34.99); pants = repo. save(pants);
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
So if the field is null in the entity to save , it will overwrite its value to null in the existing row.
CrudRepository
has only save
but it acts as update
as well.
save
on entity with empty id
it will do a save
.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With