有两个实体:父母和子女。
@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 ...
}
按em.remove(group)
删除组后,抛出异常:
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"
似乎hibernate不会通过持久性提供程序删除组中的学生,尽管它应该。当然,我能够启用DB级联,但我最好能解决这个问题。 有任何想法吗?
通过Spring配置配置EntityManager
@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
答案 0 :(得分:0)
问题在于错误的hachcode()方法实现。一旦我从源中删除它,hibernate TRACE日志中就出现了“未管理的删除”问题,应该进一步修复。