I have an entity Bar
:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "bar")
private Set<Foo> fooSet;
And an entity Foo
:
@ManyToOne(optional = false)
@JoinColumn(name = "bar_id")
private Bar bar;
Hibernate creates the foreign key constraint on foo.bar -> bar.id but it doesnt specify ON DELETE CASCADE
. Why not? And is there any ways to achieve it?
Alternatively I can add the ON DELETE CASCADE
manually in the DB (and disable DDL generation), is this a good practice? And also, do I have to modify my code in some way to let Hibernate know that related records are deleted automatically by the database?
Thanks.
Update - this is my JPA/Hibernate/PostgreSQL configuration:
<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/my_db" />
<property name="username" value="my_username" />
<property name="password" value="my_password" />
</bean>
</constructor-arg>
</bean>
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="jpaProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
Update 2 - clarified what I mean: the foreign key constraint is created, but I'm wondering why it doesnt specify ON DELETE CASCADE
(changed the original question accordingly)