├── .gitignore
├── 9781484223185.jpg
├── LICENSE.txt
├── README.md
├── chapter01
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter01
│ │ ├── hibernate
│ │ └── Message.java
│ │ └── pojo
│ │ └── Message.java
│ └── test
│ ├── java
│ └── chapter01
│ │ ├── hibernate
│ │ └── PersistenceTest.java
│ │ └── jdbc
│ │ └── PersistenceTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter02
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter02
│ │ ├── hibernate
│ │ └── Message.java
│ │ └── pojo
│ │ └── Message.java
│ └── test
│ ├── java
│ └── chapter02
│ │ ├── hibernate
│ │ └── PersistenceTest.java
│ │ └── jdbc
│ │ └── PersistenceTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter03
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter03
│ │ ├── application
│ │ ├── HibernateRankingService.java
│ │ └── RankingService.java
│ │ ├── hibernate
│ │ ├── Person.java
│ │ ├── Ranking.java
│ │ └── Skill.java
│ │ └── simple
│ │ ├── Person.java
│ │ ├── Ranking.java
│ │ └── Skill.java
│ └── test
│ ├── java
│ └── chapter03
│ │ ├── application
│ │ ├── AddRankingTest.java
│ │ ├── FindAllRankingsTest.java
│ │ ├── FindAverageRankingTest.java
│ │ ├── FindBestRankingTest.java
│ │ ├── RemoveRankingTest.java
│ │ └── UpdateRankingTest.java
│ │ ├── hibernate
│ │ ├── PersonTest.java
│ │ └── RankingTest.java
│ │ └── simple
│ │ └── ModelTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter04
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter04
│ │ ├── broken
│ │ ├── Email.java
│ │ └── Message.java
│ │ ├── id
│ │ ├── GeneratedAutoIdentity.java
│ │ ├── GeneratedIdentityIdentity.java
│ │ ├── GeneratedSequenceIdentity.java
│ │ ├── GeneratedTableIdentity.java
│ │ └── NongeneratedIdentity.java
│ │ ├── mapped
│ │ ├── Email.java
│ │ └── Message.java
│ │ ├── model
│ │ └── SimpleObject.java
│ │ └── orphan
│ │ ├── Book.java
│ │ └── Library.java
│ └── test
│ ├── java
│ └── chapter04
│ │ ├── broken
│ │ └── BrokenInversionTest.java
│ │ ├── general
│ │ ├── MergeRefreshTest.java
│ │ └── PersistingEntitiesTest.java
│ │ ├── id
│ │ └── IdentityTest.java
│ │ ├── mapped
│ │ └── WorkingInversionTest.java
│ │ └── orphan
│ │ └── OrphanRemovalTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter05
├── README.txt
└── pom.xml
├── chapter06
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter06
│ │ ├── compoundpk
│ │ ├── CPKBook.java
│ │ ├── EmbeddedPKBook.java
│ │ ├── ISBN.java
│ │ └── IdClassBook.java
│ │ ├── mappedsuperclass
│ │ ├── BookSuperclass.java
│ │ └── ComputerBook.java
│ │ ├── naturalid
│ │ ├── Employee.java
│ │ └── SimpleNaturalIdEmployee.java
│ │ ├── primarykey
│ │ ├── after
│ │ │ └── Book.java
│ │ └── before
│ │ │ └── Book.java
│ │ └── twotables
│ │ └── Customer.java
│ └── test
│ ├── java
│ └── chapter06
│ │ ├── naturalid
│ │ └── NaturalIdTest.java
│ │ └── primarykey
│ │ └── BookTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter07
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter07
│ │ ├── lifecycle
│ │ ├── FailingEntity.java
│ │ ├── LifecycleThing.java
│ │ ├── UserAccount.java
│ │ └── UserAccountListener.java
│ │ ├── unvalidated
│ │ └── UnvalidatedSimplePerson.java
│ │ └── validated
│ │ ├── Coordinate.java
│ │ ├── NoQuadrantIII.java
│ │ ├── QuadrantIIIValidator.java
│ │ └── ValidatedSimplePerson.java
│ └── test
│ ├── java
│ └── chapter07
│ │ ├── lifecycle
│ │ ├── ExternalListenerTest.java
│ │ └── LifecycleTest.java
│ │ └── validator
│ │ ├── CoordinateTest.java
│ │ └── ValidatorTest.java
│ └── resources
│ ├── META-INF
│ └── persistence.xml
│ └── hibernate.cfg.xml
├── chapter08
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter08
│ │ └── model
│ │ ├── Publisher.java
│ │ ├── Subscriber.java
│ │ └── Supplier.java
│ └── test
│ ├── java
│ └── chapter08
│ │ ├── QueryTest.java
│ │ └── TransactionExample.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter09
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter09
│ │ └── model
│ │ ├── Product.java
│ │ ├── Software.java
│ │ └── Supplier.java
│ └── test
│ ├── java
│ └── chapter09
│ │ ├── DeleteHQLTest.java
│ │ ├── PaginationTest.java
│ │ └── QueryTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter10
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter10
│ │ └── model
│ │ ├── Product.java
│ │ ├── Software.java
│ │ └── Supplier.java
│ └── test
│ ├── java
│ └── chapter10
│ │ ├── QueryTest.java
│ │ └── SupplierResult.java
│ └── resources
│ └── META-INF
│ └── persistence.xml
├── chapter11
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter11
│ │ ├── model
│ │ └── User.java
│ │ └── userrole
│ │ ├── Role1.java
│ │ └── User1.java
│ └── test
│ ├── java
│ └── chapter11
│ │ ├── FilterTests.java
│ │ └── UserRoleTests.java
│ └── resources
│ └── hibernate.cfg.xml
├── chapter12
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter12
│ │ └── Person.java
│ └── test
│ ├── java
│ └── chapter12
│ │ ├── hibernate
│ │ ├── BaseHibernateOGMTest.java
│ │ └── InfinispanTest.java
│ │ └── jpa
│ │ ├── BaseJPAOGMTest.java
│ │ ├── InfinispanTest.java
│ │ └── MongoTest.java
│ └── resources
│ ├── META-INF
│ └── persistence.xml
│ └── mongodb.xml
├── chapter13
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── chapter13
│ │ └── model
│ │ └── User.java
│ └── test
│ ├── java
│ └── chapter13
│ │ └── EnversTest.java
│ └── resources
│ └── hibernate.cfg.xml
├── contributing.md
├── pom.xml
└── util
├── pom.xml
└── src
├── main
└── java
│ └── com
│ └── autumncode
│ ├── hibernate
│ └── util
│ │ └── SessionUtil.java
│ └── jpa
│ └── util
│ └── JPASessionUtil.java
└── test
├── java
└── com
│ └── autumncode
│ ├── hibernate
│ └── util
│ │ └── SessionBuilderTest.java
│ ├── jpa
│ └── util
│ │ └── JPASessionUtilTest.java
│ └── util
│ └── model
│ └── Thing.java
└── resources
├── META-INF
└── persistence.xml
└── hibernate.cfg.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | #Editor detritus
2 | *~
3 |
4 | #Database files
5 | *.mv.db
6 | *.db
7 |
8 | # Maven
9 | target/
10 |
11 | # IDEA
12 | *.ipr
13 | *.iml
14 | .idea/
--------------------------------------------------------------------------------
/9781484223185.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/beg-hibernate-4ed/5c1745d3be3d9749c2099e983cdc717d1d845c58/9781484223185.jpg
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/beg-hibernate-4ed/5c1745d3be3d9749c2099e983cdc717d1d845c58/LICENSE.txt
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Apress Source Code
2 |
3 | This repository accompanies [*Beginning Hibernate*](http://www.apress.com/9781484223185) by Joseph Ottinger, Jeff Linwood, and Dave Minter (Apress, 2016).
4 |
5 | 
6 |
7 | Download the files as a zip using the green button, or clone the repository to your machine using Git.
8 |
9 | ## Releases
10 |
11 | Release v1.0 corresponds to the code in the published book, without corrections or updates.
12 |
13 | ## Contributions
14 |
15 | See the file Contributing.md for more information on how you can contribute to this repository.
16 |
17 | ## Issues
18 |
19 | * Note that the book relies on Hibernate 5.2.X, while Hibernate itself is on the 5.3 branch now.
20 | This is largely due to chapter08 and cache configuration, which Hibernate 5.3 has changed. The source
21 | code will update when cache configuration stabilizes and becomes more transparent.
--------------------------------------------------------------------------------
/chapter01/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | com.autumncode.books.hibernate
7 | hibernate-parent
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | chapter01
13 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/chapter01/hibernate/Message.java:
--------------------------------------------------------------------------------
1 | package chapter01.hibernate;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Message {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column(nullable = false)
11 | String text;
12 |
13 | public Message(String text) {
14 | setText(text);
15 | }
16 |
17 | public Message() {
18 | }
19 |
20 | public Long getId() {
21 | return id;
22 | }
23 |
24 | public void setId(Long id) {
25 | this.id = id;
26 | }
27 |
28 | public String getText() {
29 | return text;
30 | }
31 |
32 | public void setText(String text) {
33 | this.text = text;
34 | }
35 |
36 | @Override
37 | public String toString() {
38 | return "Message{" +
39 | "id=" + getId() +
40 | ", text='" + getText() + '\'' +
41 | '}';
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/chapter01/src/main/java/chapter01/pojo/Message.java:
--------------------------------------------------------------------------------
1 | package chapter01.pojo;
2 |
3 | public class Message {
4 | String text;
5 |
6 | public Message() {
7 | }
8 |
9 | public Message(String text) {
10 | setText(text);
11 | }
12 |
13 | public String getText() {
14 | return text;
15 | }
16 |
17 | public void setText(String text) {
18 | this.text = text;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/chapter01/src/test/java/chapter01/hibernate/PersistenceTest.java:
--------------------------------------------------------------------------------
1 | package chapter01.hibernate;
2 |
3 | import org.hibernate.Session;
4 | import org.hibernate.SessionFactory;
5 | import org.hibernate.Transaction;
6 | import org.hibernate.boot.MetadataSources;
7 | import org.hibernate.boot.registry.StandardServiceRegistry;
8 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9 | import org.testng.annotations.BeforeClass;
10 | import org.testng.annotations.Test;
11 |
12 | import java.util.List;
13 |
14 | import static org.testng.Assert.assertEquals;
15 |
16 | public class PersistenceTest {
17 | private SessionFactory factory = null;
18 |
19 | @BeforeClass
20 | public void setup() {
21 | StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
22 | .configure()
23 | .build();
24 | factory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
25 | }
26 |
27 | @Test
28 | public void saveMessage() {
29 | Message message = new Message("Hello, world");
30 | try (Session session = factory.openSession()) {
31 | Transaction tx = session.beginTransaction();
32 | session.persist(message);
33 | tx.commit();
34 | }
35 | }
36 |
37 | @Test(dependsOnMethods = "saveMessage")
38 | public void readMessage() {
39 | try (Session session = factory.openSession()) {
40 | List list = session.createQuery("from Message", Message.class).list();
41 |
42 | assertEquals(list.size(), 1);
43 | for (Message m : list) {
44 | System.out.println(m);
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/chapter01/src/test/java/chapter01/jdbc/PersistenceTest.java:
--------------------------------------------------------------------------------
1 | package chapter01.jdbc;
2 |
3 | import chapter01.hibernate.Message;
4 | import org.testng.annotations.BeforeSuite;
5 | import org.testng.annotations.Test;
6 |
7 | import java.sql.*;
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | import static org.testng.Assert.assertEquals;
12 |
13 | public class PersistenceTest {
14 | @BeforeSuite
15 | public void setup() {
16 | //Class.forName("org.h2.Driver");
17 |
18 | try (Connection connection = DriverManager.getConnection("jdbc:h2:./db1", "sa", "")) {
19 | // clear out the old data, if any, so we know the state of the DB
20 | try (PreparedStatement ps = connection.prepareStatement("DROP TABLE messages IF EXISTS")) {
21 | ps.execute();
22 | }
23 | // create the table...
24 | try (PreparedStatement ps = connection.prepareStatement(
25 | "CREATE TABLE messages ("
26 | + "id BIGINT GENERATED BY DEFAULT AS IDENTITY "
27 | + "PRIMARY KEY, "
28 | + "text VARCHAR(256))"
29 | )) {
30 | ps.execute();
31 | }
32 | } catch (SQLException e) {
33 | e.printStackTrace();
34 | throw new RuntimeException(e);
35 | }
36 | }
37 |
38 | @Test
39 | public void saveMessage() {
40 | try (Connection connection = DriverManager.getConnection("jdbc:h2:./db1", "sa", "")) {
41 |
42 | connection.setAutoCommit(false);
43 | try (PreparedStatement ps = connection.prepareStatement("INSERT INTO messages(text) VALUES (?)")) {
44 |
45 | ps.setString(1, "Hello, World");
46 | ps.execute();
47 | }
48 | connection.commit();
49 | // eagerly free resources
50 | } catch (SQLException e) {
51 | e.printStackTrace();
52 | throw new RuntimeException(e);
53 | }
54 | }
55 |
56 | @Test(dependsOnMethods = "saveMessage")
57 | public void readMessage() {
58 | final String SELECT = "SELECT id, text FROM messages";
59 | final String JDBCURL = "jdbc:h2:./db1";
60 | List list = new ArrayList<>();
61 | try (Connection connection = DriverManager.getConnection(JDBCURL, "sa", "")) {
62 | try (PreparedStatement ps = connection.prepareStatement(SELECT)) {
63 | try (ResultSet rs = ps.executeQuery()) {
64 | while (rs.next()) {
65 | Message message = new Message();
66 | message.setId(rs.getLong(1));
67 | message.setText(rs.getString(2));
68 | list.add(message);
69 | }
70 |
71 | assertEquals(list.size(), 1);
72 | for (Message m : list) {
73 | System.out.println(m);
74 | }
75 | }
76 | }
77 | } catch (SQLException e) {
78 | e.printStackTrace();
79 | throw new RuntimeException(e);
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/chapter01/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db1
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 |
14 | true
15 |
16 | create-drop
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/chapter02/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | chapter02
13 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/chapter02/hibernate/Message.java:
--------------------------------------------------------------------------------
1 | package chapter02.hibernate;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Message {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column(nullable = false)
11 | String text;
12 |
13 | public Message(String text) {
14 | setText(text);
15 | }
16 |
17 | public Message() {
18 | }
19 |
20 | public Long getId() {
21 | return id;
22 | }
23 |
24 | public void setId(Long id) {
25 | this.id = id;
26 | }
27 |
28 | public String getText() {
29 | return text;
30 | }
31 |
32 | public void setText(String text) {
33 | this.text = text;
34 | }
35 |
36 | @Override
37 | public String toString() {
38 | return "Message{" +
39 | "id=" + getId() +
40 | ", text='" + getText() + '\'' +
41 | '}';
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/chapter02/src/main/java/chapter02/pojo/Message.java:
--------------------------------------------------------------------------------
1 | package chapter02.pojo;
2 |
3 | public class Message {
4 | String text;
5 |
6 | public Message() {
7 | }
8 |
9 | public String getText() {
10 | return text;
11 | }
12 |
13 | public void setText(String text) {
14 | this.text = text;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/chapter02/src/test/java/chapter02/hibernate/PersistenceTest.java:
--------------------------------------------------------------------------------
1 | package chapter02.hibernate;
2 |
3 | import org.hibernate.Session;
4 | import org.hibernate.SessionFactory;
5 | import org.hibernate.Transaction;
6 | import org.hibernate.boot.MetadataSources;
7 | import org.hibernate.boot.registry.StandardServiceRegistry;
8 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9 | import org.testng.annotations.BeforeSuite;
10 | import org.testng.annotations.Test;
11 |
12 | import java.util.List;
13 |
14 | import static org.testng.Assert.assertEquals;
15 |
16 | public class PersistenceTest {
17 | SessionFactory factory;
18 |
19 | @BeforeSuite
20 | public void setup() {
21 | StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
22 | .configure()
23 | .build();
24 | factory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
25 | }
26 |
27 | @Test
28 | public void saveMessage() {
29 | Message message = new Message("Hello, world");
30 | try (Session session = factory.openSession()) {
31 | Transaction tx = session.beginTransaction();
32 | session.persist(message);
33 | tx.commit();
34 | }
35 | }
36 |
37 | @Test(dependsOnMethods = "saveMessage")
38 | public void readMessage() {
39 | try (Session session = factory.openSession()) {
40 | List list = session.createQuery("from Message", Message.class).list();
41 |
42 | assertEquals(list.size(), 1);
43 | for (Message m : list) {
44 | System.out.println(m);
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/chapter02/src/test/java/chapter02/jdbc/PersistenceTest.java:
--------------------------------------------------------------------------------
1 | package chapter02.jdbc;
2 |
3 | import chapter02.hibernate.Message;
4 | import org.testng.annotations.BeforeSuite;
5 | import org.testng.annotations.Test;
6 |
7 | import java.sql.*;
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | import static org.testng.Assert.assertEquals;
12 |
13 | public class PersistenceTest {
14 | @BeforeSuite
15 | public void setup() {
16 | try (Connection connection = DriverManager.getConnection("jdbc:h2:./db2", "sa", "")) {
17 | // clear out the old data, if any, so we know the state of the DB
18 | try (PreparedStatement ps = connection.prepareStatement("DROP TABLE messages IF EXISTS")) {
19 | ps.execute();
20 | }
21 | try (PreparedStatement ps = connection.prepareStatement(
22 | "CREATE TABLE messages ("
23 | + "id BIGINT GENERATED BY DEFAULT AS IDENTITY "
24 | + "PRIMARY KEY, "
25 | + "text VARCHAR(256))"
26 | )) {
27 | ps.execute();
28 | }
29 | } catch (SQLException e) {
30 | e.printStackTrace();
31 | throw new RuntimeException(e);
32 | }
33 | }
34 |
35 | @Test
36 | public void saveMessage() {
37 | try (Connection connection = DriverManager.getConnection("jdbc:h2:./db2", "sa", "")) {
38 | connection.setAutoCommit(false);
39 | try (PreparedStatement ps = connection.prepareStatement("INSERT INTO messages(text) VALUES (?)")) {
40 | ps.setString(1, "Hello, World");
41 | ps.execute();
42 | connection.commit();
43 | }
44 | } catch (SQLException e) {
45 | e.printStackTrace();
46 | throw new RuntimeException(e);
47 | }
48 | }
49 |
50 | @Test(dependsOnMethods = "saveMessage")
51 | public void readMessage() {
52 | List list = new ArrayList<>();
53 | try (Connection connection = DriverManager.getConnection("jdbc:h2:./db2", "sa", "")) {
54 | try (PreparedStatement ps = connection.prepareStatement("SELECT id, text FROM messages")) {
55 | try (ResultSet rs = ps.executeQuery()) {
56 | while (rs.next()) {
57 | Message message = new Message();
58 | message.setId(rs.getLong(1));
59 | message.setText(rs.getString(2));
60 | list.add(message);
61 | }
62 | assertEquals(list.size(), 1);
63 | for (Message m : list) {
64 | System.out.println(m);
65 | }
66 | }
67 | }
68 | } catch (SQLException e) {
69 | e.printStackTrace();
70 | throw new RuntimeException(e);
71 | }
72 | }
73 | }
--------------------------------------------------------------------------------
/chapter02/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db2
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 |
14 | true
15 |
16 | create-drop
17 |
18 |
19 |
--------------------------------------------------------------------------------
/chapter03/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter03
12 |
13 |
14 |
15 | org.hibernate
16 | hibernate-c3p0
17 |
18 |
19 | com.mchange
20 | c3p0
21 |
22 |
23 | com.autumncode.books.hibernate
24 | util
25 |
26 |
27 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/application/RankingService.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import chapter03.hibernate.Person;
4 |
5 | import java.util.Map;
6 |
7 | public interface RankingService {
8 | int getRankingFor(String subject, String skill);
9 |
10 | void addRanking(String subject, String observer, String skill, int ranking);
11 |
12 | void updateRanking(String subject, String observer, String skill, int ranking);
13 |
14 | void removeRanking(String subject, String observer, String skill);
15 |
16 | Map findRankingsFor(String subject);
17 |
18 | Person findBestPersonFor(String skill);
19 | }
20 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/hibernate/Person.java:
--------------------------------------------------------------------------------
1 | package chapter03.hibernate;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Person {
7 | @Column(unique = true)
8 | String name;
9 | @Id
10 | @GeneratedValue(strategy = GenerationType.AUTO)
11 | private Long id;
12 |
13 | public Person() {
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(Long id) {
21 | this.id = id;
22 | }
23 |
24 | public String getName() {
25 | return name;
26 | }
27 |
28 | public void setName(String name) {
29 | this.name = name;
30 | }
31 |
32 | @Override
33 | public String toString() {
34 | return "Person{" +
35 | "id=" + id +
36 | ", name='" + name + '\'' +
37 | '}';
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/hibernate/Ranking.java:
--------------------------------------------------------------------------------
1 | package chapter03.hibernate;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Ranking {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @ManyToOne
11 | Person subject;
12 | @ManyToOne
13 | Person observer;
14 | @ManyToOne
15 | Skill skill;
16 | @Column
17 | Integer ranking;
18 |
19 | public Ranking() {
20 | }
21 |
22 | public Long getId() {
23 | return id;
24 | }
25 |
26 | public void setId(Long id) {
27 | this.id = id;
28 | }
29 |
30 | public Person getSubject() {
31 | return subject;
32 | }
33 |
34 | public void setSubject(Person subject) {
35 | this.subject = subject;
36 | }
37 |
38 | public Person getObserver() {
39 | return observer;
40 | }
41 |
42 | public void setObserver(Person observer) {
43 | this.observer = observer;
44 | }
45 |
46 | public Skill getSkill() {
47 | return skill;
48 | }
49 |
50 | public void setSkill(Skill skill) {
51 | this.skill = skill;
52 | }
53 |
54 | public Integer getRanking() {
55 | return ranking;
56 | }
57 |
58 | public void setRanking(Integer ranking) {
59 | this.ranking = ranking;
60 | }
61 |
62 | @Override
63 | public String toString() {
64 | return "Ranking{" +
65 | "id=" + id +
66 | ", subject=" + subject +
67 | ", observer=" + observer +
68 | ", skill=" + skill +
69 | ", ranking=" + ranking +
70 | '}';
71 | }
72 | }
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/hibernate/Skill.java:
--------------------------------------------------------------------------------
1 | package chapter03.hibernate;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Skill {
7 | @Column
8 | String name;
9 | @Id
10 | @GeneratedValue(strategy = GenerationType.AUTO)
11 | private Long id;
12 |
13 | public Skill() {
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(Long id) {
21 | this.id = id;
22 | }
23 |
24 | public String getName() {
25 | return name;
26 | }
27 |
28 | public void setName(String name) {
29 | this.name = name;
30 | }
31 |
32 | @Override
33 | public String toString() {
34 | return "Skill{" +
35 | "id=" + id +
36 | ", name='" + name + '\'' +
37 | '}';
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/simple/Person.java:
--------------------------------------------------------------------------------
1 | package chapter03.simple;
2 |
3 | public class Person {
4 | String name;
5 |
6 | public Person() {
7 | }
8 |
9 | public String getName() {
10 | return name;
11 | }
12 |
13 | public void setName(String name) {
14 | this.name = name;
15 | }
16 |
17 | @Override
18 | public String toString() {
19 | return "Person{" +
20 | "name='" + name + '\'' +
21 | '}';
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/simple/Ranking.java:
--------------------------------------------------------------------------------
1 | package chapter03.simple;
2 |
3 | public class Ranking {
4 | Person subject;
5 | Person observer;
6 | Skill skill;
7 | Integer ranking;
8 |
9 | public Ranking() {
10 | }
11 |
12 | public Person getSubject() {
13 | return subject;
14 | }
15 |
16 | public void setSubject(Person subject) {
17 | this.subject = subject;
18 | }
19 |
20 | public Person getObserver() {
21 | return observer;
22 | }
23 |
24 | public void setObserver(Person observer) {
25 | this.observer = observer;
26 | }
27 |
28 | public Skill getSkill() {
29 | return skill;
30 | }
31 |
32 | public void setSkill(Skill skill) {
33 | this.skill = skill;
34 | }
35 |
36 | public Integer getRanking() {
37 | return ranking;
38 | }
39 |
40 | public void setRanking(Integer ranking) {
41 | this.ranking = ranking;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | return "Ranking{" +
47 | "subject=" + subject +
48 | ", observer=" + observer +
49 | ", skill=" + skill +
50 | ", ranking=" + ranking +
51 | '}';
52 | }
53 | }
--------------------------------------------------------------------------------
/chapter03/src/main/java/chapter03/simple/Skill.java:
--------------------------------------------------------------------------------
1 | package chapter03.simple;
2 |
3 | public class Skill {
4 | String name;
5 |
6 | public Skill() {
7 | }
8 |
9 | public String getName() {
10 | return name;
11 | }
12 |
13 | public void setName(String name) {
14 | this.name = name;
15 | }
16 |
17 | @Override
18 | public String toString() {
19 | return "Skill{" +
20 | "name='" + name + '\'' +
21 | '}';
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/application/AddRankingTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import org.testng.annotations.Test;
4 |
5 | import static org.testng.Assert.assertEquals;
6 |
7 | public class AddRankingTest {
8 | RankingService service = new HibernateRankingService();
9 |
10 | @Test
11 | public void addRanking() {
12 | service.addRanking("J. C. Smell", "Drew Lombardo", "Mule", 8);
13 | assertEquals(service.getRankingFor("J. C. Smell", "Mule"), 8);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/application/FindAllRankingsTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import org.testng.annotations.Test;
4 |
5 | import java.util.Map;
6 |
7 | import static org.testng.Assert.assertEquals;
8 | import static org.testng.Assert.assertNotNull;
9 |
10 | public class FindAllRankingsTest {
11 | RankingService service = new HibernateRankingService();
12 |
13 | @Test
14 | public void findAllRankingsEmptySet() {
15 | assertEquals(service.getRankingFor("Nobody", "Java"), 0);
16 | assertEquals(service.getRankingFor("Nobody", "Python"), 0);
17 | Map rankings = service.findRankingsFor("Nobody");
18 |
19 | // make sure our dataset size is what we expect: empty
20 | assertEquals(rankings.size(), 0);
21 | }
22 |
23 | @Test
24 | public void findAllRankings() {
25 | assertEquals(service.getRankingFor("Somebody", "Java"), 0);
26 | assertEquals(service.getRankingFor("Somebody", "Python"), 0);
27 | service.addRanking("Somebody", "Nobody", "Java", 9);
28 | service.addRanking("Somebody", "Nobody", "Java", 7);
29 | service.addRanking("Somebody", "Nobody", "Python", 7);
30 | service.addRanking("Somebody", "Nobody", "Python", 5);
31 | Map rankings = service.findRankingsFor("Somebody");
32 |
33 | assertEquals(rankings.size(), 2);
34 | assertNotNull(rankings.get("Java"));
35 | assertEquals(rankings.get("Java"), new Integer(8));
36 | assertNotNull(rankings.get("Python"));
37 | assertEquals(rankings.get("Python"), new Integer(6));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/application/FindAverageRankingTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import org.testng.annotations.Test;
4 |
5 | import static org.testng.Assert.assertEquals;
6 |
7 | public class FindAverageRankingTest {
8 | RankingService service = new HibernateRankingService();
9 |
10 | @Test
11 | public void validateRankingAverage() {
12 | service.addRanking("A", "B", "C", 4);
13 | service.addRanking("A", "B", "C", 5);
14 | service.addRanking("A", "B", "C", 6);
15 | assertEquals(service.getRankingFor("A", "C"), 5);
16 | service.addRanking("A", "B", "C", 7);
17 | service.addRanking("A", "B", "C", 8);
18 | assertEquals(service.getRankingFor("A", "C"), 6);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/application/FindBestRankingTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import chapter03.hibernate.Person;
4 | import org.testng.annotations.Test;
5 |
6 | import static org.testng.Assert.assertEquals;
7 | import static org.testng.Assert.assertNull;
8 |
9 | public class FindBestRankingTest {
10 | RankingService service = new HibernateRankingService();
11 |
12 | @Test
13 | public void findBestForNonexistentSkill() {
14 | Person p = service.findBestPersonFor("no skill");
15 | assertNull(p);
16 | }
17 |
18 | @Test
19 | public void findBestForSkill() {
20 | service.addRanking("S1", "O1", "Sk1", 6);
21 | service.addRanking("S1", "O2", "Sk1", 8);
22 | service.addRanking("S2", "O1", "Sk1", 5);
23 | service.addRanking("S2", "O2", "Sk1", 7);
24 | service.addRanking("S3", "O1", "Sk1", 7);
25 | service.addRanking("S3", "O2", "Sk1", 9);
26 | // data that should not factor in!
27 | service.addRanking("S1", "O2", "Sk2", 2);
28 |
29 | Person p = service.findBestPersonFor("Sk1");
30 | assertEquals(p.getName(), "S3");
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/application/RemoveRankingTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import org.testng.annotations.Test;
4 |
5 | import static org.testng.Assert.assertEquals;
6 |
7 | public class RemoveRankingTest {
8 | RankingService service = new HibernateRankingService();
9 |
10 | @Test
11 | public void removeRanking() {
12 | service.addRanking("R1", "R2", "RS1", 8);
13 | assertEquals(service.getRankingFor("R1", "RS1"), 8);
14 | service.removeRanking("R1", "R2", "RS1");
15 | assertEquals(service.getRankingFor("R1", "RS1"), 0);
16 | }
17 |
18 | @Test
19 | public void removeNonexistentRanking() {
20 | service.removeRanking("R3", "R4", "RS2");
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/application/UpdateRankingTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.application;
2 |
3 | import org.testng.annotations.Test;
4 |
5 | import static org.testng.Assert.assertEquals;
6 |
7 | public class UpdateRankingTest {
8 | RankingService service = new HibernateRankingService();
9 |
10 | @Test
11 | public void updateExistingRanking() {
12 | service.addRanking("Gene Showrama", "Scottball Most", "Ceylon", 6);
13 | assertEquals(service.getRankingFor("Gene Showrama", "Ceylon"), 6);
14 | service.updateRanking("Gene Showrama", "Scottball Most", "Ceylon", 7);
15 | assertEquals(service.getRankingFor("Gene Showrama", "Ceylon"), 7);
16 | }
17 |
18 | @Test
19 | public void updateNonexistentRanking() {
20 | assertEquals(service.getRankingFor("Scottball Most", "Ceylon"), 0);
21 | service.updateRanking("Scottball Most", "Gene Showrama", "Ceylon", 7);
22 | assertEquals(service.getRankingFor("Scottball Most", "Ceylon"), 7);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/hibernate/PersonTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.hibernate;
2 |
3 | import org.hibernate.Session;
4 | import org.hibernate.SessionFactory;
5 | import org.hibernate.Transaction;
6 | import org.hibernate.boot.MetadataSources;
7 | import org.hibernate.boot.registry.StandardServiceRegistry;
8 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9 | import org.testng.annotations.BeforeClass;
10 | import org.testng.annotations.Test;
11 |
12 | public class PersonTest {
13 | SessionFactory factory;
14 |
15 | @BeforeClass
16 | public void setup() {
17 | StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
18 | .configure()
19 | .build();
20 | factory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
21 | }
22 |
23 | @Test
24 | public void testSavePerson() {
25 | try (Session session = factory.openSession()) {
26 | Transaction tx = session.beginTransaction();
27 | Person person = new Person();
28 | person.setName("J. C. Smell");
29 |
30 | session.save(person);
31 |
32 | tx.commit();
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/chapter03/src/test/java/chapter03/simple/ModelTest.java:
--------------------------------------------------------------------------------
1 | package chapter03.simple;
2 |
3 | import org.testng.annotations.Test;
4 |
5 | public class ModelTest {
6 | @Test
7 | public void testModelCreation() {
8 | Person subject = new Person();
9 | subject.setName("J. C. Smell");
10 |
11 | Person observer = new Person();
12 | observer.setName("Drew Lombardo");
13 |
14 | Skill skill = new Skill();
15 | skill.setName("Java");
16 |
17 | Ranking ranking = new Ranking();
18 | ranking.setSubject(subject);
19 | ranking.setObserver(observer);
20 | ranking.setSkill(skill);
21 | ranking.setRanking(8);
22 |
23 | // just to give us visual verification
24 | System.out.println(ranking);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/chapter03/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db3
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 |
14 | 10
15 |
16 | true
17 |
18 | create
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/chapter04/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter04
12 |
13 |
14 |
15 | org.hibernate
16 | hibernate-c3p0
17 |
18 |
19 | com.mchange
20 | c3p0
21 |
22 |
23 | com.autumncode.books.hibernate
24 | util
25 |
26 |
27 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/broken/Email.java:
--------------------------------------------------------------------------------
1 | package chapter04.broken;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Email {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column
11 | String subject;
12 | @OneToOne
13 | // (mappedBy = "email")
14 | Message message;
15 |
16 | public Email() {
17 | }
18 |
19 | public Email(String subject) {
20 | setSubject(subject);
21 | }
22 |
23 | public Long getId() {
24 | return id;
25 | }
26 |
27 | public void setId(Long id) {
28 | this.id = id;
29 | }
30 |
31 | public String getSubject() {
32 | return subject;
33 | }
34 |
35 | public void setSubject(String subject) {
36 | this.subject = subject;
37 | }
38 |
39 | public Message getMessage() {
40 | return message;
41 | }
42 |
43 | public void setMessage(Message message) {
44 | this.message = message;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | // note use of message.content because otherwise properly constructed
50 | // relationships would cause an endless loop that never ends
51 | // and therefore runs endlessly.
52 | return "Email{" +
53 | "id=" + id +
54 | ", subject='" + subject + '\'' +
55 | ", message.content=" + (message != null ? message.getContent() : "null") +
56 | '}';
57 | }
58 | }
59 |
60 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/broken/Message.java:
--------------------------------------------------------------------------------
1 | package chapter04.broken;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Message {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 |
11 | @Column
12 | String content;
13 |
14 | @OneToOne
15 | Email email;
16 |
17 | public Message() {
18 | }
19 |
20 | public Message(String content) {
21 | setContent(content);
22 | }
23 |
24 | public Long getId() {
25 | return id;
26 | }
27 |
28 | public void setId(Long id) {
29 | this.id = id;
30 | }
31 |
32 | public String getContent() {
33 | return content;
34 | }
35 |
36 | public void setContent(String content) {
37 | this.content = content;
38 | }
39 |
40 | public Email getEmail() {
41 | return email;
42 | }
43 |
44 | public void setEmail(Email email) {
45 | this.email = email;
46 | }
47 |
48 | @Override
49 | public String toString() {
50 | // note use of email.subject because otherwise properly constructed
51 | // relationships would cause an endless loop that never ends
52 | // and therefore runs endlessly.
53 | return "Message{" +
54 | "id=" + id +
55 | ", content='" + content + '\'' +
56 | ", email.subject=" + (email != null ? email.getSubject() : "null") +
57 | '}';
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/id/GeneratedAutoIdentity.java:
--------------------------------------------------------------------------------
1 | package chapter04.id;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class GeneratedAutoIdentity {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column
11 | String value;
12 |
13 | public GeneratedAutoIdentity() {
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(Long id) {
21 | this.id = id;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/id/GeneratedIdentityIdentity.java:
--------------------------------------------------------------------------------
1 | package chapter04.id;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class GeneratedIdentityIdentity {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.IDENTITY)
9 | Long id;
10 | @Column
11 | String value;
12 |
13 | public GeneratedIdentityIdentity() {
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(Long id) {
21 | this.id = id;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/id/GeneratedSequenceIdentity.java:
--------------------------------------------------------------------------------
1 | package chapter04.id;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class GeneratedSequenceIdentity {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.SEQUENCE)
9 | Long id;
10 | @Column
11 | String value;
12 |
13 | public GeneratedSequenceIdentity() {
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(Long id) {
21 | this.id = id;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/id/GeneratedTableIdentity.java:
--------------------------------------------------------------------------------
1 | package chapter04.id;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class GeneratedTableIdentity {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.TABLE)
9 | Long id;
10 | @Column
11 | String value;
12 |
13 | public GeneratedTableIdentity() {
14 | }
15 |
16 | public Long getId() {
17 | return id;
18 | }
19 |
20 | public void setId(Long id) {
21 | this.id = id;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/id/NongeneratedIdentity.java:
--------------------------------------------------------------------------------
1 | package chapter04.id;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.Id;
6 |
7 | @Entity
8 | public class NongeneratedIdentity {
9 | @Id
10 | Long id;
11 | @Column
12 | String value;
13 |
14 | public NongeneratedIdentity() {
15 | }
16 |
17 | public Long getId() {
18 | return id;
19 | }
20 |
21 | public void setId(Long id) {
22 | this.id = id;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/mapped/Email.java:
--------------------------------------------------------------------------------
1 | package chapter04.mapped;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity(name = "Email2")
6 | public class Email {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column
11 | String subject;
12 | @OneToOne(mappedBy = "email")
13 | Message message;
14 |
15 | public Email() {
16 | }
17 |
18 | public Email(String subject) {
19 | setSubject(subject);
20 | }
21 |
22 | public Long getId() {
23 | return id;
24 | }
25 |
26 | public void setId(Long id) {
27 | this.id = id;
28 | }
29 |
30 | public String getSubject() {
31 | return subject;
32 | }
33 |
34 | public void setSubject(String subject) {
35 | this.subject = subject;
36 | }
37 |
38 | public Message getMessage() {
39 | return message;
40 | }
41 |
42 | public void setMessage(Message message) {
43 | this.message = message;
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | // note use of message.content because otherwise properly constructed
49 | // relationships would cause an endless loop that never ends
50 | // and therefore runs endlessly.
51 | return "Email{" +
52 | "id=" + id +
53 | ", subject='" + subject + '\'' +
54 | ", message.content=" + (message != null ? message.getContent() : "null") +
55 | '}';
56 | }
57 | }
58 |
59 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/mapped/Message.java:
--------------------------------------------------------------------------------
1 | package chapter04.mapped;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity(name = "Message2")
6 | public class Message {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 |
11 | @Column
12 | String content;
13 |
14 | @OneToOne
15 | Email email;
16 |
17 | public Message() {
18 | }
19 |
20 | public Message(String content) {
21 | setContent(content);
22 | }
23 |
24 | public Long getId() {
25 | return id;
26 | }
27 |
28 | public void setId(Long id) {
29 | this.id = id;
30 | }
31 |
32 | public String getContent() {
33 | return content;
34 | }
35 |
36 | public void setContent(String content) {
37 | this.content = content;
38 | }
39 |
40 | public Email getEmail() {
41 | return email;
42 | }
43 |
44 | public void setEmail(Email email) {
45 | this.email = email;
46 | }
47 |
48 | @Override
49 | public String toString() {
50 | // note use of email.subject because otherwise properly constructed
51 | // relationships would cause an endless loop that never ends
52 | // and therefore runs endlessly.
53 | return "Message{" +
54 | "id=" + id +
55 | ", content='" + content + '\'' +
56 | ", email.subject=" + (email != null ? email.getSubject() : "null") +
57 | '}';
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/model/SimpleObject.java:
--------------------------------------------------------------------------------
1 | package chapter04.model;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class SimpleObject {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column
11 | String key;
12 | @Column
13 | Long value;
14 |
15 | public SimpleObject() {
16 | }
17 |
18 | public Long getId() {
19 | return id;
20 | }
21 |
22 | public void setId(Long id) {
23 | this.id = id;
24 | }
25 |
26 | public String getKey() {
27 | return key;
28 | }
29 |
30 | public void setKey(String key) {
31 | this.key = key;
32 | }
33 |
34 | public Long getValue() {
35 | return value;
36 | }
37 |
38 | public void setValue(Long value) {
39 | this.value = value;
40 | }
41 |
42 | @Override
43 | public boolean equals(Object o) {
44 | if (this == o) return true;
45 | if (!(o instanceof SimpleObject)) return false;
46 |
47 | SimpleObject that = (SimpleObject) o;
48 |
49 | // we prefer the method versions of accessors, because of Hibernate's proxies.
50 | if (getId() != null ? !getId().equals(that.getId()) : that.getId() != null)
51 | return false;
52 | if (getKey() != null ? !getKey().equals(that.getKey()) : that.getKey() != null)
53 | return false;
54 | return getValue() != null ? getValue().equals(that.getValue()) : that.getValue() == null;
55 |
56 | }
57 |
58 | @Override
59 | public int hashCode() {
60 | int result = getId() != null ? getId().hashCode() : 0;
61 | result = 31 * result + (getKey() != null ? getKey().hashCode() : 0);
62 | result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
63 | return result;
64 | }
65 |
66 | @Override
67 | public String toString() {
68 | return "SimpleObject{" +
69 | "id=" + id +
70 | ", key='" + key + '\'' +
71 | ", value=" + value +
72 | '}';
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/orphan/Book.java:
--------------------------------------------------------------------------------
1 | package chapter04.orphan;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class Book {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.AUTO)
9 | Long id;
10 | @Column
11 | String title;
12 | @ManyToOne
13 | Library library;
14 |
15 | public Book() {
16 | }
17 |
18 | public Long getId() {
19 | return id;
20 | }
21 |
22 | public void setId(Long id) {
23 | this.id = id;
24 | }
25 |
26 | public String getTitle() {
27 | return title;
28 | }
29 |
30 | public void setTitle(String title) {
31 | this.title = title;
32 | }
33 |
34 | public Library getLibrary() {
35 | return library;
36 | }
37 |
38 | public void setLibrary(Library library) {
39 | this.library = library;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/chapter04/src/main/java/chapter04/orphan/Library.java:
--------------------------------------------------------------------------------
1 | package chapter04.orphan;
2 |
3 | import javax.persistence.*;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | @Entity
8 | public class Library {
9 | @Id
10 | @GeneratedValue(strategy = GenerationType.AUTO)
11 | Long id;
12 | @Column
13 | String name;
14 | @OneToMany(orphanRemoval = true, mappedBy = "library")
15 | List books = new ArrayList<>();
16 |
17 | public Library() {
18 | }
19 |
20 | public Long getId() {
21 | return id;
22 | }
23 |
24 | public void setId(Long id) {
25 | this.id = id;
26 | }
27 |
28 | public String getName() {
29 | return name;
30 | }
31 |
32 | public void setName(String name) {
33 | this.name = name;
34 | }
35 |
36 | public List getBooks() {
37 | return books;
38 | }
39 |
40 | public void setBooks(List books) {
41 | this.books = books;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/chapter04/src/test/java/chapter04/broken/BrokenInversionTest.java:
--------------------------------------------------------------------------------
1 | package chapter04.broken;
2 |
3 | import com.autumncode.hibernate.util.SessionUtil;
4 | import org.hibernate.Session;
5 | import org.hibernate.Transaction;
6 | import org.testng.annotations.Test;
7 |
8 | import static org.testng.Assert.*;
9 |
10 | public class BrokenInversionTest {
11 |
12 | @Test
13 | public void testProperSimpleInversionCode() {
14 | Long emailId;
15 | Long messageId;
16 | Email email;
17 | Message message;
18 |
19 | try (Session session = SessionUtil.getSession()) {
20 | Transaction tx = session.beginTransaction();
21 |
22 | email = new Email("Proper");
23 | message = new Message("Proper");
24 |
25 | email.setMessage(message);
26 | message.setEmail(email);
27 |
28 | session.save(email);
29 | session.save(message);
30 |
31 | emailId = email.getId();
32 | messageId = message.getId();
33 |
34 | tx.commit();
35 | }
36 |
37 | assertNotNull(email.getMessage());
38 | assertNotNull(message.getEmail());
39 |
40 | try (Session session = SessionUtil.getSession()) {
41 | email = session.get(Email.class, emailId);
42 | System.out.println(email);
43 | message = session.get(Message.class, messageId);
44 | System.out.println(message);
45 | }
46 |
47 | assertNotNull(email.getMessage());
48 | assertNotNull(message.getEmail());
49 | }
50 |
51 | @Test()
52 | public void testBrokenInversionCode() {
53 | Long emailId;
54 | Long messageId;
55 | Email email;
56 | Message message;
57 |
58 | try (Session session = SessionUtil.getSession()) {
59 | Transaction tx = session.beginTransaction();
60 |
61 | email = new Email("Broken");
62 | message = new Message("Broken");
63 |
64 | email.setMessage(message);
65 | // message.setEmail(email);
66 |
67 | session.save(email);
68 | session.save(message);
69 |
70 | emailId = email.getId();
71 | messageId = message.getId();
72 |
73 | tx.commit();
74 | }
75 |
76 | assertNotNull(email.getMessage());
77 | assertNull(message.getEmail());
78 |
79 | try (Session session = SessionUtil.getSession()) {
80 | email = session.get(Email.class, emailId);
81 | System.out.println(email);
82 | message = session.get(Message.class, messageId);
83 | System.out.println(message);
84 | }
85 |
86 | assertNotNull(email.getMessage());
87 | assertNull(message.getEmail());
88 | }
89 |
90 | @Test
91 | public void testImpliedRelationship() {
92 | Long emailId;
93 | Long messageId;
94 |
95 | Session session = SessionUtil.getSession();
96 | Transaction tx = session.beginTransaction();
97 |
98 | Email email = new Email("Inverse Email");
99 | Message message = new Message("Inverse Message");
100 |
101 | email.setMessage(message);
102 | // message.setEmail(email);
103 |
104 | session.save(email);
105 | session.save(message);
106 |
107 | emailId = email.getId();
108 | messageId = message.getId();
109 |
110 | tx.commit();
111 | session.close();
112 |
113 | assertEquals(email.getSubject(), "Inverse Email");
114 | assertEquals(message.getContent(), "Inverse Message");
115 | assertNotNull(email.getMessage());
116 | assertNull(message.getEmail());
117 |
118 | session = SessionUtil.getSession();
119 | tx = session.beginTransaction();
120 | email = session.get(Email.class, emailId);
121 | System.out.println(email);
122 | message = session.get(Message.class, messageId);
123 | System.out.println(message);
124 |
125 | tx.commit();
126 | session.close();
127 |
128 | assertNotNull(email.getMessage());
129 | assertNull(message.getEmail());
130 |
131 | }
132 |
133 | }
134 |
--------------------------------------------------------------------------------
/chapter04/src/test/java/chapter04/general/MergeRefreshTest.java:
--------------------------------------------------------------------------------
1 | package chapter04.general;
2 |
3 | import chapter04.model.SimpleObject;
4 | import com.autumncode.hibernate.util.SessionUtil;
5 | import org.hibernate.Session;
6 | import org.hibernate.Transaction;
7 | import org.testng.annotations.Test;
8 |
9 | import static org.testng.Assert.assertEquals;
10 |
11 | public class MergeRefreshTest {
12 | @Test
13 | public void testMerge() {
14 | Long id;
15 | try (Session session = SessionUtil.getSession()) {
16 | Transaction tx = session.beginTransaction();
17 |
18 | SimpleObject simpleObject = new SimpleObject();
19 |
20 | simpleObject.setKey("testMerge");
21 | simpleObject.setValue(1L);
22 |
23 | session.save(simpleObject);
24 |
25 | id = simpleObject.getId();
26 |
27 | tx.commit();
28 | }
29 |
30 | SimpleObject so = validateSimpleObject(id, 1L);
31 |
32 | so.setValue(2L);
33 |
34 | try (Session session = SessionUtil.getSession()) {
35 | // merge is potentially an update, so we need a TX
36 | Transaction tx = session.beginTransaction();
37 |
38 | session.merge(so);
39 |
40 | tx.commit();
41 | }
42 |
43 | validateSimpleObject(id, 2L);
44 | }
45 |
46 | @Test
47 | public void testRefresh() {
48 | Long id;
49 | try (Session session = SessionUtil.getSession()) {
50 | Transaction tx = session.beginTransaction();
51 |
52 | SimpleObject simpleObject = new SimpleObject();
53 |
54 | simpleObject.setKey("testMerge");
55 | simpleObject.setValue(1L);
56 |
57 | session.save(simpleObject);
58 |
59 | id = simpleObject.getId();
60 |
61 | tx.commit();
62 | }
63 |
64 | SimpleObject so = validateSimpleObject(id, 1L);
65 |
66 | so.setValue(2L);
67 |
68 | try (Session session = SessionUtil.getSession()) {
69 | // note that refresh is a read,
70 | // so no TX is necessary unless an update occurs later
71 | session.refresh(so);
72 | }
73 |
74 | validateSimpleObject(id, 1L);
75 | }
76 |
77 | private SimpleObject validateSimpleObject(Long id, Long value) {
78 | SimpleObject so = null;
79 | try (Session session = SessionUtil.getSession()) {
80 | so = session.load(SimpleObject.class, id);
81 |
82 | assertEquals(so.getKey(), "testMerge");
83 | assertEquals(so.getValue(), value);
84 | }
85 |
86 | return so;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/chapter04/src/test/java/chapter04/general/PersistingEntitiesTest.java:
--------------------------------------------------------------------------------
1 | package chapter04.general;
2 |
3 | import chapter04.model.SimpleObject;
4 | import com.autumncode.hibernate.util.SessionUtil;
5 | import org.hibernate.Session;
6 | import org.hibernate.Transaction;
7 | import org.testng.annotations.Test;
8 |
9 | import static org.testng.Assert.*;
10 |
11 | public class PersistingEntitiesTest {
12 | @Test
13 | public void testSaveLoad() {
14 | Long id = null;
15 | SimpleObject obj;
16 |
17 | try (Session session = SessionUtil.getSession()) {
18 | Transaction tx = session.beginTransaction();
19 |
20 | obj = new SimpleObject();
21 | obj.setKey("sl");
22 | obj.setValue(10L);
23 |
24 | session.save(obj);
25 | assertNotNull(obj.getId());
26 | // we should have an id now, set by Session.save()
27 | id = obj.getId();
28 |
29 | tx.commit();
30 | }
31 |
32 | try (Session session = SessionUtil.getSession()) {
33 | // we're loading the object by id
34 | SimpleObject o2 = session.load(SimpleObject.class, id);
35 | assertEquals(o2.getKey(), "sl");
36 | assertNotNull(o2.getValue());
37 | assertEquals(o2.getValue().longValue(), 10L);
38 |
39 | SimpleObject o3 = session.load(SimpleObject.class, id);
40 |
41 | // since o3 and o2 were loaded in the same session, they're not only
42 | // equivalent - as shown by equals() - but equal, as shown by ==.
43 | // since obj was NOT loaded in this session, it's equivalent but
44 | // not ==.
45 | assertEquals(o2, o3);
46 | assertEquals(obj, o2);
47 |
48 | assertTrue(o2 == o3);
49 | assertFalse(o2 == obj);
50 | }
51 | }
52 |
53 | @Test
54 | public void testSavingEntitiesTwice() {
55 | Long id;
56 | SimpleObject obj;
57 |
58 | try (Session session = SessionUtil.getSession()) {
59 | Transaction tx = session.beginTransaction();
60 |
61 | obj = new SimpleObject();
62 |
63 | obj.setKey("osas");
64 | obj.setValue(10L);
65 |
66 | session.save(obj);
67 | assertNotNull(obj.getId());
68 |
69 | id = obj.getId();
70 |
71 | tx.commit();
72 | }
73 |
74 | try (Session session = SessionUtil.getSession()) {
75 | Transaction tx = session.beginTransaction();
76 |
77 | obj.setValue(12L);
78 |
79 | session.save(obj);
80 |
81 | tx.commit();
82 | }
83 |
84 | // note that save() creates a new row in the database!
85 | // this is wrong behavior. Don't do this!
86 | assertNotEquals(id, obj.getId());
87 | }
88 |
89 | @Test
90 | public void testSaveOrUpdateEntity() {
91 | Long id;
92 | SimpleObject obj;
93 |
94 | try (Session session = SessionUtil.getSession()) {
95 | Transaction tx = session.beginTransaction();
96 |
97 | obj = new SimpleObject();
98 |
99 | obj.setKey("osas2");
100 | obj.setValue(14L);
101 |
102 | session.save(obj);
103 | assertNotNull(obj.getId());
104 |
105 | id = obj.getId();
106 |
107 | tx.commit();
108 | }
109 |
110 | try (Session session = SessionUtil.getSession()) {
111 | Transaction tx = session.beginTransaction();
112 |
113 | obj.setValue(12L);
114 |
115 | session.saveOrUpdate(obj);
116 |
117 | tx.commit();
118 | }
119 |
120 | // saveOrUpdate() will update a row in the database
121 | // if one matches. This is what one usually expects.
122 | assertEquals(id, obj.getId());
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/chapter04/src/test/java/chapter04/id/IdentityTest.java:
--------------------------------------------------------------------------------
1 | package chapter04.id;
2 |
3 | import com.autumncode.hibernate.util.SessionUtil;
4 | import org.hibernate.Session;
5 | import org.hibernate.Transaction;
6 | import org.testng.annotations.Test;
7 |
8 | import javax.persistence.PersistenceException;
9 |
10 | public class IdentityTest {
11 | @Test
12 | public void testAutoIdentity() {
13 | Session session = SessionUtil.getSession();
14 | Transaction tx = session.beginTransaction();
15 |
16 | GeneratedAutoIdentity obj = new GeneratedAutoIdentity();
17 |
18 | session.persist(obj);
19 |
20 | tx.commit();
21 | session.close();
22 |
23 | System.out.println(obj.getId());
24 | }
25 |
26 | @Test(expectedExceptions = PersistenceException.class)
27 | public void testNongeneratedIdentityFailure() {
28 | Session session = SessionUtil.getSession();
29 | Transaction tx = session.beginTransaction();
30 |
31 | NongeneratedIdentity obj = new NongeneratedIdentity();
32 |
33 | session.persist(obj);
34 |
35 | tx.commit();
36 | session.close();
37 |
38 | System.out.println(obj.getId());
39 | }
40 |
41 | @Test
42 | public void testNongeneratedIdentity() {
43 | Session session = SessionUtil.getSession();
44 | Transaction tx = session.beginTransaction();
45 |
46 | NongeneratedIdentity obj = new NongeneratedIdentity();
47 | obj.setId(1l);
48 | session.persist(obj);
49 |
50 | tx.commit();
51 | session.close();
52 |
53 | System.out.println(obj.getId());
54 | }
55 |
56 | @Test
57 | public void testSequenceIdentity() {
58 | Session session = SessionUtil.getSession();
59 | Transaction tx = session.beginTransaction();
60 |
61 | GeneratedSequenceIdentity obj = new GeneratedSequenceIdentity();
62 | session.persist(obj);
63 |
64 | tx.commit();
65 | session.close();
66 |
67 | System.out.println(obj.getId());
68 | }
69 |
70 | @Test
71 | public void testTableIdentity() {
72 | Session session = SessionUtil.getSession();
73 | Transaction tx = session.beginTransaction();
74 |
75 | GeneratedTableIdentity obj = new GeneratedTableIdentity();
76 | session.persist(obj);
77 |
78 | tx.commit();
79 | session.close();
80 |
81 | System.out.println(obj.getId());
82 | }
83 |
84 | @Test
85 | public void testIdentityIdentity() {
86 | Session session = SessionUtil.getSession();
87 | Transaction tx = session.beginTransaction();
88 |
89 | GeneratedIdentityIdentity obj = new GeneratedIdentityIdentity();
90 | session.persist(obj);
91 |
92 | tx.commit();
93 | session.close();
94 |
95 | System.out.println(obj.getId());
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/chapter04/src/test/java/chapter04/mapped/WorkingInversionTest.java:
--------------------------------------------------------------------------------
1 | package chapter04.mapped;
2 |
3 | import com.autumncode.hibernate.util.SessionUtil;
4 | import org.hibernate.Session;
5 | import org.hibernate.Transaction;
6 | import org.testng.annotations.Test;
7 |
8 | import static org.testng.Assert.*;
9 |
10 | public class WorkingInversionTest {
11 |
12 | @Test
13 | public void testProperSimpleInversionCode() {
14 | Long emailId;
15 | Long messageId;
16 | Email email;
17 | Message message;
18 |
19 | try (Session session = SessionUtil.getSession()) {
20 | Transaction tx = session.beginTransaction();
21 |
22 | email = new Email("Proper");
23 | message = new Message("Proper");
24 |
25 | email.setMessage(message);
26 | message.setEmail(email);
27 |
28 | session.save(email);
29 | session.save(message);
30 |
31 | emailId = email.getId();
32 | messageId = message.getId();
33 |
34 | tx.commit();
35 | }
36 |
37 | assertNotNull(email.getMessage());
38 | assertNotNull(message.getEmail());
39 |
40 | try (Session session = SessionUtil.getSession()) {
41 | email = session.get(Email.class, emailId);
42 | System.out.println(email);
43 | message = session.get(Message.class, messageId);
44 | System.out.println(message);
45 | }
46 |
47 | assertNotNull(email.getMessage());
48 | assertNotNull(message.getEmail());
49 | }
50 |
51 | @Test()
52 | public void testBrokenInversionCode() {
53 | Long emailId;
54 | Long messageId;
55 |
56 | Session session = SessionUtil.getSession();
57 | Transaction tx = session.beginTransaction();
58 |
59 | Email email = new Email("Broken");
60 | Message message = new Message("Broken");
61 |
62 | email.setMessage(message);
63 | // message.setEmail(email);
64 |
65 | session.save(email);
66 | session.save(message);
67 |
68 | emailId = email.getId();
69 | messageId = message.getId();
70 |
71 | tx.commit();
72 | session.close();
73 |
74 | assertNotNull(email.getMessage());
75 | assertNull(message.getEmail());
76 |
77 | session = SessionUtil.getSession();
78 | tx = session.beginTransaction();
79 | email = session.get(Email.class, emailId);
80 | System.out.println(email);
81 | message = session.get(Message.class, messageId);
82 | System.out.println(message);
83 |
84 | tx.commit();
85 | session.close();
86 |
87 | assertNull(email.getMessage());
88 | assertNull(message.getEmail());
89 | }
90 |
91 | @Test
92 | public void testImpliedRelationship() {
93 | Long emailId;
94 | Long messageId;
95 | Email email;
96 | Message message;
97 |
98 | try (Session session = SessionUtil.getSession()) {
99 | Transaction tx = session.beginTransaction();
100 |
101 | email = new Email("Inverse Email");
102 | message = new Message("Inverse Message");
103 |
104 | // email.setMessage(message);
105 | message.setEmail(email);
106 |
107 | session.save(email);
108 | session.save(message);
109 |
110 | emailId = email.getId();
111 | messageId = message.getId();
112 |
113 | tx.commit();
114 | }
115 |
116 | assertEquals(email.getSubject(), "Inverse Email");
117 | assertEquals(message.getContent(), "Inverse Message");
118 | assertNull(email.getMessage());
119 | assertNotNull(message.getEmail());
120 |
121 | try (Session session = SessionUtil.getSession()) {
122 | email = session.get(Email.class, emailId);
123 | System.out.println(email);
124 | message = session.get(Message.class, messageId);
125 | System.out.println(message);
126 | }
127 |
128 | assertNotNull(email.getMessage());
129 | assertNotNull(message.getEmail());
130 | }
131 |
132 | }
133 |
--------------------------------------------------------------------------------
/chapter04/src/test/java/chapter04/orphan/OrphanRemovalTest.java:
--------------------------------------------------------------------------------
1 | package chapter04.orphan;
2 |
3 | import com.autumncode.hibernate.util.SessionUtil;
4 | import org.hibernate.Session;
5 | import org.hibernate.Transaction;
6 | import org.hibernate.query.Query;
7 | import org.testng.annotations.Test;
8 |
9 | import java.util.List;
10 |
11 | import static org.testng.Assert.assertEquals;
12 |
13 | public class OrphanRemovalTest {
14 | @Test
15 | public void orphanRemovalTest() {
16 | Long id = createLibrary();
17 |
18 | try (Session session = SessionUtil.getSession()) {
19 | Transaction tx = session.beginTransaction();
20 |
21 | Library library = session.load(Library.class, id);
22 | assertEquals(library.getBooks().size(), 3);
23 |
24 | library.getBooks().remove(0);
25 | assertEquals(library.getBooks().size(), 2);
26 |
27 | tx.commit();
28 | }
29 |
30 | try (Session session = SessionUtil.getSession()) {
31 | Transaction tx = session.beginTransaction();
32 |
33 | Library l2 = session.load(Library.class, id);
34 | assertEquals(l2.getBooks().size(), 2);
35 |
36 | Query query = session.createQuery("from Book b", Book.class);
37 | List books = query.list();
38 | assertEquals(books.size(), 2);
39 |
40 | tx.commit();
41 | }
42 | }
43 |
44 | private Long createLibrary() {
45 | Library library = null;
46 | try (Session session = SessionUtil.getSession()) {
47 | Transaction tx = session.beginTransaction();
48 |
49 | library = new Library();
50 | library.setName("orphanLib");
51 | session.save(library);
52 |
53 | Book book = new Book();
54 | book.setLibrary(library);
55 | book.setTitle("book 1");
56 | session.save(book);
57 | library.getBooks().add(book);
58 |
59 | book = new Book();
60 | book.setLibrary(library);
61 | book.setTitle("book 2");
62 | session.save(book);
63 | library.getBooks().add(book);
64 |
65 | book = new Book();
66 | book.setLibrary(library);
67 | book.setTitle("book 3");
68 | session.save(book);
69 | library.getBooks().add(book);
70 |
71 | tx.commit();
72 | }
73 |
74 | return library.getId();
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/chapter04/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db4
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 |
14 | 10
15 |
16 | true
17 |
18 | create
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/chapter05/README.txt:
--------------------------------------------------------------------------------
1 | Chapter 5's project is empty, mostly because Chapter 5 was focused
2 | almost entirely on mapping concepts and not on actual coding
3 | practices; the few places where coding would be appropriate have
4 | already been shown in prior chapters.
--------------------------------------------------------------------------------
/chapter05/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter05
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/chapter06/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter06
12 |
13 |
14 |
15 | org.hibernate
16 | hibernate-c3p0
17 |
18 |
19 | com.mchange
20 | c3p0
21 |
22 |
23 | com.autumncode.books.hibernate
24 | util
25 |
26 |
27 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/compoundpk/CPKBook.java:
--------------------------------------------------------------------------------
1 | package chapter06.compoundpk;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.Id;
6 |
7 | @Entity
8 | public class CPKBook {
9 | @Id
10 | ISBN id;
11 | @Column
12 | String name;
13 |
14 | public CPKBook() {
15 | }
16 |
17 | public ISBN getId() {
18 | return id;
19 | }
20 |
21 | public void setId(ISBN id) {
22 | this.id = id;
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String title) {
30 | this.name = title;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/compoundpk/EmbeddedPKBook.java:
--------------------------------------------------------------------------------
1 | package chapter06.compoundpk;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.EmbeddedId;
5 | import javax.persistence.Entity;
6 | import java.io.Serializable;
7 |
8 | @Entity
9 | public class EmbeddedPKBook {
10 | @EmbeddedId
11 | EmbeddedISBN id;
12 | @Column
13 | String name;
14 |
15 | static class EmbeddedISBN implements Serializable {
16 | @Column(name = "group_number")
17 | int group;
18 | int publisher;
19 | int title;
20 | int checkdigit;
21 |
22 | public EmbeddedISBN() {
23 | }
24 |
25 | public int getGroup() {
26 | return group;
27 | }
28 |
29 | public void setGroup(int group) {
30 | this.group = group;
31 | }
32 |
33 | public int getPublisher() {
34 | return publisher;
35 | }
36 |
37 | public void setPublisher(int publisher) {
38 | this.publisher = publisher;
39 | }
40 |
41 | public int getTitle() {
42 | return title;
43 | }
44 |
45 | public void setTitle(int title) {
46 | this.title = title;
47 | }
48 |
49 | public int getCheckdigit() {
50 | return checkdigit;
51 | }
52 |
53 | public void setCheckdigit(int checkdigit) {
54 | this.checkdigit = checkdigit;
55 | }
56 |
57 | @Override
58 | public boolean equals(Object o) {
59 | if (this == o) return true;
60 | if (!(o instanceof ISBN)) return false;
61 |
62 | ISBN isbn = (ISBN) o;
63 |
64 | if (checkdigit != isbn.checkdigit) return false;
65 | if (group != isbn.group) return false;
66 | if (publisher != isbn.publisher) return false;
67 | if (title != isbn.title) return false;
68 |
69 | return true;
70 | }
71 |
72 | @Override
73 | public int hashCode() {
74 | int result = group;
75 | result = 31 * result + publisher;
76 | result = 31 * result + title;
77 | result = 31 * result + checkdigit;
78 | return result;
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/compoundpk/ISBN.java:
--------------------------------------------------------------------------------
1 | package chapter06.compoundpk;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Embeddable;
5 | import java.io.Serializable;
6 |
7 | @Embeddable
8 | public class ISBN implements Serializable {
9 | @Column(name = "group_number")
10 | int group;
11 | int publisher;
12 | int title;
13 | int checkdigit;
14 |
15 | public ISBN() {
16 | }
17 |
18 | public int getGroup() {
19 | return group;
20 | }
21 |
22 | public void setGroup(int group) {
23 | this.group = group;
24 | }
25 |
26 | public int getPublisher() {
27 | return publisher;
28 | }
29 |
30 | public void setPublisher(int publisher) {
31 | this.publisher = publisher;
32 | }
33 |
34 | public int getTitle() {
35 | return title;
36 | }
37 |
38 | public void setTitle(int title) {
39 | this.title = title;
40 | }
41 |
42 | public int getCheckdigit() {
43 | return checkdigit;
44 | }
45 |
46 | public void setCheckdigit(int checkdigit) {
47 | this.checkdigit = checkdigit;
48 | }
49 |
50 | @Override
51 | public boolean equals(Object o) {
52 | if (this == o) return true;
53 | if (!(o instanceof ISBN)) return false;
54 |
55 | ISBN isbn = (ISBN) o;
56 |
57 | if (checkdigit != isbn.checkdigit) return false;
58 | if (group != isbn.group) return false;
59 | if (publisher != isbn.publisher) return false;
60 | if (title != isbn.title) return false;
61 |
62 | return true;
63 | }
64 |
65 | @Override
66 | public int hashCode() {
67 | int result = group;
68 | result = 31 * result + publisher;
69 | result = 31 * result + title;
70 | result = 31 * result + checkdigit;
71 | return result;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/compoundpk/IdClassBook.java:
--------------------------------------------------------------------------------
1 | package chapter06.compoundpk;
2 |
3 | import javax.persistence.Column;
4 | import javax.persistence.Entity;
5 | import javax.persistence.Id;
6 | import javax.persistence.IdClass;
7 | import java.io.Serializable;
8 |
9 | @Entity
10 | @IdClass(IdClassBook.EmbeddedISBN.class)
11 | public class IdClassBook {
12 | @Id
13 | @Column(name = "group_number")
14 | int group;
15 | @Id
16 | int publisher;
17 | @Id
18 | int title;
19 | @Id
20 | int checkdigit;
21 | String name;
22 |
23 | public IdClassBook() {
24 | }
25 |
26 | public int getGroup() {
27 | return group;
28 | }
29 |
30 | public void setGroup(int group) {
31 | this.group = group;
32 | }
33 |
34 | public int getPublisher() {
35 | return publisher;
36 | }
37 |
38 | public void setPublisher(int publisher) {
39 | this.publisher = publisher;
40 | }
41 |
42 | public int getTitle() {
43 | return title;
44 | }
45 |
46 | public void setTitle(int title) {
47 | this.title = title;
48 | }
49 |
50 | public int getCheckdigit() {
51 | return checkdigit;
52 | }
53 |
54 | public void setCheckdigit(int checkdigit) {
55 | this.checkdigit = checkdigit;
56 | }
57 |
58 | public String getName() {
59 | return name;
60 | }
61 |
62 | public void setName(String name) {
63 | this.name = name;
64 | }
65 |
66 | static class EmbeddedISBN implements Serializable {
67 | int group;
68 | int publisher;
69 | int title;
70 | int checkdigit;
71 |
72 | public EmbeddedISBN() {
73 | }
74 |
75 | public int getGroup() {
76 | return group;
77 | }
78 |
79 | public void setGroup(int group) {
80 | this.group = group;
81 | }
82 |
83 | public int getPublisher() {
84 | return publisher;
85 | }
86 |
87 | public void setPublisher(int publisher) {
88 | this.publisher = publisher;
89 | }
90 |
91 | public int getTitle() {
92 | return title;
93 | }
94 |
95 | public void setTitle(int title) {
96 | this.title = title;
97 | }
98 |
99 | public int getCheckdigit() {
100 | return checkdigit;
101 | }
102 |
103 | public void setCheckdigit(int checkdigit) {
104 | this.checkdigit = checkdigit;
105 | }
106 |
107 | @Override
108 | public boolean equals(Object o) {
109 | if (this == o) return true;
110 | if (!(o instanceof ISBN)) return false;
111 |
112 | ISBN isbn = (ISBN) o;
113 |
114 | if (checkdigit != isbn.checkdigit) return false;
115 | if (group != isbn.group) return false;
116 | if (publisher != isbn.publisher) return false;
117 | if (title != isbn.title) return false;
118 |
119 | return true;
120 | }
121 |
122 | @Override
123 | public int hashCode() {
124 | int result = group;
125 | result = 31 * result + publisher;
126 | result = 31 * result + title;
127 | result = 31 * result + checkdigit;
128 | return result;
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/mappedsuperclass/BookSuperclass.java:
--------------------------------------------------------------------------------
1 | package chapter06.mappedsuperclass;
2 |
3 |
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.Id;
6 | import javax.persistence.MappedSuperclass;
7 |
8 | @MappedSuperclass
9 | public class BookSuperclass {
10 | @Id
11 | @GeneratedValue
12 | Integer id;
13 | String name;
14 |
15 | public BookSuperclass() {
16 | }
17 |
18 | public Integer getId() {
19 | return id;
20 | }
21 |
22 | public void setId(Integer id) {
23 | this.id = id;
24 | }
25 |
26 | public String getName() {
27 | return name;
28 | }
29 |
30 | public void setName(String name) {
31 | this.name = name;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/mappedsuperclass/ComputerBook.java:
--------------------------------------------------------------------------------
1 | package chapter06.mappedsuperclass;
2 |
3 | import javax.persistence.Entity;
4 |
5 | @Entity
6 | public class ComputerBook extends BookSuperclass {
7 | String language;
8 |
9 | public ComputerBook() {
10 | }
11 |
12 | public String getLanguage() {
13 | return language;
14 | }
15 |
16 | public void setLanguage(String language) {
17 | this.language = language;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/naturalid/Employee.java:
--------------------------------------------------------------------------------
1 | package chapter06.naturalid;
2 |
3 | import org.hibernate.annotations.NaturalId;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 |
10 | @Entity
11 | public class Employee {
12 | @Id
13 | @GeneratedValue(strategy = GenerationType.AUTO)
14 | Integer id;
15 | @NaturalId
16 | Integer section;
17 | @NaturalId
18 | Integer department;
19 | String name;
20 |
21 | public Employee() {
22 | }
23 |
24 | public Integer getId() {
25 | return id;
26 | }
27 |
28 | public void setId(Integer id) {
29 | this.id = id;
30 | }
31 |
32 | public Integer getSection() {
33 | return section;
34 | }
35 |
36 | public void setSection(Integer section) {
37 | this.section = section;
38 | }
39 |
40 | public Integer getDepartment() {
41 | return department;
42 | }
43 |
44 | public void setDepartment(Integer department) {
45 | this.department = department;
46 | }
47 |
48 | public String getName() {
49 | return name;
50 | }
51 |
52 | public void setName(String name) {
53 | this.name = name;
54 | }
55 |
56 | @Override
57 | public boolean equals(Object o) {
58 | if (this == o) return true;
59 | if (!(o instanceof Employee)) return false;
60 |
61 | Employee employee = (Employee) o;
62 |
63 | if (department != null ? !department.equals(employee.getDepartment()) : employee.getDepartment() != null)
64 | return false;
65 | if (id != null ? !id.equals(employee.getId()) : employee.getId() != null) return false;
66 | if (name != null ? !name.equals(employee.getName()) : employee.getName() != null) return false;
67 | if (section != null ? !section.equals(employee.getSection()) : employee.getSection() != null) return false;
68 | System.out.println("returning true for equals()");
69 | return true;
70 | }
71 |
72 | @Override
73 | public int hashCode() {
74 | int result = id != null ? id.hashCode() : 0;
75 | result = 31 * result + (section != null ? section.hashCode() : 0);
76 | result = 31 * result + (department != null ? department.hashCode() : 0);
77 | result = 31 * result + (name != null ? name.hashCode() : 0);
78 | return result;
79 | }
80 |
81 | @Override
82 | public String toString() {
83 | final StringBuilder sb = new StringBuilder("Employee{");
84 | sb.append("id=").append(id);
85 | sb.append(", section=").append(section);
86 | sb.append(", department=").append(department);
87 | sb.append(", name='").append(name).append('\'');
88 | sb.append('}');
89 | return sb.toString();
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/naturalid/SimpleNaturalIdEmployee.java:
--------------------------------------------------------------------------------
1 | package chapter06.naturalid;
2 |
3 | import org.hibernate.annotations.NaturalId;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 |
10 | @Entity
11 | public class SimpleNaturalIdEmployee {
12 | @Id
13 | @GeneratedValue(strategy = GenerationType.AUTO)
14 | Integer id;
15 | @NaturalId
16 | Integer badge;
17 | String name;
18 |
19 | public SimpleNaturalIdEmployee() {
20 | }
21 |
22 | public Integer getId() {
23 | return id;
24 | }
25 |
26 | public void setId(Integer id) {
27 | this.id = id;
28 | }
29 |
30 | public Integer getBadge() {
31 | return badge;
32 | }
33 |
34 | public void setBadge(Integer badge) {
35 | this.badge = badge;
36 | }
37 |
38 | public String getName() {
39 | return name;
40 | }
41 |
42 | public void setName(String name) {
43 | this.name = name;
44 | }
45 |
46 | @Override
47 | public boolean equals(Object o) {
48 | if (this == o) return true;
49 | if (!(o instanceof SimpleNaturalIdEmployee)) return false;
50 |
51 | SimpleNaturalIdEmployee that = (SimpleNaturalIdEmployee) o;
52 |
53 | if (badge != null ? !badge.equals(that.badge) : that.badge != null) return false;
54 | if (id != null ? !id.equals(that.id) : that.id != null) return false;
55 | if (name != null ? !name.equals(that.name) : that.name != null) return false;
56 |
57 | return true;
58 | }
59 |
60 | @Override
61 | public int hashCode() {
62 | int result = id != null ? id.hashCode() : 0;
63 | result = 31 * result + (badge != null ? badge.hashCode() : 0);
64 | result = 31 * result + (name != null ? name.hashCode() : 0);
65 | return result;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/primarykey/after/Book.java:
--------------------------------------------------------------------------------
1 | package chapter06.primarykey.after;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.Id;
6 |
7 | @Entity
8 | public class Book {
9 | String title;
10 | int pages;
11 | @Id
12 | @GeneratedValue()
13 | int id;
14 |
15 | public Book() {
16 | }
17 |
18 | public String getTitle() {
19 | return title;
20 | }
21 |
22 | public void setTitle(String title) {
23 | this.title = title;
24 | }
25 |
26 | public int getPages() {
27 | return pages;
28 | }
29 |
30 | public void setPages(int pages) {
31 | this.pages = pages;
32 | }
33 |
34 | public int getId() {
35 | return id;
36 | }
37 |
38 | public void setId(int id) {
39 | this.id = id;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/primarykey/before/Book.java:
--------------------------------------------------------------------------------
1 | package chapter06.primarykey.before;
2 |
3 | public class Book {
4 | String title;
5 | int pages;
6 | int id;
7 |
8 | public String getTitle() {
9 | return title;
10 | }
11 |
12 | public void setTitle(String title) {
13 | this.title = title;
14 | }
15 |
16 | public int getPages() {
17 | return pages;
18 | }
19 |
20 | public void setPages(int pages) {
21 | this.pages = pages;
22 | }
23 |
24 | public int getId() {
25 | return id;
26 | }
27 |
28 | public void setId(int id) {
29 | this.id = id;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/chapter06/src/main/java/chapter06/twotables/Customer.java:
--------------------------------------------------------------------------------
1 | package chapter06.twotables;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | @Table(
7 | name = "customer",
8 | uniqueConstraints = {@UniqueConstraint(columnNames = "name")}
9 | )
10 | @SecondaryTable(name = "customer_details")
11 | public class Customer {
12 | @Id
13 | public int id;
14 | public String name;
15 | @Column(table = "customer_details")
16 | public String address;
17 |
18 | public Customer() {
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/chapter06/src/test/java/chapter06/naturalid/NaturalIdTest.java:
--------------------------------------------------------------------------------
1 | package chapter06.naturalid;
2 |
3 | import com.autumncode.hibernate.util.SessionUtil;
4 | import org.hibernate.ObjectNotFoundException;
5 | import org.hibernate.Session;
6 | import org.hibernate.Transaction;
7 | import org.testng.annotations.Test;
8 |
9 | import static org.testng.Assert.*;
10 |
11 | public class NaturalIdTest {
12 | @Test
13 | public void testSimpleNaturalId() {
14 | Integer id = createSimpleEmployee("Sorhed", 5401).getId();
15 |
16 | try (Session session = SessionUtil.getSession()) {
17 | Transaction tx = session.beginTransaction();
18 |
19 | SimpleNaturalIdEmployee employee =
20 | session
21 | .byId(SimpleNaturalIdEmployee.class)
22 | .load(id);
23 | assertNotNull(employee);
24 | SimpleNaturalIdEmployee badgedEmployee =
25 | session
26 | .bySimpleNaturalId(SimpleNaturalIdEmployee.class)
27 | .load(5401);
28 | assertEquals(badgedEmployee, employee);
29 |
30 | tx.commit();
31 | }
32 | }
33 |
34 | @Test
35 | public void testLoadByNaturalId() {
36 | Employee initial = createEmployee("Arrowroot", 11, 291);
37 | try (Session session = SessionUtil.getSession()) {
38 | Transaction tx = session.beginTransaction();
39 |
40 | Employee arrowroot = session
41 | .byNaturalId(Employee.class)
42 | .using("section", 11)
43 | .using("department", 291)
44 | .load();
45 | assertNotNull(arrowroot);
46 | assertEquals(initial, arrowroot);
47 |
48 | tx.commit();
49 | }
50 | }
51 |
52 | @Test
53 | public void testGetByNaturalId() {
54 | Employee initial = createEmployee("Eorwax", 11, 292);
55 | try (Session session = SessionUtil.getSession()) {
56 | Transaction tx = session.beginTransaction();
57 |
58 | Employee eorwax = session
59 | .byNaturalId(Employee.class)
60 | .using("section", 11)
61 | .using("department", 292)
62 | .getReference();
63 | System.out.println(initial.equals(eorwax));
64 | assertEquals(initial, eorwax);
65 |
66 | tx.commit();
67 | }
68 | }
69 |
70 | @Test
71 | public void testLoadById() {
72 | Integer id = createEmployee("Legolam", 10, 289).getId();
73 | try (Session session = SessionUtil.getSession()) {
74 | Transaction tx = session.beginTransaction();
75 |
76 | Employee boggit = session.byId(Employee.class).load(id);
77 | assertNotNull(boggit);
78 |
79 | /*
80 | load successful, let's delete it for the second half of the test
81 | */
82 | session.delete(boggit);
83 |
84 | tx.commit();
85 | }
86 |
87 | try (Session session = SessionUtil.getSession()) {
88 | Transaction tx = session.beginTransaction();
89 |
90 | Employee boggit = session.byId(Employee.class).load(id);
91 | assertNull(boggit);
92 |
93 | tx.commit();
94 | }
95 | }
96 |
97 | @Test
98 | public void testGetById() {
99 | Integer id = createEmployee("Eorache", 10, 290).getId();
100 | try (Session session = SessionUtil.getSession()) {
101 | Transaction tx = session.beginTransaction();
102 |
103 | Employee boggit = session.byId(Employee.class).getReference(id);
104 | assertNotNull(boggit);
105 |
106 | /*
107 | load successful, let's delete it for the second half of the test
108 | */
109 | session.delete(boggit);
110 |
111 | tx.commit();
112 | }
113 |
114 | try (Session session = SessionUtil.getSession()) {
115 | Transaction tx = session.beginTransaction();
116 |
117 | try {
118 | Employee boggit = session.byId(Employee.class).getReference(id);
119 |
120 | // trigger object initialization - which, with a nonexistent object,
121 | // will blow up.
122 | boggit.getDepartment();
123 | fail("Should have had an exception thrown!");
124 | } catch (ObjectNotFoundException ignored) {
125 | }
126 |
127 | tx.commit();
128 | }
129 | }
130 |
131 | private Employee createEmployee(String name, int section, int department) {
132 | Employee employee = new Employee();
133 | employee.setName(name);
134 | employee.setDepartment(department);
135 | employee.setSection(section);
136 | try (Session session = SessionUtil.getSession()) {
137 | Transaction tx = session.beginTransaction();
138 | session.save(employee);
139 | tx.commit();
140 | }
141 | return employee;
142 | }
143 |
144 | private SimpleNaturalIdEmployee createSimpleEmployee(String name, int badge) {
145 | SimpleNaturalIdEmployee employee = new SimpleNaturalIdEmployee();
146 | employee.setName(name);
147 | employee.setBadge(badge);
148 |
149 | try (Session session = SessionUtil.getSession()) {
150 | Transaction tx = session.beginTransaction();
151 | session.save(employee);
152 | tx.commit();
153 | }
154 | return employee;
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/chapter06/src/test/java/chapter06/primarykey/BookTest.java:
--------------------------------------------------------------------------------
1 | package chapter06.primarykey;
2 |
3 | import com.autumncode.hibernate.util.SessionUtil;
4 | import org.hibernate.Session;
5 | import org.testng.annotations.Test;
6 |
7 | import static org.testng.Assert.assertNotNull;
8 |
9 | public class BookTest {
10 | @Test
11 | public void bookTest() {
12 | try (Session session = SessionUtil.getSession()) {
13 | assertNotNull(session);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/chapter06/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db6
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 |
14 | 10
15 |
16 | true
17 |
18 | create
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/chapter07/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter07
12 |
13 |
14 |
15 | com.autumncode.books.hibernate
16 | util
17 |
18 |
19 | org.hibernate
20 | hibernate-c3p0
21 |
22 |
23 | org.hibernate
24 | hibernate-entitymanager
25 |
26 |
27 | org.projectlombok
28 | lombok
29 |
30 |
31 | com.mchange
32 | c3p0
33 |
34 |
35 | org.hibernate
36 | hibernate-validator
37 |
38 |
39 | org.hibernate
40 | hibernate-validator-cdi
41 |
42 |
43 | javax.el
44 | javax.el-api
45 |
46 |
47 | org.glassfish.web
48 | javax.el
49 |
50 |
51 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/lifecycle/FailingEntity.java:
--------------------------------------------------------------------------------
1 | package chapter07.lifecycle;
2 |
3 | import lombok.*;
4 |
5 | import javax.persistence.*;
6 |
7 | @Entity
8 | @ToString
9 | @NoArgsConstructor
10 | @Data
11 | @EqualsAndHashCode
12 | public class FailingEntity {
13 | @Id
14 | @GeneratedValue(strategy = GenerationType.AUTO)
15 | Integer id;
16 | FailureStatus failureStatus = null;
17 | String value;
18 |
19 | static enum FailureStatus {
20 | NOFAILURE, PREPERSIST, POSTPERSIST, POSTLOAD
21 | }
22 |
23 | @PrePersist
24 | void prePersist() {
25 | if (failureStatus.equals(FailureStatus.PREPERSIST)) {
26 | throw new RuntimeException("prepersist failure");
27 | }
28 | }
29 |
30 | @PostPersist
31 | void postPersist() {
32 | if (failureStatus.equals(FailureStatus.POSTPERSIST)) {
33 | throw new RuntimeException("postpersist failure");
34 | }
35 | }
36 |
37 | @PostLoad
38 | void postLoad() {
39 | if (failureStatus.equals(FailureStatus.POSTLOAD)) {
40 | throw new RuntimeException("postload failure");
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/lifecycle/LifecycleThing.java:
--------------------------------------------------------------------------------
1 | package chapter07.lifecycle;
2 |
3 | import lombok.Data;
4 | import org.jboss.logging.Logger;
5 |
6 | import javax.persistence.*;
7 | import java.util.BitSet;
8 |
9 | @Entity
10 | @Data
11 | public class LifecycleThing {
12 | static Logger logger = Logger.getLogger(LifecycleThing.class);
13 | static BitSet lifecycleCalls = new BitSet();
14 |
15 | @Id
16 | @GeneratedValue(strategy = GenerationType.AUTO)
17 | Integer id;
18 | @Column
19 | String name;
20 |
21 | @PostLoad
22 | public void postLoad() {
23 | log("postLoad", 0);
24 | }
25 |
26 | @PrePersist
27 | public void prePersist() {
28 | log("prePersist", 1);
29 | }
30 |
31 | @PostPersist
32 | public void postPersist() {
33 | log("postPersist", 2);
34 | }
35 |
36 | @PreUpdate
37 | public void preUpdate() {
38 | log("preUpdate", 3);
39 | }
40 |
41 | @PostUpdate
42 | public void postUpdate() {
43 | log("postUpdate", 4);
44 | }
45 |
46 | @PreRemove
47 | public void preRemove() {
48 | log("preRemove", 5);
49 | }
50 |
51 | @PostRemove
52 | public void postRemove() {
53 | log("postRemove", 6);
54 | }
55 |
56 | private void log(String method, int index) {
57 | lifecycleCalls.set(index, true);
58 | logger.errorf("%12s: %s (%s)", method, this.getClass().getSimpleName(), this.toString());
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/lifecycle/UserAccount.java:
--------------------------------------------------------------------------------
1 | package chapter07.lifecycle;
2 |
3 | import lombok.*;
4 |
5 | import javax.persistence.*;
6 |
7 | @Entity
8 | @NoArgsConstructor
9 | @Data
10 | @EntityListeners({UserAccountListener.class})
11 | public class UserAccount {
12 | @Id
13 | @GeneratedValue(strategy = GenerationType.AUTO)
14 | Integer id;
15 | String name;
16 | @Transient
17 | String password;
18 | Integer salt;
19 | Integer passwordHash;
20 |
21 | public boolean validPassword(String newPass) {
22 | return newPass.hashCode() * salt == getPasswordHash();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/lifecycle/UserAccountListener.java:
--------------------------------------------------------------------------------
1 | package chapter07.lifecycle;
2 |
3 | import javax.persistence.PrePersist;
4 |
5 | public class UserAccountListener {
6 | @PrePersist
7 | void setPasswordHash(Object o) {
8 | UserAccount ua = (UserAccount) o;
9 | if (ua.getSalt() == null || ua.getSalt() == 0) {
10 | ua.setSalt((int) (Math.random() * 65535));
11 | }
12 | ua.setPasswordHash(
13 | ua.getPassword().hashCode() * ua.getSalt()
14 | );
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/unvalidated/UnvalidatedSimplePerson.java:
--------------------------------------------------------------------------------
1 | package chapter07.unvalidated;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | public class UnvalidatedSimplePerson {
7 | @Id
8 | @GeneratedValue(strategy = GenerationType.IDENTITY)
9 | Long id;
10 | @Column
11 | String fname;
12 | @Column
13 | String lname;
14 | @Column
15 | Integer age;
16 |
17 | public Long getId() {
18 | return id;
19 | }
20 |
21 | public void setId(Long id) {
22 | this.id = id;
23 | }
24 |
25 | public String getFname() {
26 | return fname;
27 | }
28 |
29 | public void setFname(String fname) {
30 | this.fname = fname;
31 | }
32 |
33 | public String getLname() {
34 | return lname;
35 | }
36 |
37 | public void setLname(String lname) {
38 | this.lname = lname;
39 | }
40 |
41 | public Integer getAge() {
42 | return age;
43 | }
44 |
45 | public void setAge(Integer age) {
46 | this.age = age;
47 | }
48 |
49 | @Override
50 | public String toString() {
51 | return "(Unvalidated) ValidatedSimplePerson{" +
52 | "id=" + id +
53 | ", fname='" + fname + '\'' +
54 | ", lname='" + lname + '\'' +
55 | ", age=" + age +
56 | '}';
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/validated/Coordinate.java:
--------------------------------------------------------------------------------
1 | package chapter07.validated;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 |
8 | import javax.persistence.Entity;
9 | import javax.persistence.GeneratedValue;
10 | import javax.persistence.GenerationType;
11 | import javax.persistence.Id;
12 | import javax.validation.constraints.NotNull;
13 |
14 | @Entity
15 | @Data
16 | @Builder
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | @NoQuadrantIII
20 | public class Coordinate {
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.AUTO)
23 | Integer id;
24 | @NotNull
25 | Integer x;
26 | @NotNull
27 | Integer y;
28 | }
29 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/validated/NoQuadrantIII.java:
--------------------------------------------------------------------------------
1 | package chapter07.validated;
2 |
3 | import javax.validation.Constraint;
4 | import javax.validation.Payload;
5 | import java.lang.annotation.*;
6 |
7 | @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
8 | @Retention(RetentionPolicy.RUNTIME)
9 | @Constraint(validatedBy = {QuadrantIIIValidator.class})
10 | @Documented
11 | public @interface NoQuadrantIII {
12 | String message() default "Failed quadrant III test";
13 |
14 | Class>[] groups() default {};
15 |
16 | Class extends Payload>[] payload() default {};
17 | }
18 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/validated/QuadrantIIIValidator.java:
--------------------------------------------------------------------------------
1 | package chapter07.validated;
2 |
3 | import javax.validation.ConstraintValidator;
4 | import javax.validation.ConstraintValidatorContext;
5 |
6 | public class QuadrantIIIValidator implements ConstraintValidator {
7 | @Override
8 | public void initialize(NoQuadrantIII constraintAnnotation) {
9 | }
10 |
11 | @Override
12 | public boolean isValid(Coordinate value, ConstraintValidatorContext context) {
13 | return !(value.getX() < 0 && value.getY() < 0);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/chapter07/src/main/java/chapter07/validated/ValidatedSimplePerson.java:
--------------------------------------------------------------------------------
1 | package chapter07.validated;
2 |
3 | import lombok.*;
4 |
5 | import javax.persistence.*;
6 | import javax.validation.constraints.Min;
7 | import javax.validation.constraints.NotNull;
8 | import javax.validation.constraints.Size;
9 |
10 | @Entity
11 | @Data
12 | @Builder
13 | @AllArgsConstructor(access = AccessLevel.PACKAGE)
14 | @NoArgsConstructor
15 | public class ValidatedSimplePerson {
16 | @Id
17 | @GeneratedValue(strategy = GenerationType.IDENTITY)
18 | Long id;
19 | @Column
20 | @NotNull
21 | @Size(min = 2, max = 60)
22 | String fname;
23 | @Column
24 | @NotNull
25 | @Size(min = 2, max = 60)
26 | String lname;
27 | @Column
28 | @Min(value = 13)
29 | Integer age;
30 | }
31 |
--------------------------------------------------------------------------------
/chapter07/src/test/java/chapter07/lifecycle/ExternalListenerTest.java:
--------------------------------------------------------------------------------
1 | package chapter07.lifecycle;
2 |
3 | import com.autumncode.jpa.util.JPASessionUtil;
4 | import org.hibernate.Session;
5 | import org.hibernate.Transaction;
6 | import org.testng.annotations.Test;
7 |
8 | import java.util.Date;
9 |
10 | import static org.testng.Assert.assertEquals;
11 | import static org.testng.Assert.assertFalse;
12 | import static org.testng.Assert.assertTrue;
13 |
14 | public class ExternalListenerTest {
15 | @Test
16 | public void testExternalListener() {
17 | Integer id;
18 | String accountName = Long.toString(new Date().getTime());
19 | Session session = JPASessionUtil.getSession("chapter07");
20 | Transaction tx = session.beginTransaction();
21 | UserAccount ua = new UserAccount();
22 |
23 | ua.setName(accountName);
24 | ua.setPassword("foobar");
25 |
26 | session.persist(ua);
27 | id = ua.getId();
28 | tx.commit();
29 | session.close();
30 | session = JPASessionUtil.getSession("chapter07");
31 | //tx = session.beginTransaction();
32 | UserAccount ua2 = session
33 | .byId(UserAccount.class)
34 | .getReference(id);
35 | assertEquals(ua.getName(), ua2.getName());
36 | assertEquals(ua.getPasswordHash(), ua2.getPasswordHash());
37 |
38 | assertTrue(ua2.validPassword("foobar"));
39 | assertFalse(ua2.validPassword("barfoo"));
40 |
41 | //tx.commit();
42 | session.close();
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/chapter07/src/test/java/chapter07/lifecycle/LifecycleTest.java:
--------------------------------------------------------------------------------
1 | package chapter07.lifecycle;
2 |
3 | import com.autumncode.jpa.util.JPASessionUtil;
4 | import org.hibernate.Session;
5 | import org.hibernate.Transaction;
6 | import org.testng.Reporter;
7 | import org.testng.annotations.Test;
8 |
9 | import java.util.List;
10 |
11 | import static org.testng.Assert.*;
12 |
13 | public class LifecycleTest {
14 | @Test
15 | public void testLifecycle() {
16 | Integer id;
17 | LifecycleThing thing1, thing2, thing3;
18 | try (Session session = JPASessionUtil.getSession("chapter07")) {
19 | Transaction tx = session.beginTransaction();
20 | thing1 = new LifecycleThing();
21 | thing1.setName("Thing 1");
22 |
23 | session.save(thing1);
24 | id = thing1.getId();
25 | System.out.println(thing1);
26 | tx.commit();
27 | }
28 |
29 | try (Session session = JPASessionUtil.getSession("chapter07")) {
30 | Transaction tx = session.beginTransaction();
31 | thing2 = session
32 | .byId(LifecycleThing.class)
33 | .load(-1);
34 | assertNull(thing2);
35 |
36 | Reporter.log("attempted to load nonexistent reference");
37 |
38 | thing2 = session.byId(LifecycleThing.class)
39 | .getReference(id);
40 | assertNotNull(thing2);
41 | assertEquals(thing1, thing2);
42 |
43 | thing2.setName("Thing 2");
44 |
45 | tx.commit();
46 | }
47 | try (Session session = JPASessionUtil.getSession("chapter07")) {
48 | Transaction tx = session.beginTransaction();
49 |
50 | thing3 = session
51 | .byId(LifecycleThing.class)
52 | .getReference(id);
53 | assertNotNull(thing3);
54 | assertEquals(thing2, thing3);
55 |
56 | session.delete(thing3);
57 |
58 | tx.commit();
59 | }
60 | assertEquals(LifecycleThing.lifecycleCalls.nextClearBit(0), 7);
61 | }
62 |
63 | @Test
64 | public void persistenceErrorTests() {
65 | testPersistence("value1", FailingEntity.FailureStatus.NOFAILURE);
66 | testPersistence("value2", FailingEntity.FailureStatus.PREPERSIST);
67 | testPersistence("value3", FailingEntity.FailureStatus.POSTPERSIST);
68 | }
69 |
70 | @Test
71 | public void prepersistException() {
72 | Session session = JPASessionUtil.getSession("chapter07");
73 |
74 | Transaction tx = session.beginTransaction();
75 | session.createQuery("delete from FailingEntity").executeUpdate();
76 | tx.commit();
77 |
78 | tx = session.beginTransaction();
79 | FailingEntity fe = new FailingEntity();
80 | fe.setValue("FailingEntity");
81 | fe.setFailureStatus(FailingEntity.FailureStatus.PREPERSIST);
82 | try {
83 | session.persist(fe);
84 | } catch (Throwable ignored) {
85 | ignored.printStackTrace();
86 | }
87 | tx.rollback();
88 | session.close();
89 |
90 | session = JPASessionUtil.getSession("chapter07");
91 | tx = session.beginTransaction();
92 | List e = session.createQuery("from FailingEntity fe").list();
93 | System.out.println(e);
94 | tx.commit();
95 | session.close();
96 | }
97 |
98 | public void testPersistence(String value,
99 | FailingEntity.FailureStatus status) {
100 | Session session = JPASessionUtil.getSession("chapter07");
101 | Transaction tx = session.beginTransaction();
102 |
103 | FailingEntity failingEntity = new FailingEntity();
104 | failingEntity.setValue(value);
105 | failingEntity.setFailureStatus(status);
106 | try {
107 | session.persist(failingEntity);
108 | Integer id = failingEntity.getId();
109 | tx.commit();
110 | session.close();
111 | System.out.println(failingEntity);
112 | session = JPASessionUtil.getSession("chapter07");
113 | tx = session.beginTransaction();
114 | FailingEntity fe = session.load(FailingEntity.class, id);
115 | assertEquals(fe, failingEntity);
116 | session.delete(fe);
117 | tx.commit();
118 | session.close();
119 | } catch (RuntimeException exception) {
120 | if (FailingEntity.FailureStatus.NOFAILURE.equals(status)) {
121 | throw exception;
122 | }
123 | tx.rollback();
124 | session.close();
125 | }
126 | }
127 |
128 | @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "postload failure")
129 | public void testPostLoad() {
130 | Integer id;
131 | Session session = JPASessionUtil.getSession("chapter07");
132 | Transaction tx = session.beginTransaction();
133 |
134 | FailingEntity failingEntity = new FailingEntity();
135 | failingEntity.setValue("postload");
136 | failingEntity.setFailureStatus(FailingEntity.FailureStatus.POSTLOAD);
137 |
138 | session.persist(failingEntity);
139 | tx.commit();
140 | session.close();
141 |
142 | session = JPASessionUtil.getSession("chapter07");
143 | tx = session.beginTransaction();
144 | FailingEntity e = session
145 | .byId(FailingEntity.class)
146 | .load(failingEntity.getId());
147 | System.out.println(e);
148 | tx.commit();
149 | session.close();
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/chapter07/src/test/java/chapter07/validator/CoordinateTest.java:
--------------------------------------------------------------------------------
1 | package chapter07.validator;
2 |
3 | import chapter07.validated.Coordinate;
4 | import com.autumncode.hibernate.util.SessionUtil;
5 | import org.hibernate.Session;
6 | import org.hibernate.Transaction;
7 | import org.testng.annotations.DataProvider;
8 | import org.testng.annotations.Test;
9 |
10 | import javax.validation.ConstraintViolationException;
11 |
12 | import static org.testng.Assert.fail;
13 |
14 | public class CoordinateTest {
15 | private Coordinate persist(Coordinate entity) {
16 | try (Session session = SessionUtil.getSession()) {
17 | Transaction tx = session.beginTransaction();
18 | session.persist(entity);
19 | tx.commit();
20 | }
21 | return entity;
22 | }
23 |
24 | @DataProvider(name = "validCoordinates")
25 | private Object[][] validCoordinates() {
26 | return new Object[][]{
27 | {1, 1},
28 | {-1, 1},
29 | {1, -1},
30 | {0, 0},
31 | };
32 | }
33 |
34 | @Test(dataProvider = "validCoordinates")
35 | public void testValidCoordinate(Integer x, Integer y) {
36 | Coordinate c = Coordinate.builder().x(x).y(y).build();
37 | persist(c);
38 | // has passed validation, if we reach this point.
39 | }
40 |
41 | @Test(expectedExceptions = ConstraintViolationException.class)
42 | public void testInvalidCoordinate() {
43 | testValidCoordinate(-1, -1);
44 | fail("Should have gotten a constraint violation");
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/chapter07/src/test/java/chapter07/validator/ValidatorTest.java:
--------------------------------------------------------------------------------
1 | package chapter07.validator;
2 |
3 | import chapter07.unvalidated.UnvalidatedSimplePerson;
4 | import chapter07.validated.ValidatedSimplePerson;
5 | import com.autumncode.hibernate.util.SessionUtil;
6 | import org.hibernate.Session;
7 | import org.hibernate.Transaction;
8 | import org.testng.annotations.Test;
9 |
10 | import javax.validation.ConstraintViolationException;
11 |
12 | import static org.testng.Assert.fail;
13 |
14 | public class ValidatorTest {
15 | @Test
16 | public void createUnvalidatedUnderagePerson() {
17 | Long id = null;
18 | try (Session session = SessionUtil.getSession()) {
19 | Transaction transaction = session.beginTransaction();
20 |
21 | UnvalidatedSimplePerson person = new UnvalidatedSimplePerson();
22 | person.setAge(12); // underage for system
23 | person.setFname("Johnny");
24 | person.setLname("McYoungster");
25 |
26 | session.persist(person);
27 | id = person.getId();
28 | transaction.commit();
29 | }
30 | }
31 |
32 | @Test
33 | public void createValidPerson() {
34 | persist(ValidatedSimplePerson.builder()
35 | .age(15)
36 | .fname("Johnny")
37 | .lname("McYoungster").build());
38 | }
39 |
40 | @Test(expectedExceptions = ConstraintViolationException.class)
41 | public void createValidatedUnderagePerson() {
42 | persist(ValidatedSimplePerson.builder()
43 | .age(12)
44 | .fname("Johnny")
45 | .lname("McYoungster").build());
46 | fail("Should have failed validation");
47 | }
48 |
49 | @Test(expectedExceptions = ConstraintViolationException.class)
50 | public void createValidatedPoorFNamePerson2() {
51 | persist(ValidatedSimplePerson.builder()
52 | .age(14)
53 | .fname("J")
54 | .lname("McYoungster2").build());
55 | fail("Should have failed validation");
56 | }
57 |
58 | @Test(expectedExceptions = ConstraintViolationException.class)
59 | public void createValidatedNoFNamePerson() {
60 | persist(ValidatedSimplePerson.builder()
61 | .age(14)
62 | .lname("McYoungster2").build());
63 | fail("Should have failed validation");
64 | }
65 |
66 | private ValidatedSimplePerson persist(ValidatedSimplePerson person) {
67 | try (Session session = SessionUtil.getSession()) {
68 | Transaction tx = session.beginTransaction();
69 | session.persist(person);
70 | tx.commit();
71 | }
72 | return person;
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/chapter07/src/test/resources/META-INF/persistence.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 | chapter07.lifecycle.LifecycleThing
7 | chapter07.lifecycle.UserAccount
8 | chapter07.lifecycle.FailingEntity
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/chapter07/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db7
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 |
14 | 10
15 |
16 | true
17 |
18 | create
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/chapter08/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter08
12 |
13 |
14 |
15 | com.autumncode.books.hibernate
16 | util
17 |
18 |
19 | org.hibernate
20 | hibernate-c3p0
21 |
22 |
23 | org.hibernate
24 | hibernate-entitymanager
25 |
26 |
27 | org.projectlombok
28 | lombok
29 |
30 |
31 | com.mchange
32 | c3p0
33 |
34 |
35 | org.hibernate
36 | hibernate-ehcache
37 |
38 |
39 | org.slf4j
40 | slf4j-api
41 |
42 |
43 |
44 |
45 | org.slf4j
46 | slf4j-api
47 |
48 |
49 | org.ehcache
50 | ehcache
51 | 3.5.2
52 |
53 |
54 |
--------------------------------------------------------------------------------
/chapter08/src/main/java/chapter08/model/Publisher.java:
--------------------------------------------------------------------------------
1 | package chapter08.model;
2 |
3 | import lombok.Data;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 |
10 | @Entity
11 | @Data
12 | public class Publisher {
13 | @Id
14 | @GeneratedValue(strategy = GenerationType.AUTO)
15 | Long id;
16 | String name;
17 | }
18 |
--------------------------------------------------------------------------------
/chapter08/src/main/java/chapter08/model/Subscriber.java:
--------------------------------------------------------------------------------
1 | package chapter08.model;
2 |
3 | import lombok.Data;
4 |
5 | import javax.persistence.Entity;
6 | import javax.persistence.GeneratedValue;
7 | import javax.persistence.GenerationType;
8 | import javax.persistence.Id;
9 |
10 | @Entity
11 | @Data
12 | public class Subscriber {
13 | @Id
14 | @GeneratedValue(strategy = GenerationType.AUTO)
15 | Long id;
16 | String name;
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/chapter08/src/main/java/chapter08/model/Supplier.java:
--------------------------------------------------------------------------------
1 | package chapter08.model;
2 |
3 | import org.hibernate.annotations.Cache;
4 | import org.hibernate.annotations.CacheConcurrencyStrategy;
5 |
6 | import javax.persistence.*;
7 | import java.io.Serializable;
8 |
9 | @Entity
10 | @Cacheable
11 | @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
12 | public class Supplier implements Serializable {
13 | @Id
14 | @GeneratedValue(strategy = GenerationType.AUTO)
15 | Integer id;
16 | @Column(unique = true)
17 | String name;
18 |
19 | public Supplier(String name) {
20 | this.name = name;
21 | }
22 |
23 | public Supplier() {
24 | }
25 |
26 | public Integer getId() {
27 | return id;
28 | }
29 |
30 | public void setId(Integer id) {
31 | this.id = id;
32 | }
33 |
34 | public String getName() {
35 | return name;
36 | }
37 |
38 | public void setName(String name) {
39 | this.name = name;
40 | }
41 |
42 | @Override
43 | public boolean equals(Object o) {
44 | if (this == o) return true;
45 | if (!(o instanceof Supplier)) return false;
46 |
47 | Supplier supplier = (Supplier) o;
48 |
49 | if (id != null ? !id.equals(supplier.id) : supplier.id != null) return false;
50 | return name.equals(supplier.name);
51 |
52 | }
53 |
54 | @Override
55 | public int hashCode() {
56 | int result = id != null ? id.hashCode() : 0;
57 | result = 31 * result + name.hashCode();
58 | return result;
59 | }
60 |
61 | @Override
62 | public String toString() {
63 | final StringBuilder sb = new StringBuilder("Supplier{");
64 | sb.append("id=").append(id);
65 | sb.append(", name='").append(name).append('\'');
66 | sb.append('}');
67 | return sb.toString();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/chapter08/src/test/java/chapter08/QueryTest.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import chapter08.model.Supplier;
4 | import com.autumncode.hibernate.util.SessionUtil;
5 | import org.hibernate.Session;
6 | import org.hibernate.Transaction;
7 | import org.testng.annotations.AfterMethod;
8 | import org.testng.annotations.BeforeMethod;
9 | import org.testng.annotations.Test;
10 |
11 | public class QueryTest {
12 | @BeforeMethod
13 | public void populateData() {
14 | Session session = SessionUtil.getSession();
15 | Transaction tx = session.beginTransaction();
16 |
17 | Supplier supplier = new Supplier("Hardware, Inc.");
18 | session.save(supplier);
19 |
20 | supplier = new Supplier("Supplier 2");
21 |
22 | session.save(supplier);
23 | tx.commit();
24 | session.close();
25 | }
26 |
27 | @AfterMethod
28 | public void closeSession() {
29 | Session session = SessionUtil.getSession();
30 | Transaction tx = session.beginTransaction();
31 |
32 | session.createQuery("delete from Supplier").executeUpdate();
33 | tx.commit();
34 | session.close();
35 | }
36 |
37 | @Test
38 | public void testSuppliers() {
39 | Session session = SessionUtil.getSession();
40 | Transaction tx = session.beginTransaction();
41 |
42 | Supplier supplier = session.byId(Supplier.class).load(1);
43 | tx.commit();
44 | session.close();
45 |
46 | session = SessionUtil.getSession();
47 | tx = session.beginTransaction();
48 |
49 | supplier = session.byId(Supplier.class).load(1);
50 |
51 | tx.commit();
52 | session.close();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/chapter08/src/test/java/chapter08/TransactionExample.java:
--------------------------------------------------------------------------------
1 | package chapter08;
2 |
3 | import chapter08.model.Publisher;
4 | import com.autumncode.hibernate.util.SessionUtil;
5 | import org.hibernate.*;
6 | import org.hibernate.boot.MetadataSources;
7 | import org.hibernate.boot.registry.StandardServiceRegistry;
8 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9 | import org.hibernate.query.Query;
10 | import org.testng.annotations.Test;
11 |
12 | import java.util.concurrent.ExecutorService;
13 | import java.util.concurrent.Executors;
14 | import java.util.concurrent.TimeUnit;
15 | import java.util.stream.Collectors;
16 |
17 | import static org.testng.Assert.assertEquals;
18 |
19 | public class TransactionExample {
20 | // note lack of @Test annotation
21 | public void thisIsNotATest() {
22 | try (Session session = SessionUtil.getSession()) {
23 | Transaction tx = null;
24 | try {
25 | tx = session.beginTransaction();
26 | // normal session usage here
27 |
28 | tx.commit();
29 | } catch (HibernateException e) {
30 | if (tx != null && tx.isActive()) {
31 | tx.rollback();
32 | }
33 | }
34 | }
35 | }
36 |
37 | @Test
38 | public void demonstrateRollback() {
39 | try (Session session = SessionUtil.getSession()) {
40 | Transaction tx = session.beginTransaction();
41 | Query query = session.createQuery("delete from Publisher");
42 | query.executeUpdate();
43 | tx.commit();
44 | }
45 | try (Session session = SessionUtil.getSession()) {
46 | Query query = session.createQuery("from Publisher", Publisher.class);
47 | assertEquals(query.list().size(), 0);
48 | }
49 | try (Session session = SessionUtil.getSession()) {
50 | Transaction tx = session.beginTransaction();
51 | Publisher publisher = new Publisher();
52 | publisher.setName("foo");
53 | session.save(publisher);
54 | // tx.rollback();
55 | }
56 | try (Session session = SessionUtil.getSession()) {
57 | Query query = session.createQuery("from Publisher", Publisher.class);
58 | assertEquals(query.list().size(), 0);
59 | }
60 | }
61 |
62 | @Test
63 | public void showDeadlock() throws InterruptedException {
64 | Long publisherAId;
65 | Long publisherBId;
66 |
67 | //clear out old data and populate tables
68 | try (Session session = SessionUtil.getSession()) {
69 | Transaction tx = session.beginTransaction();
70 | session.createQuery("delete from Publisher").executeUpdate();
71 |
72 | Publisher publisher = new Publisher();
73 | publisher.setName("A");
74 | session.save(publisher);
75 | publisherAId = publisher.getId();
76 |
77 | publisher = new Publisher();
78 | publisher.setName("B");
79 | session.save(publisher);
80 | publisherBId = publisher.getId();
81 | tx.commit();
82 | }
83 |
84 | ExecutorService executor = Executors.newFixedThreadPool(2);
85 | executor.submit(() -> updatePublishers("session1", publisherAId, publisherBId));
86 | executor.submit(() -> updatePublishers("session2", publisherBId, publisherAId));
87 | executor.shutdown();
88 |
89 | if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
90 | executor.shutdownNow();
91 | if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
92 | System.out.println("Executor did not terminate");
93 | }
94 | }
95 | try (Session session = SessionUtil.getSession()) {
96 | Query query = session.createQuery("from Publisher p order by p.name", Publisher.class);
97 | String result = query.list().stream().map(Publisher::getName).collect(Collectors.joining(","));
98 | assertEquals(result, "A,B");
99 | }
100 | }
101 |
102 | private void updatePublishers(String prefix, Long... ids) {
103 | try (Session session = SessionUtil.getSession()) {
104 | Transaction tx = session.beginTransaction();
105 | for (Long id : ids) {
106 | Thread.sleep(100);
107 | Publisher publisher = session
108 | .byId(Publisher.class)
109 | .load(id);
110 | publisher.setName(prefix + " " + publisher.getName());
111 | }
112 | tx.commit();
113 | } catch (InterruptedException | PessimisticLockException e) {
114 | e.printStackTrace();
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/chapter08/src/test/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.h2.Driver
9 | jdbc:h2:./db8
10 | sa
11 |
12 | org.hibernate.dialect.H2Dialect
13 | true
14 | true
15 | chapter08
16 |
17 | org.hibernate.cache.ehcache.EhCacheRegionFactory
18 |
19 |
20 |
21 | 10
22 |
23 | true
24 | true
25 |
26 |
27 | create-drop
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/chapter09/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | hibernate-parent
7 | com.autumncode.books.hibernate
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 | chapter09
12 |
13 |
14 |
15 | com.autumncode.books.hibernate
16 | util
17 |
18 |
19 | org.hibernate
20 | hibernate-c3p0
21 |
22 |
23 | org.hibernate
24 | hibernate-entitymanager
25 |
26 |
27 | org.projectlombok
28 | lombok
29 |
30 |
31 | com.mchange
32 | c3p0
33 |
34 |
35 | org.hibernate
36 | hibernate-validator
37 |
38 |
39 | org.hibernate
40 | hibernate-validator-cdi
41 |
42 |
43 | javax.el
44 | javax.el-api
45 |
46 |
47 | org.glassfish.web
48 | javax.el
49 |
50 |
51 |
--------------------------------------------------------------------------------
/chapter09/src/main/java/chapter09/model/Product.java:
--------------------------------------------------------------------------------
1 | package chapter09.model;
2 |
3 | import javax.persistence.*;
4 | import javax.validation.constraints.NotNull;
5 | import java.io.Serializable;
6 |
7 | @Entity
8 | @Inheritance(strategy = InheritanceType.JOINED)
9 | @NamedQueries({
10 | @NamedQuery(name = "product.searchByPhrase",
11 | query = "from Product p "
12 | + "where p.name like :text or p.description like :text"),
13 | @NamedQuery(name = "product.findProductAndSupplier",
14 | query = "from Product p inner join p.supplier as s"),
15 | })
16 | public class Product implements Serializable {
17 | @Id
18 | @GeneratedValue(strategy = GenerationType.AUTO)
19 | Integer id;
20 | @ManyToOne(optional = false, fetch = FetchType.LAZY)
21 | Supplier supplier;
22 | @Column
23 | @NotNull
24 | String name;
25 | @Column
26 | @NotNull
27 | String description;
28 | @Column
29 | @NotNull
30 | Double price;
31 |
32 | public Product() {
33 | }
34 |
35 | public Product(Supplier supplier, String name, String description, Double price) {
36 | this.supplier = supplier;
37 | this.name = name;
38 | this.description = description;
39 | this.price = price;
40 | }
41 |
42 | public Integer getId() {
43 | return id;
44 | }
45 |
46 | public void setId(Integer id) {
47 | this.id = id;
48 | }
49 |
50 | public Supplier getSupplier() {
51 | return supplier;
52 | }
53 |
54 | public void setSupplier(Supplier supplier) {
55 | this.supplier = supplier;
56 | }
57 |
58 | public String getName() {
59 | return name;
60 | }
61 |
62 | public void setName(String name) {
63 | this.name = name;
64 | }
65 |
66 | public String getDescription() {
67 | return description;
68 | }
69 |
70 | public void setDescription(String description) {
71 | this.description = description;
72 | }
73 |
74 | public Double getPrice() {
75 | return price;
76 | }
77 |
78 | public void setPrice(Double price) {
79 | this.price = price;
80 | }
81 |
82 | @Override
83 | public boolean equals(Object o) {
84 | if (this == o) return true;
85 | if (!(o instanceof Product)) return false;
86 |
87 | Product product = (Product) o;
88 |
89 | if (!description.equals(product.description)) return false;
90 | if (id != null ? !id.equals(product.id) : product.id != null) return false;
91 | if (!name.equals(product.name)) return false;
92 | if (!price.equals(product.price)) return false;
93 | return supplier.equals(product.supplier);
94 |
95 | }
96 |
97 | @Override
98 | public int hashCode() {
99 | int result = id != null ? id.hashCode() : 0;
100 | result = 31 * result + supplier.hashCode();
101 | result = 31 * result + name.hashCode();
102 | result = 31 * result + description.hashCode();
103 | result = 31 * result + price.hashCode();
104 | return result;
105 | }
106 |
107 | @Override
108 | public String toString() {
109 | final StringBuilder sb = new StringBuilder("Product{");
110 | sb.append("id=").append(id);
111 | sb.append(", supplier='").append(supplier.getName());
112 | sb.append("', name='").append(name).append('\'');
113 | sb.append(", description='").append(description).append('\'');
114 | sb.append(", price=").append(price);
115 | sb.append('}');
116 | return sb.toString();
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/chapter09/src/main/java/chapter09/model/Software.java:
--------------------------------------------------------------------------------
1 | package chapter09.model;
2 |
3 |
4 | import javax.persistence.Column;
5 | import javax.persistence.Entity;
6 | import javax.validation.constraints.NotNull;
7 | import java.io.Serializable;
8 |
9 | @Entity
10 | public class Software extends Product implements Serializable {
11 | @Column
12 | @NotNull
13 | String version;
14 |
15 | public Software() {
16 | }
17 |
18 | public Software(Supplier supplier, String name, String description, Double price, String version) {
19 | super(supplier, name, description, price);
20 | this.version = version;
21 | }
22 |
23 | public String getVersion() {
24 | return version;
25 | }
26 |
27 | public void setVersion(String version) {
28 | this.version = version;
29 | }
30 |
31 | @Override
32 | public boolean equals(Object o) {
33 | if (this == o) return true;
34 | if (!(o instanceof Software)) return false;
35 | if (!super.equals(o)) return false;
36 |
37 | Software software = (Software) o;
38 |
39 | return version.equals(software.version);
40 |
41 | }
42 |
43 | @Override
44 | public int hashCode() {
45 | int result = super.hashCode();
46 | result = 31 * result + version.hashCode();
47 | return result;
48 | }
49 |
50 | @Override
51 | public String toString() {
52 | final StringBuilder sb = new StringBuilder(super.toString());
53 | sb.append(":Software{");
54 | sb.append('}');
55 | return sb.toString();
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/chapter09/src/main/java/chapter09/model/Supplier.java:
--------------------------------------------------------------------------------
1 | package chapter09.model;
2 |
3 | import javax.persistence.*;
4 | import javax.validation.constraints.NotNull;
5 | import java.io.Serializable;
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | @Entity
10 | @NamedQueries({
11 | @NamedQuery(name = "supplier.findAll", query = "from Supplier s"),
12 | @NamedQuery(name = "supplier.findByName",
13 | query = "from Supplier s where s.name=:name"),
14 | })
15 | @NamedNativeQueries({
16 | @NamedNativeQuery(name = "supplier.findAverage",
17 | query = "SELECT p.supplier_id, avg(p.price) "
18 | + "FROM Product p GROUP BY p.supplier_id"
19 | )
20 | })
21 | public class Supplier implements Serializable {
22 | @Id
23 | @GeneratedValue(strategy = GenerationType.AUTO)
24 | Integer id;
25 | @Column(unique = true)
26 | @NotNull
27 | String name;
28 | @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true,
29 | mappedBy = "supplier", targetEntity = Product.class)
30 | List products = new ArrayList<>();
31 |
32 | public Supplier(String name) {
33 | this.name = name;
34 | }
35 |
36 | public Supplier() {
37 | }
38 |
39 | public Integer getId() {
40 | return id;
41 | }
42 |
43 | public void setId(Integer id) {
44 | this.id = id;
45 | }
46 |
47 | public String getName() {
48 | return name;
49 | }
50 |
51 | public void setName(String name) {
52 | this.name = name;
53 | }
54 |
55 | public List getProducts() {
56 | return products;
57 | }
58 |
59 | public void setProducts(List products) {
60 | this.products = products;
61 | }
62 |
63 | @Override
64 | public boolean equals(Object o) {
65 | if (this == o) return true;
66 | if (!(o instanceof Supplier)) return false;
67 |
68 | Supplier supplier = (Supplier) o;
69 |
70 | if (id != null ? !id.equals(supplier.id) : supplier.id != null) return false;
71 | return name.equals(supplier.name);
72 |
73 | }
74 |
75 | @Override
76 | public int hashCode() {
77 | int result = id != null ? id.hashCode() : 0;
78 | result = 31 * result + name.hashCode();
79 | return result;
80 | }
81 |
82 | @Override
83 | public String toString() {
84 | final StringBuilder sb = new StringBuilder("Supplier{");
85 | sb.append("id=").append(id);
86 | sb.append(", name='").append(name).append('\'');
87 | sb.append(", products=").append(products);
88 | sb.append('}');
89 | return sb.toString();
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/chapter09/src/test/java/chapter09/DeleteHQLTest.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import chapter09.model.Product;
4 | import chapter09.model.Supplier;
5 | import com.autumncode.hibernate.util.SessionUtil;
6 | import org.hibernate.query.Query;
7 | import org.hibernate.Session;
8 | import org.hibernate.Transaction;
9 | import org.testng.annotations.Test;
10 |
11 | import java.util.List;
12 |
13 | import static org.testng.Assert.assertEquals;
14 |
15 | public class DeleteHQLTest {
16 | @Test
17 | public void testDeleteHQL() {
18 | try (Session session = SessionUtil.getSession()) {
19 | Transaction tx = session.beginTransaction();
20 | session.createQuery("delete from Supplier").executeUpdate();
21 | // create a set of suppliers, then delete them
22 | Supplier supplier = new Supplier("DSupplier 1");
23 | session.save(supplier);
24 | supplier.getProducts().add(
25 | new Product(supplier, "foo", "bar", 10.00)
26 | );
27 |
28 | session.save(new Supplier("DSupplier 2"));
29 | tx.commit();
30 |
31 | tx = session.beginTransaction();
32 | Query queryAll = session.createQuery("from Supplier",
33 | Supplier.class);
34 | queryAll.setReadOnly(true);
35 | List suppliers = queryAll.list();
36 | for (Supplier s : suppliers) {
37 | System.out.println(s);
38 | }
39 | assertEquals(suppliers.size(), 2);
40 |
41 | session.createQuery("delete from Product").executeUpdate();
42 |
43 | Query deleteAll = session.createQuery("delete from Supplier");
44 | deleteAll.executeUpdate();
45 | tx.commit();
46 | assertEquals(queryAll.list().size(), 0);
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/chapter09/src/test/java/chapter09/PaginationTest.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import chapter09.model.Supplier;
4 | import com.autumncode.hibernate.util.SessionUtil;
5 | import org.hibernate.Session;
6 | import org.hibernate.Transaction;
7 | import org.hibernate.query.Query;
8 | import org.testng.annotations.Test;
9 |
10 | import java.util.List;
11 | import java.util.stream.Collectors;
12 |
13 | import static org.testng.Assert.assertEquals;
14 |
15 | public class PaginationTest {
16 | @Test
17 | public void testPagination() {
18 | try (Session session = SessionUtil.getSession()) {
19 | Transaction tx = session.beginTransaction();
20 | session.createQuery("delete from Product").executeUpdate();
21 | session.createQuery("delete from Supplier").executeUpdate();
22 |
23 | for (int i = 0; i < 30; i++) {
24 | Supplier supplier = new Supplier();
25 | supplier.setName(String.format("supplier %02d", i));
26 | session.save(supplier);
27 | }
28 |
29 | tx.commit();
30 | }
31 |
32 | try (Session session = SessionUtil.getSession()) {
33 | Query query = session.createQuery("select s.name from Supplier s order by s.name", String.class);
34 | query.setFirstResult(5);
35 | query.setMaxResults(5);
36 | List suppliers = query.list();
37 | String list = suppliers
38 | .stream()
39 | .collect(Collectors.joining(","));
40 | assertEquals(list, "supplier 05,supplier 06,supplier 07,supplier 08,supplier 09");
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/chapter09/src/test/java/chapter09/QueryTest.java:
--------------------------------------------------------------------------------
1 | package chapter09;
2 |
3 | import chapter09.model.Product;
4 | import chapter09.model.Software;
5 | import chapter09.model.Supplier;
6 | import com.autumncode.hibernate.util.SessionUtil;
7 | import org.hibernate.Session;
8 | import org.hibernate.Transaction;
9 | import org.hibernate.query.Query;
10 | import org.testng.Assert;
11 | import org.testng.annotations.AfterMethod;
12 | import org.testng.annotations.BeforeMethod;
13 | import org.testng.annotations.DataProvider;
14 | import org.testng.annotations.Test;
15 |
16 | import java.util.Arrays;
17 | import java.util.List;
18 |
19 | import static org.testng.Assert.assertEquals;
20 |
21 | public class QueryTest {
22 | Session session;
23 | Transaction tx;
24 |
25 | @BeforeMethod
26 | public void populateData() {
27 | try(Session session = SessionUtil.getSession()) {
28 | Transaction tx = session.beginTransaction();
29 |
30 | Supplier supplier = new Supplier("Hardware, Inc.");
31 | supplier.getProducts().add(
32 | new Product(supplier, "Optical Wheel Mouse", "Mouse", 5.00));
33 | supplier.getProducts().add(
34 | new Product(supplier, "Trackball Mouse", "Mouse", 22.00));
35 | session.save(supplier);
36 |
37 | supplier = new Supplier("Supplier 2");
38 | supplier.getProducts().add(
39 | new Software(supplier, "SuperDetect", "Antivirus", 14.95, "1.0"));
40 | supplier.getProducts().add(
41 | new Software(supplier, "Wildcat", "Browser", 19.95, "2.2"));
42 | supplier.getProducts().add(
43 | new Product(supplier, "AxeGrinder", "Gaming Mouse", 42.00));
44 |
45 | session.save(supplier);
46 | tx.commit();
47 | }
48 |
49 | this.session = SessionUtil.getSession();
50 | this.tx = this.session.beginTransaction();
51 | }
52 |
53 | @AfterMethod
54 | public void closeSession() {
55 | session.createQuery("delete from Product").executeUpdate();
56 | session.createQuery("delete from Supplier").executeUpdate();
57 | if (tx.isActive()) {
58 | tx.commit();
59 | }
60 | if (session.isOpen()) {
61 | session.close();
62 | }
63 | }
64 |
65 | @Test
66 | public void testNamedQuery() {
67 | Query query = session.getNamedQuery("supplier.findAll");
68 | List suppliers = query.list();
69 | assertEquals(suppliers.size(), 2);
70 | }
71 | @Test
72 | public void testJoin() {
73 | Query