Skip to content

Commit d0a6a0e

Browse files
bdraganzhendrikse
authored andcommitted
BAEL-446: Deleting objects with Hibernate. (eugenp#879)
1 parent 50bc4fb commit d0a6a0e

7 files changed

Lines changed: 354 additions & 2 deletions

File tree

‎spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public PersistenceJPAConfigL2Cache() {
4040
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
4141
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
4242
em.setDataSource(dataSource());
43-
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
43+
em.setPackagesToScan(getPackagesToScan());
4444

4545
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
4646
em.setJpaVendorAdapter(vendorAdapter);
@@ -49,6 +49,10 @@ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
4949
return em;
5050
}
5151

52+
protected String[] getPackagesToScan() {
53+
return new String[] { "org.baeldung.persistence.model" };
54+
}
55+
5256
@Bean
5357
public DataSource dataSource() {
5458
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
@@ -78,6 +82,7 @@ final Properties additionalProperties() {
7882
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
7983
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
8084
hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
85+
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
8186
return hibernateProperties;
8287
}
8388

‎spring-jpa/src/main/resources/persistence-h2.properties‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ jdbc.user=sa
66

77
# hibernate.X
88
hibernate.dialect=org.hibernate.dialect.H2Dialect
9-
hibernate.show_sql=false
9+
hibernate.show_sql=true
1010
hibernate.hbm2ddl.auto=create-drop
1111
hibernate.cache.use_second_level_cache=true
1212
hibernate.cache.use_query_cache=true
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package org.baeldung.persistence.deletion.config;
2+
3+
import org.baeldung.config.PersistenceJPAConfigL2Cache;
4+
5+
import java.util.Properties;
6+
7+
public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache {
8+
9+
public PersistenceJPAConfigDeletion() {
10+
super();
11+
}
12+
13+
@Override
14+
protected String[] getPackagesToScan() {
15+
return new String[] { "org.baeldung.persistence.deletion.model" };
16+
}
17+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package org.baeldung.persistence.deletion.model;
2+
3+
import javax.persistence.*;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
@Entity
8+
@Table(name = "BAR")
9+
public class Bar {
10+
11+
@Id
12+
@GeneratedValue(strategy = GenerationType.AUTO)
13+
private long id;
14+
15+
@Column(nullable = false)
16+
private String name;
17+
18+
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
19+
List<Baz> bazList = new ArrayList<>();
20+
21+
public Bar() {
22+
super();
23+
}
24+
25+
public Bar(final String name) {
26+
super();
27+
this.name = name;
28+
}
29+
30+
public long getId() {
31+
return id;
32+
}
33+
34+
public void setId(final long id) {
35+
this.id = id;
36+
}
37+
38+
public String getName() {
39+
return name;
40+
}
41+
42+
public void setName(final String name) {
43+
this.name = name;
44+
}
45+
46+
public List<Baz> getBazList() {
47+
return bazList;
48+
}
49+
50+
public void setBazList(final List<Baz> bazList) {
51+
this.bazList = bazList;
52+
}
53+
54+
@Override
55+
public String toString() {
56+
final StringBuilder builder = new StringBuilder();
57+
builder.append("Bar [name=").append(name).append("]");
58+
return builder.toString();
59+
}
60+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package org.baeldung.persistence.deletion.model;
2+
3+
import javax.persistence.*;
4+
import java.util.List;
5+
6+
@Entity
7+
@Table(name = "BAZ")
8+
public class Baz {
9+
10+
@Id
11+
@GeneratedValue(strategy = GenerationType.AUTO)
12+
private long id;
13+
14+
@Column(nullable = false)
15+
private String name;
16+
17+
public Baz() {
18+
super();
19+
}
20+
21+
public Baz(final String name) {
22+
super();
23+
this.name = name;
24+
}
25+
26+
public long getId() {
27+
return id;
28+
}
29+
30+
public void setId(final long id) {
31+
this.id = id;
32+
}
33+
34+
public String getName() {
35+
return name;
36+
}
37+
38+
public void setName(final String name) {
39+
this.name = name;
40+
}
41+
42+
@Override
43+
public String toString() {
44+
final StringBuilder builder = new StringBuilder();
45+
builder.append("Bar [name=").append(name).append("]");
46+
return builder.toString();
47+
}
48+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package org.baeldung.persistence.deletion.model;
2+
3+
import org.hibernate.annotations.Where;
4+
5+
import javax.persistence.*;
6+
7+
@Entity
8+
@Table(name = "FOO")
9+
@Where(clause = "DELETED = 0")
10+
public class Foo {
11+
12+
public Foo() {
13+
super();
14+
}
15+
16+
public Foo(final String name) {
17+
super();
18+
this.name = name;
19+
}
20+
21+
@Id
22+
@GeneratedValue(strategy = GenerationType.AUTO)
23+
@Column(name = "ID")
24+
private long id;
25+
26+
@Column(name = "NAME")
27+
private String name;
28+
29+
@Column(name = "DELETED")
30+
private Integer deleted = 0;
31+
32+
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
33+
@JoinColumn(name = "BAR_ID")
34+
private Bar bar;
35+
36+
public Bar getBar() {
37+
return bar;
38+
}
39+
40+
public void setBar(final Bar bar) {
41+
this.bar = bar;
42+
}
43+
44+
public long getId() {
45+
return id;
46+
}
47+
48+
public void setId(final int id) {
49+
this.id = id;
50+
}
51+
52+
public String getName() {
53+
return name;
54+
}
55+
56+
public void setName(final String name) {
57+
this.name = name;
58+
}
59+
60+
public void setDeleted() {
61+
this.deleted = 1;
62+
}
63+
}
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
package org.baeldung.persistence.service;
2+
3+
import org.baeldung.persistence.deletion.config.PersistenceJPAConfigDeletion;
4+
import org.baeldung.persistence.deletion.model.Bar;
5+
import org.baeldung.persistence.deletion.model.Baz;
6+
import org.baeldung.persistence.deletion.model.Foo;
7+
import org.junit.Before;
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
import org.springframework.beans.factory.annotation.Autowired;
11+
import org.springframework.test.context.ContextConfiguration;
12+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13+
import org.springframework.test.context.support.AnnotationConfigContextLoader;
14+
import org.springframework.transaction.PlatformTransactionManager;
15+
import org.springframework.transaction.annotation.Transactional;
16+
17+
import javax.persistence.EntityManager;
18+
import javax.persistence.PersistenceContext;
19+
20+
import static org.hamcrest.Matchers.notNullValue;
21+
import static org.hamcrest.Matchers.nullValue;
22+
import static org.junit.Assert.assertThat;
23+
24+
@RunWith(SpringJUnit4ClassRunner.class)
25+
@ContextConfiguration(classes = { PersistenceJPAConfigDeletion.class }, loader = AnnotationConfigContextLoader.class)
26+
public class DeletionIntegrationTest {
27+
28+
@PersistenceContext
29+
private EntityManager entityManager;
30+
@Autowired
31+
private PlatformTransactionManager platformTransactionManager;
32+
33+
@Before
34+
public final void before() {
35+
entityManager.getEntityManagerFactory().getCache().evictAll();
36+
}
37+
38+
@Test
39+
@Transactional
40+
public final void givenEntityIsRemoved_thenItIsNotInDB() {
41+
Foo foo = new Foo("foo");
42+
entityManager.persist(foo);
43+
flushAndClear();
44+
45+
foo = entityManager.find(Foo.class, foo.getId());
46+
assertThat(foo, notNullValue());
47+
48+
entityManager.remove(foo);
49+
flushAndClear();
50+
51+
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
52+
}
53+
54+
@Test
55+
@Transactional
56+
public final void givenEntityIsRemovedAndReferencedByAnotherEntity_thenItIsNotRemoved() {
57+
Bar bar = new Bar("bar");
58+
Foo foo = new Foo("foo");
59+
foo.setBar(bar);
60+
entityManager.persist(foo);
61+
flushAndClear();
62+
63+
foo = entityManager.find(Foo.class, foo.getId());
64+
bar = entityManager.find(Bar.class, bar.getId());
65+
entityManager.remove(bar);
66+
flushAndClear();
67+
68+
bar = entityManager.find(Bar.class, bar.getId());
69+
assertThat(bar, notNullValue());
70+
71+
foo = entityManager.find(Foo.class, foo.getId());
72+
foo.setBar(null);
73+
entityManager.remove(bar);
74+
flushAndClear();
75+
76+
assertThat(entityManager.find(Bar.class, bar.getId()), nullValue());
77+
}
78+
79+
@Test
80+
@Transactional
81+
public final void givenEntityIsRemoved_thenRemovalIsCascaded() {
82+
Bar bar = new Bar("bar");
83+
Foo foo = new Foo("foo");
84+
foo.setBar(bar);
85+
entityManager.persist(foo);
86+
flushAndClear();
87+
88+
foo = entityManager.find(Foo.class, foo.getId());
89+
entityManager.remove(foo);
90+
flushAndClear();
91+
92+
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
93+
assertThat(entityManager.find(Bar.class, bar.getId()), nullValue());
94+
}
95+
96+
@Test
97+
@Transactional
98+
public final void givenEntityIsDisassociated_thenOrphanRemovalIsApplied() {
99+
Bar bar = new Bar("bar");
100+
Baz baz = new Baz("baz");
101+
bar.getBazList().add(baz);
102+
entityManager.persist(bar);
103+
flushAndClear();
104+
105+
bar = entityManager.find(Bar.class, bar.getId());
106+
baz = bar.getBazList().get(0);
107+
bar.getBazList().remove(baz);
108+
flushAndClear();
109+
110+
assertThat(entityManager.find(Baz.class, baz.getId()), nullValue());
111+
}
112+
113+
@Test
114+
@Transactional
115+
public final void givenEntityIsDeletedWithJpaBulkDeleteStatement_thenItIsNotInDB() {
116+
Foo foo = new Foo("foo");
117+
entityManager.persist(foo);
118+
flushAndClear();
119+
120+
entityManager.createQuery("delete from Foo where id = :id")
121+
.setParameter("id", foo.getId())
122+
.executeUpdate();
123+
124+
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
125+
}
126+
127+
@Test
128+
@Transactional
129+
public final void givenEntityIsDeletedWithNativeQuery_thenItIsNotInDB() {
130+
Foo foo = new Foo("foo");
131+
entityManager.persist(foo);
132+
flushAndClear();
133+
134+
entityManager.createNativeQuery("delete from FOO where ID = :id")
135+
.setParameter("id", foo.getId())
136+
.executeUpdate();
137+
138+
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
139+
}
140+
141+
@Test
142+
@Transactional
143+
public final void givenEntityIsSoftDeleted_thenItIsNotReturnedFromQueries() {
144+
Foo foo = new Foo("foo");
145+
entityManager.persist(foo);
146+
flushAndClear();
147+
148+
foo = entityManager.find(Foo.class, foo.getId());
149+
foo.setDeleted();
150+
flushAndClear();
151+
152+
assertThat(entityManager.find(Foo.class, foo.getId()), nullValue());
153+
}
154+
155+
private void flushAndClear() {
156+
entityManager.flush();
157+
entityManager.clear();
158+
}
159+
}

0 commit comments

Comments
 (0)