如何使用JPA在Java Spring应用程序中删除用户时自动更新设备状态?

xtupzzrd  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(57)

我正在使用Spring开发一个Java程序,该程序使用JPA与数据库通信。在我的应用程序中,我有多个类,但我遇到了User和Equipment类的问题。每个用户都拥有设备,每个设备都有一个状态。(已分配,未分配,或正在维修中)。我的目标是在删除用户时自动将关联设备的状态从已分配更新为未分配。如何实现?请参阅下面的代码片段以供参考:

package se.what.inventorymanager;

import jakarta.persistence.*;
import java.util.Date;

@Entity
@Table(name="equipment")
public class Equipment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name="equipment_name")
    private String name;

    @Column(name="purchase_date")
    private Date purchaseDate;

    @Column(name="purchase_price")
    private double purchasePrice;

    @Enumerated(EnumType.STRING)
    private EquipmentState state;

    @Enumerated(EnumType.STRING)
    private EquipmentType type;

    @OneToOne(mappedBy = "equipment")
    private EquipmentSupport equipmentSupport;
    @ManyToOne
    @JoinColumn(name = "purchased_by", referencedColumnName = "id")
    private User user;

    public Equipment() {}

    public Equipment(String name, Date purchaseDate, double purchasePrice, EquipmentState state,
                     EquipmentType type, User user) {
        this.name = name;
        this.purchaseDate = purchaseDate;
        this.purchasePrice = purchasePrice;
        this.state = state;
        this.type = type;
        this.user = user;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getPurchaseDate() {
        return purchaseDate;
    }

    public void setPurchaseDate(Date purchaseDate) {
        this.purchaseDate = purchaseDate;
    }

    public double getPurchasePrice() {
        return purchasePrice;
    }

    public void setPurchasePrice(double purchasePrice) {
        this.purchasePrice = purchasePrice;
    }

    public EquipmentState getState() {
        return state;
    }

    public void setState(EquipmentState state) {
        this.state = state;
    }

    public EquipmentType getType() {
        return type;
    }

    public void setType(EquipmentType type) {
        this.type = type;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Equipment{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", purchaseDate=" + purchaseDate +
                ", purchasePrice=" + purchasePrice +
                ", state=" + state +
                ", type=" + type +
                ", equipmentSupport=" + equipmentSupport +
                ", user=" + user.getName() +
                '}';
    }

    @PreUpdate
    @PrePersist
    public void updateEquipmentState() {
        if (user == null) {
            state = EquipmentState.unassigned;
        }
    }
}
package se.what.inventorymanager;
import jakarta.persistence.*;
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;
    private String department;
    private String email;
    private String telephone;
    private String username;
    private String password;

    @Column(name = "role")
    @Enumerated(EnumType.STRING)
    private RoleType role;

    public User(String name, String department, String email, String telephone, String username, String password, RoleType role) {
        this.name = name;
        this.department = department;
        this.email = email;
        this.telephone = telephone;
        this.username = username;
        this.password = password;
        this.role = role;
    }

    public User() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public RoleType getRole() {
        return role;
    }

    public void setRole(RoleType role) {
        this.role = role;
    }

    @Override
    public String toString() {
        return "\nUser id: " + id + " Name: " + name  + " Department: " + department + " Email: " + email + " Telephone: "
                + telephone + " Username: " + username + " Password: " + password + " Role: " + role;
    }
}

;

字符串

u3r8eeie

u3r8eeie1#

在Spring应用程序中,当您需要在删除实体时自动执行某些操作时,可以使用JPA的生命周期回调方法或使用实体侦听器。例如,当删除User实体时,您希望将与该用户关联的所有Equipment的状态更新为unassigned。
在User实体中创建一个@PreRemove回调方法,该方法将在实体被删除之前调用。在这个@PreRemove方法中,您可以编写逻辑来更新所有相关Equipment的状态。请记住,您需要注入一个自定义服务或存储库,以便您可以执行数据库操作。这通常是通过使用Spring的@Autowired,但不建议直接在实体类中执行注入,因为实体应该保持轻量级状态,不应该处理业务逻辑。2更好的方法是在服务级别处理此逻辑。
下面是一个简单的示例,展示了如何在服务级别执行此操作:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private EquipmentRepository equipmentRepository;

    @Transactional
    public void deleteUser(int userId) {
        // Find all devices owned by the user
        List<Equipment> equipments = equipmentRepository.findByUserId(userId);

        // Update the status of these devices to unassigned
        equipments.forEach(equipment -> {
            equipment.setState(EquipmentState.UNASSIGNED);
            equipment.setUser(null); // Optional, if you want to unassociate with the user
            equipmentRepository.save(equipment);
        });

        // Delete User
        userRepository.deleteById(userId);
    }
}

字符串

相关问题