有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java软删除工具Hibernate

我有一个插件类。删除实体时,我希望将记录保留在数据库中,但将其隐藏在查询中

在以下实现中,我遇到了一个异常:

@Entity
@SQLDelete(sql = "UPDATE addon SET active IS FALSE WHERE id = ?")
@Where(clause = "active = false")
public class Addon {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @ManyToOne
    private Category category;
    private String name;
    private int amount;
    private int minimalAmount;
    @OneToMany
    private Set<HandOver> handOvers;
    private boolean active;

    public Addon(){
         this.setAmount(0);
         this.active = true;
    }

    @PreRemove
    public void deleteAddon() {
        this.setActive(false);
    }
}

删除方法:

private void deleteAddon(){
        Addon toBeDeleted = chooseAddon();

        Session s = MainController.getSession();
        try {
            s.beginTransaction();
            s.remove(toBeDeleted);
            s.getTransaction().commit();
        } catch (Exception e) {
            s.getTransaction().rollback();
            System.err.println("An error occured. Addon has not been deleted: " + e);
        }
    }

例外情况:

Led 17, 2019 3:45:44 ODP. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Led 17, 2019 3:45:44 ODP. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IS FALSE WHERE id = 3' at line 1
Led 17, 2019 3:45:44 ODP. org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Led 17, 2019 3:45:44 ODP. org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: could not execute statement]

An error occured. Addon has not been deleted: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement

查询(在hibernate配置中为“show_sql”=true)是:

Hibernate: delete from Addon_HandOver where Addon_id=?
Hibernate: UPDATE addon SET active IS FALSE WHERE id = ?

我正在使用Hibernate 5和MySQL 8


共 (1) 个答案

  1. # 1 楼答案

    试着这样写:@Where(clause=“active='false'”),或者如果active=true表示可访问记录,则为true;)