【问题标题】:How can I update field in MySQL database using hibernate如何使用休眠更新 MySQL 数据库中的字段
【发布时间】:2025-06-01 08:30:01
【问题描述】:

所以,我的程序中有公司和员工实体。员工为公司工作,在员工表中有 company_id(外键),我在其中跟踪某个员工在哪里工作,为哪个公司工作。现在,如果我想更新该字段,我该如何更改 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

我想使用将引用该列的字段 int companyId 更新员工类中的 company_id,但它不起作用。在 EmployeeServiceImplementation.Class 中,如果我想更新该列(这意味着 Employee 不为公司工作,或者员工更改了公司),我必须调用 Company 类,这不是我想要更改 Employee 表中信息的方式。 有什么建议如何更新该字段? 这是我在 EmployeeRepository 接口中的查询:

@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);

【问题讨论】:

    标签: java mysql spring-boot hibernate spring-data-jpa


    【解决方案1】:

    尝试在下面的代码中使用一个带有参数的额外注释:

    @Modifying(clearAutomatically=true)
    

    EntityManager 默认不会自动刷新任何更改。

    【讨论】:

    • 在哪里添加?到实体?
    • 要查询方法,过查询注解
    • 谢谢。有效。我还在 updateEmployeeAuthority 方法中添加了@Transactional。但是,现在我还有其他问题,那就是代码中的其他地方。我正在处理 Postman 中的 DataIntegrityViolationException 和 Eclipse 中的 SQLIntegrityConstraintViolationException。现在需要解决这个问题。
    最近更新 更多