简体   繁体   中英

Hibernate cascade delete does not work

There are two entities: parent and child one.



    @Entity
    @Table(name = "university_group")
    public class Group {
        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        private long id;
        private String name;

        @OneToMany(mappedBy = "group", fetch = FetchType.LAZY, cascade = CascadeType.ALL, 
orphanRemoval = true) private Set<Student> students = new HashSet<>(); // getters, setters, constructor, equals+hashcode ... } @Entity @Table(name = "student") public class Student { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private long id; private String name; private String password; private String email; @ManyToOne(optional = false) private Group group; // getters, setters, constructor, equals+hashcode ... }

After removing group by em.remove(group) an exception is thrown:

javax.persistence.PersistenceException:
  org.hibernate.exception.ConstraintViolationException ... 
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper: ERROR:
    UPDATE or DELETE in table "university_group" breaks foreign key constraint "fk_20su8ubuwt33je1a3ygal7wd6" of table "student"

It seems like hibernate is not deleting students before the group by means of Persistence Provider although it should. Of course, I am able to enable DB cascading, but I would better solve the problem. Any ideas?

Configured the EntityManager by Spring configs



    @Configuration
    @EnableTransactionManagement
    @PropertySource({"classpath:db.properties"})
    public class PersistenceContext {

        private static final String BASE_MODEL_SCAN_PACKAGE = "com.chiefhelpsystem.model";

        @Value("${db.driverClassName}")
        private String dbClassName;
        @Value("${db.url}")
        private String dbUrl;
        @Value("${db.username}")
        private String dbUserName;
        @Value("${db.password}")
        private String dbPassword;

        @Bean
        DataSource dataSource() {
            BasicDataSource ds = new BasicDataSource();
            ds.setMaxIdle(20);
            ds.setMinIdle(0);
            ds.setMaxActive(20);

            ds.setDriverClassName(dbClassName);
            ds.setUrl(dbUrl);
            ds.setUsername(dbUserName);
            ds.setPassword(dbPassword);

            return ds;
        }

        @Bean
        PlatformTransactionManager transactionManager() {
            return new JpaTransactionManager();
        }

        @Bean(destroyMethod = "destroy")
        LocalContainerEntityManagerFactoryBean emf() {
            LocalContainerEntityManagerFactoryBean emFactory =
                    new LocalContainerEntityManagerFactoryBean();

            HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
            jpaVendorAdapter.setDatabase(Database.POSTGRESQL);
            jpaVendorAdapter.setGenerateDdl(true);
            jpaVendorAdapter.setShowSql(true);
            emFactory.setDataSource(dataSource());
            emFactory.setPackagesToScan(BASE_MODEL_SCAN_PACKAGE);
            emFactory.setJpaVendorAdapter(jpaVendorAdapter);
            emFactory.setJpaProperties(jpaProps());
            emFactory.setPersistenceProvider(new HibernatePersistenceProvider());
            return emFactory;
        }

        private Properties jpaProps() {
            Properties properties = new Properties();
            properties.setProperty("format_sql", "true");
            return properties;
        }

    }

Hibernate 4.3.11, Spring 4.3.2

The problem was in the incorrect hachcode() method realization. As soon as I deleted it from sources, the "un-managed deleting" problem has appeared in hibernate TRACE logs and it should be further fixed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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