Skip to content

Commit 5733676

Browse files
Merge pull request eugenp#481 from GuenHamza/master
BAEL-63 - Add Stored Procedures with Hibernate Tests
2 parents 3b9e4c7 + 11bc145 commit 5733676

4 files changed

Lines changed: 234 additions & 82 deletions

File tree

‎spring-hibernate4/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
99
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
1010
- [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa)
11-
11+
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
1212

1313
### Quick Start
1414

‎spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java‎

Lines changed: 85 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -11,93 +11,97 @@
1111
import javax.persistence.Id;
1212
import javax.persistence.JoinColumn;
1313
import javax.persistence.ManyToOne;
14+
import javax.persistence.NamedNativeQueries;
15+
import javax.persistence.NamedNativeQuery;
1416

1517
import org.hibernate.envers.Audited;
1618

19+
@NamedNativeQueries({
20+
@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class),
21+
@NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
1722
@Entity
1823
@Audited
1924
// @Proxy(lazy = false)
2025
public class Foo implements Serializable {
2126

22-
@Id
23-
@GeneratedValue(strategy = GenerationType.AUTO)
24-
@Column(name = "id")
25-
private long id;
26-
27-
@Column(name = "name")
28-
private String name;
29-
30-
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
31-
@JoinColumn(name = "BAR_ID")
32-
private Bar bar = new Bar();
33-
34-
public Foo() {
35-
super();
36-
}
37-
38-
public Foo(final String name) {
39-
super();
40-
this.name = name;
41-
}
42-
43-
//
44-
45-
public Bar getBar() {
46-
return bar;
47-
}
48-
49-
public void setBar(final Bar bar) {
50-
this.bar = bar;
51-
}
52-
53-
public long getId() {
54-
return id;
55-
}
56-
57-
public void setId(final long id) {
58-
this.id = id;
59-
}
60-
61-
public String getName() {
62-
return name;
63-
}
64-
65-
public void setName(final String name) {
66-
this.name = name;
67-
}
68-
69-
//
70-
71-
@Override
72-
public int hashCode() {
73-
final int prime = 31;
74-
int result = 1;
75-
result = prime * result + ((name == null) ? 0 : name.hashCode());
76-
return result;
77-
}
78-
79-
@Override
80-
public boolean equals(final Object obj) {
81-
if (this == obj)
82-
return true;
83-
if (obj == null)
84-
return false;
85-
if (getClass() != obj.getClass())
86-
return false;
87-
final Foo other = (Foo) obj;
88-
if (name == null) {
89-
if (other.name != null)
90-
return false;
91-
} else if (!name.equals(other.name))
92-
return false;
93-
return true;
94-
}
95-
96-
@Override
97-
public String toString() {
98-
final StringBuilder builder = new StringBuilder();
99-
builder.append("Foo [name=").append(name).append("]");
100-
return builder.toString();
101-
}
102-
27+
@Id
28+
@GeneratedValue(strategy = GenerationType.AUTO)
29+
@Column(name = "id")
30+
private long id;
31+
32+
@Column(name = "name")
33+
private String name;
34+
35+
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
36+
@JoinColumn(name = "BAR_ID")
37+
private Bar bar = new Bar();
38+
39+
public Foo() {
40+
super();
41+
}
42+
43+
public Foo(final String name) {
44+
super();
45+
this.name = name;
46+
}
47+
48+
//
49+
50+
public Bar getBar() {
51+
return bar;
52+
}
53+
54+
public void setBar(final Bar bar) {
55+
this.bar = bar;
56+
}
57+
58+
public long getId() {
59+
return id;
60+
}
61+
62+
public void setId(final long id) {
63+
this.id = id;
64+
}
65+
66+
public String getName() {
67+
return name;
68+
}
69+
70+
public void setName(final String name) {
71+
this.name = name;
72+
}
73+
74+
//
75+
76+
@Override
77+
public int hashCode() {
78+
final int prime = 31;
79+
int result = 1;
80+
result = prime * result + ((name == null) ? 0 : name.hashCode());
81+
return result;
82+
}
83+
84+
@Override
85+
public boolean equals(final Object obj) {
86+
if (this == obj)
87+
return true;
88+
if (obj == null)
89+
return false;
90+
if (getClass() != obj.getClass())
91+
return false;
92+
final Foo other = (Foo) obj;
93+
if (name == null) {
94+
if (other.name != null)
95+
return false;
96+
} else if (!name.equals(other.name))
97+
return false;
98+
return true;
99+
}
100+
101+
@Override
102+
public String toString() {
103+
final StringBuilder builder = new StringBuilder();
104+
builder.append("Foo [name=").append(name).append("]");
105+
return builder.toString();
106+
}
103107
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
DELIMITER //
2+
CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
3+
LANGUAGE SQL
4+
DETERMINISTIC
5+
SQL SECURITY DEFINER
6+
BEGIN
7+
SELECT * FROM foo WHERE name = fooName;
8+
END //
9+
DELIMITER ;
10+
11+
12+
DELIMITER //
13+
CREATE PROCEDURE GetAllFoos()
14+
LANGUAGE SQL
15+
DETERMINISTIC
16+
SQL SECURITY DEFINER
17+
BEGIN
18+
SELECT * FROM foo;
19+
END //
20+
DELIMITER ;
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
package com.baeldung.persistence.service;
2+
3+
import java.util.List;
4+
5+
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
6+
import static org.junit.Assert.assertEquals;
7+
8+
import org.hibernate.Query;
9+
import org.hibernate.Session;
10+
import org.hibernate.SessionFactory;
11+
import org.hibernate.exception.SQLGrammarException;
12+
import org.junit.After;
13+
import org.junit.Assume;
14+
import org.junit.Before;
15+
import org.junit.Test;
16+
import org.junit.runner.RunWith;
17+
import org.springframework.beans.factory.annotation.Autowired;
18+
import org.springframework.test.context.ContextConfiguration;
19+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
20+
import org.springframework.test.context.support.AnnotationConfigContextLoader;
21+
22+
import com.baeldung.persistence.model.Foo;
23+
import com.baeldung.spring.PersistenceConfig;
24+
25+
@RunWith(SpringJUnit4ClassRunner.class)
26+
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
27+
public class FooStoredProceduresIntegrationTest {
28+
29+
@Autowired
30+
private SessionFactory sessionFactory;
31+
32+
@Autowired
33+
private IFooService fooService;
34+
35+
private Session session;
36+
37+
@Before
38+
public final void before() {
39+
session = sessionFactory.openSession();
40+
Assume.assumeTrue(getAllFoosExists());
41+
Assume.assumeTrue(getFoosByNameExists());
42+
}
43+
44+
private boolean getFoosByNameExists() {
45+
try {
46+
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
47+
.addEntity(Foo.class);
48+
sqlQuery.list();
49+
return true;
50+
} catch (SQLGrammarException e) {
51+
System.out
52+
.println("WARNING : GetFoosByName() Procedure is may be missing ");
53+
return false;
54+
}
55+
}
56+
57+
private boolean getAllFoosExists() {
58+
try {
59+
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
60+
.addEntity(Foo.class);
61+
sqlQuery.list();
62+
return true;
63+
} catch (SQLGrammarException e) {
64+
System.out
65+
.println("WARNING : GetAllFoos() Procedure is may be missing ");
66+
return false;
67+
}
68+
}
69+
70+
@After
71+
public final void after() {
72+
session.close();
73+
}
74+
75+
@Test
76+
public final void getAllFoosUsingStoredProcedures() {
77+
78+
fooService.create(new Foo(randomAlphabetic(6)));
79+
80+
// Stored procedure getAllFoos using createSQLQuery
81+
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(
82+
Foo.class);
83+
@SuppressWarnings("unchecked")
84+
List<Foo> allFoos = sqlQuery.list();
85+
for (Foo foo : allFoos) {
86+
System.out.println("getAllFoos() SQL Query result : "
87+
+ foo.getName());
88+
}
89+
assertEquals(allFoos.size(), fooService.findAll().size());
90+
91+
// Stored procedure getAllFoos using a Named Query
92+
Query namedQuery = session.getNamedQuery("callGetAllFoos");
93+
@SuppressWarnings("unchecked")
94+
List<Foo> allFoos2 = namedQuery.list();
95+
for (Foo foo : allFoos2) {
96+
System.out.println("getAllFoos() NamedQuery result : "
97+
+ foo.getName());
98+
}
99+
assertEquals(allFoos2.size(), fooService.findAll().size());
100+
}
101+
102+
@Test
103+
public final void getFoosByNameUsingStoredProcedures() {
104+
105+
fooService.create(new Foo("NewFooName"));
106+
107+
// Stored procedure getFoosByName using createSQLQuery()
108+
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)")
109+
.addEntity(Foo.class).setParameter("fooName", "NewFooName");
110+
@SuppressWarnings("unchecked")
111+
List<Foo> allFoosByName = sqlQuery.list();
112+
for (Foo foo : allFoosByName) {
113+
System.out.println("getFoosByName() using SQL Query : found => "
114+
+ foo.toString());
115+
}
116+
117+
// Stored procedure getFoosByName using getNamedQuery()
118+
Query namedQuery = session.getNamedQuery("callGetFoosByName")
119+
.setParameter("fooName", "NewFooName");
120+
@SuppressWarnings("unchecked")
121+
List<Foo> allFoosByName2 = namedQuery.list();
122+
for (Foo foo : allFoosByName2) {
123+
System.out.println("getFoosByName() using Native Query : found => "
124+
+ foo.toString());
125+
}
126+
127+
}
128+
}

0 commit comments

Comments
 (0)