简体   繁体   English

软删除实现 Hibernate

[英]soft delete imlementation Hibernate

I have a Addon class.我有一个插件类。 When deleting its entity, I want to keep the record in the database, but hide it in queries.删除其实体时,我想将记录保留在数据库中,但将其隐藏在查询中。

With following implementation I run into an exception:通过以下实现,我遇到了一个异常:

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

The delete method:删除方法:

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

The exception:例外:

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

And the Query (with "show_sql" = true in hibernate config) is:查询(在休眠配置中使用“show_sql”=true)是:

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

I'm using Hibernate 5 and MySQL 8.我正在使用 Hibernate 5 和 MySQL 8。

尝试这样写:@Where(clause = "active='false'"),如果 active = true 表示可见记录,则为 true ;)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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