简体   繁体   中英

how to update a table in spring data JPA using where clause

I want to update particular record in a table and i am using primary key(empId) and one more column(empSalary) to identify the particular column. As we know primary key(empId) is enough to identify the record. But in my case i want update the record if that employee salary is 1000. is there any option to update a record using entity not query?. I am using spring data JPA

Example:

public class Employee {

    @Id
    @Column
    private int empId;

    @Column
    private String name;

    @Column
    private float salary;

    @Column
    private String state;

    // getters, setters
}

I want to update the whole table if empId and salary match with table.

In an EmployeeRepository create the following method;

findOneByEmpIdAndSalary(Integer empId, Float salary);

Then you can pass the salary = 1000.0 or can create a default method within the same repository with that value hard coded;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {

    Optional<Employee> findOneByEmpIdAndSalary(Integer empId, Float salary);

    default Optional<Employee> findOneByEmpIdAndSalaryEqualTo1000(Integer empId) {
        return findOneByEmpIdAndSalary(empId, 1000.0);
    }
}

I used findOne since you are already selecting with the primary key plus an extra condition, so you will either get one or none, thus using Optional<T> as the result, to control either possibility in a better way.

After fetching this entity within a @Transactional state, just update the resulting entity. If Optional is not empty, then the ending of the transaction will commit that update to the DB, else nothing.

@Transactional
public String updateWithCondition(Integer empId) {
    employeeRepository.findOneByEmpIdAndSalaryEqualTo1000(empId)
            .ifPresent(employee -> employee.setState("desired Update"));
}

Like the above snippet as an example.

You can use @Modifying along with @Query annotation to include where clause in your query. This way you save a round trip to DB by fetching the entity first and then updating it.

This article from Baeldung explains it neatly. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM