Taverna Joe
Taverna Joe

Reputation: 31

How can I update field in MySQL database using hibernate

So, I have Company and Employee entity in my program. Employee is working for Company and in Employee table there is company_id (foreign key) where I keep track where certain Employee is working, for which Company. Now, what if I want to update that field, how can I change Company Employee is working for?

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer employeeId;
    @NotNull
    private String name;
    private int authority=2;
    @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
    @JoinColumn(name = "company_id", insertable = false, updatable = true)
    private Company company;
//getters and setters


@Entity
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer companyId;
    @NotNull
    private String name;
    private final int authority = 1;
//getters and setters

I wanted to update company_id in employee class using field int companyId that will refer to that column, however it didn't work. In EmployeeServiceImplementation.Class if I want to update that column (which means the Employee is not working for Company, or Employee changed Company) i have to call Company class, and that is not the way I want to change info in Employee table. Is there any suggestion how to update that field? Here is my query in EmployeeRepository interface:

@Query("update Employee e set e.company_id=:company_id where e.employee_id=:employee_id")
void updateEmployeeCompany (@Param ("employee_id") Integer employeeId, @Param("company_id") Integer companyId);

Employee table in MySQL database

Upvotes: 0

Views: 594

Answers (1)

Vielen Danke
Vielen Danke

Reputation: 187

Try to use one extra annotation with parameter like in code below:

@Modifying(clearAutomatically=true)

The EntityManager doesn't flush any change automatically by default.

Upvotes: 1

Related Questions