Reputation: 1256
I am trying to update only three columns of a table with 36 column using spring data jpa
. I am debating between following two approaches and did quite research but could not reach to conclusion on which one is preferred way.I am however leaning toward second approach that way I don't have to create entity class with @Column
annotation and getters/setters
.
First Approach
using spring data jpa
i will first get entity object using id, update the field and save it.
MyObject object= myRepository.getOne(id);
object.setName("updated Name);
myRepository.save(object);
Second Approach
@Repository
public interface MyRepository extends JpaRepository<MyObject , Long> {
@Query("update MyTable c set c.name= :name WHERE c.id = :id")
void updateName(@Param("id") Long id, @Param("name") String name);
}
Which one is the preferred way to solve problem like my case.
Upvotes: 0
Views: 42
Reputation: 13747
getOne(id)
gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement. While the second Approach fetches values from DB which takes more cost in my opinion.
You can Refer this for internal working.
Upvotes: 1