├── .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 | ![Cover image](9781484223185.jpg) 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[] 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 query = session.getNamedQuery("product.findProductAndSupplier"); 74 | List suppliers = query.list(); 75 | for(Object[] o:suppliers) { 76 | Assert.assertTrue(o[0] instanceof Product); 77 | Assert.assertTrue(o[1] instanceof Supplier); 78 | } 79 | assertEquals(suppliers.size(), 5); 80 | } 81 | @Test 82 | public void testSimpleQuery() { 83 | Query query = session.createQuery("from Product", Product.class); 84 | 85 | query.setComment("This is only a query for product"); 86 | List products = query.list(); 87 | assertEquals(products.size(), 5); 88 | } 89 | 90 | @Test 91 | public void testSimpleProjection() { 92 | Query query = session.createQuery("select p.name from Product p", String.class); 93 | List suppliers = query.list(); 94 | for(String s:suppliers) { 95 | System.out.println(s); 96 | } 97 | assertEquals(suppliers.size(), 5); 98 | } 99 | 100 | @Test 101 | public void testProjection() { 102 | Query query = session.getNamedQuery("supplier.findAverage"); 103 | List suppliers = query.list(); 104 | for (Object[] o : suppliers) { 105 | System.out.println(Arrays.toString(o)); 106 | } 107 | assertEquals(suppliers.size(), 2); 108 | } 109 | 110 | @Test 111 | public void testLikeQuery() { 112 | Query query = session.createQuery( 113 | "from Product p " 114 | + " where p.price > :minprice" 115 | + " and p.description like :desc", Product.class); 116 | query.setParameter("desc", "Mou%"); 117 | query.setParameter("minprice", 15.0); 118 | List products = query.list(); 119 | assertEquals(products.size(), 1); 120 | } 121 | 122 | @DataProvider 123 | Object[][] queryTypesProvider() { 124 | return new Object[][]{ 125 | {"Supplier", 2}, 126 | {"Product", 5}, 127 | {"Software", 2}, 128 | }; 129 | } 130 | 131 | @Test(dataProvider = "queryTypesProvider") 132 | public void testQueryTypes(String type, Integer count) { 133 | Query query = session.createQuery("from " + type); 134 | List list = query.list(); 135 | assertEquals(list.size(), count.intValue()); 136 | } 137 | 138 | @Test 139 | public void searchForProduct() { 140 | Query query = session.getNamedQuery("product.searchByPhrase"); 141 | query.setParameter("text", "%Mou%"); 142 | List products = query.list(); 143 | assertEquals(products.size(), 3); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /chapter09/src/test/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | org.h2.Driver 9 | jdbc:h2:./db9 10 | sa 11 | 12 | org.hibernate.dialect.H2Dialect 13 | 14 | 10 15 | 16 | true 17 | true 18 | 19 | 20 | create-drop 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /chapter10/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | hibernate-parent 7 | com.autumncode.books.hibernate 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | chapter10 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 | org.hibernate 52 | hibernate-jpamodelgen 53 | ${hibernate-core.version} 54 | 55 | 56 | -------------------------------------------------------------------------------- /chapter10/src/main/java/chapter10/model/Product.java: -------------------------------------------------------------------------------- 1 | package chapter10.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 | Integer vseion; 33 | 34 | public Product() { 35 | } 36 | 37 | public Product(Supplier supplier, String name, String description, Double price) { 38 | this.supplier = supplier; 39 | this.name = name; 40 | this.description = description; 41 | this.price = price; 42 | } 43 | 44 | public Integer getId() { 45 | return id; 46 | } 47 | 48 | public void setId(Integer id) { 49 | this.id = id; 50 | } 51 | 52 | public Supplier getSupplier() { 53 | return supplier; 54 | } 55 | 56 | public void setSupplier(Supplier supplier) { 57 | this.supplier = supplier; 58 | } 59 | 60 | public String getName() { 61 | return name; 62 | } 63 | 64 | public void setName(String name) { 65 | this.name = name; 66 | } 67 | 68 | public String getDescription() { 69 | return description; 70 | } 71 | 72 | public void setDescription(String description) { 73 | this.description = description; 74 | } 75 | 76 | public Double getPrice() { 77 | return price; 78 | } 79 | 80 | public void setPrice(Double price) { 81 | this.price = price; 82 | } 83 | 84 | @Override 85 | public boolean equals(Object o) { 86 | if (this == o) return true; 87 | if (!(o instanceof Product)) return false; 88 | 89 | Product product = (Product) o; 90 | 91 | if (!description.equals(product.description)) return false; 92 | if (id != null ? !id.equals(product.id) : product.id != null) return false; 93 | if (!name.equals(product.name)) return false; 94 | if (!price.equals(product.price)) return false; 95 | return supplier.equals(product.supplier); 96 | 97 | } 98 | 99 | @Override 100 | public int hashCode() { 101 | int result = id != null ? id.hashCode() : 0; 102 | result = 31 * result + supplier.hashCode(); 103 | result = 31 * result + name.hashCode(); 104 | result = 31 * result + description.hashCode(); 105 | result = 31 * result + price.hashCode(); 106 | return result; 107 | } 108 | 109 | @Override 110 | public String toString() { 111 | final StringBuilder sb = new StringBuilder("Product{"); 112 | sb.append("id=").append(id); 113 | sb.append(", supplier='").append(supplier.getName()); 114 | sb.append("', name='").append(name).append('\''); 115 | sb.append(", description='").append(description).append('\''); 116 | sb.append(", price=").append(price); 117 | sb.append('}'); 118 | return sb.toString(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /chapter10/src/main/java/chapter10/model/Software.java: -------------------------------------------------------------------------------- 1 | package chapter10.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 | -------------------------------------------------------------------------------- /chapter10/src/main/java/chapter10/model/Supplier.java: -------------------------------------------------------------------------------- 1 | package chapter10.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 | public class Supplier implements Serializable { 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.AUTO) 13 | Integer id; 14 | @Column(unique = true) 15 | @NotNull 16 | String name; 17 | @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, 18 | mappedBy = "supplier", targetEntity = Product.class) 19 | List products = new ArrayList<>(); 20 | 21 | public Supplier(String name) { 22 | this.name = name; 23 | } 24 | 25 | public Supplier() { 26 | } 27 | 28 | public Integer getId() { 29 | return id; 30 | } 31 | 32 | public void setId(Integer id) { 33 | this.id = id; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | 44 | public List getProducts() { 45 | return products; 46 | } 47 | 48 | public void setProducts(List products) { 49 | this.products = products; 50 | } 51 | 52 | @Override 53 | public boolean equals(Object o) { 54 | if (this == o) return true; 55 | if (!(o instanceof Supplier)) return false; 56 | 57 | Supplier supplier = (Supplier) o; 58 | 59 | if (id != null ? !id.equals(supplier.id) : supplier.id != null) return false; 60 | return name.equals(supplier.name); 61 | 62 | } 63 | 64 | @Override 65 | public int hashCode() { 66 | int result = id != null ? id.hashCode() : 0; 67 | result = 31 * result + name.hashCode(); 68 | return result; 69 | } 70 | 71 | @Override 72 | public String toString() { 73 | final StringBuilder sb = new StringBuilder("Supplier{"); 74 | sb.append("id=").append(id); 75 | sb.append(", name='").append(name).append('\''); 76 | sb.append(", products=").append(products); 77 | sb.append('}'); 78 | return sb.toString(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /chapter10/src/test/java/chapter10/SupplierResult.java: -------------------------------------------------------------------------------- 1 | package chapter10; 2 | 3 | class SupplierResult { 4 | String name; 5 | long count; 6 | 7 | public SupplierResult(String name, Long count) { 8 | this.name = name; 9 | this.count = count; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | final StringBuilder sb = new StringBuilder("SupplierResult{"); 15 | sb.append("name='").append(name).append('\''); 16 | sb.append(", count=").append(count); 17 | sb.append('}'); 18 | return sb.toString(); 19 | } 20 | } -------------------------------------------------------------------------------- /chapter10/src/test/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | chapter10.model.Product 8 | chapter10.model.Supplier 9 | chapter10.model.Software 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /chapter11/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | hibernate-parent 7 | com.autumncode.books.hibernate 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | chapter11 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 | -------------------------------------------------------------------------------- /chapter11/src/main/java/chapter11/model/User.java: -------------------------------------------------------------------------------- 1 | package chapter11.model; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import org.hibernate.annotations.*; 6 | 7 | import javax.persistence.*; 8 | import javax.persistence.Entity; 9 | import java.util.Arrays; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | @Entity 14 | @Data 15 | @NoArgsConstructor 16 | @FilterDefs({ 17 | @FilterDef(name = "byStatus", parameters = @ParamDef(name = "status", type = "boolean")), 18 | @FilterDef(name = "byGroup", parameters = @ParamDef(name = "group", type = "string")), 19 | @FilterDef(name = "userEndsWith1") 20 | }) 21 | @Filters({ 22 | @Filter(name = "byStatus", condition = "active = :status"), 23 | @Filter(name = "byGroup", condition = ":group in ( select ug.groups from user_groups ug where ug.user_id = id)"), 24 | @Filter(name = "userEndsWith1", condition = "name like '%1'") 25 | }) 26 | public class User { 27 | @Id 28 | @GeneratedValue(strategy = GenerationType.AUTO) 29 | Integer id; 30 | @Column(unique = true) 31 | String name; 32 | boolean active; 33 | @ElementCollection 34 | Set groups; 35 | 36 | public User(String name, boolean active) { 37 | this.name=name; 38 | this.active=active; 39 | } 40 | 41 | public void addGroups(String... groupSet) { 42 | if (getGroups() == null) { 43 | setGroups(new HashSet<>()); 44 | } 45 | getGroups().addAll(Arrays.asList(groupSet)); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /chapter11/src/main/java/chapter11/userrole/Role1.java: -------------------------------------------------------------------------------- 1 | package chapter11.userrole; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import org.hibernate.annotations.*; 6 | 7 | import javax.persistence.*; 8 | import javax.persistence.Entity; 9 | import java.util.Arrays; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | @Entity 14 | @Data 15 | @NoArgsConstructor 16 | 17 | public class Role1 { 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.AUTO) 20 | Integer id; 21 | @Column(unique = true) 22 | String name; 23 | 24 | public Role1(String name) { 25 | this.name=name; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter11/src/main/java/chapter11/userrole/User1.java: -------------------------------------------------------------------------------- 1 | package chapter11.userrole; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import org.hibernate.annotations.*; 6 | 7 | import javax.persistence.*; 8 | import javax.persistence.Entity; 9 | import java.util.Arrays; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | @Entity 14 | @Data 15 | @NoArgsConstructor 16 | public class User1 { 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.AUTO) 19 | Integer id; 20 | @Column(unique = true) 21 | String name; 22 | boolean active; 23 | @ManyToMany 24 | Set roles; 25 | 26 | public User1(String name, boolean active) { 27 | this.name=name; 28 | this.active=active; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /chapter11/src/test/java/chapter11/FilterTests.java: -------------------------------------------------------------------------------- 1 | package chapter11; 2 | 3 | import chapter11.model.User; 4 | import com.autumncode.hibernate.util.SessionUtil; 5 | import org.hibernate.query.Query; 6 | import org.testng.annotations.AfterMethod; 7 | import org.testng.annotations.BeforeMethod; 8 | import org.testng.annotations.Test; 9 | 10 | import java.util.List; 11 | 12 | import static org.testng.Assert.assertEquals; 13 | 14 | public class FilterTests { 15 | @BeforeMethod 16 | public void setupTest() { 17 | SessionUtil.doWithSession((session) -> { 18 | User user = new User("user1", true); 19 | user.addGroups("group1", "group2"); 20 | session.save(user); 21 | user = new User("user2", true); 22 | user.addGroups("group2", "group3"); 23 | session.save(user); 24 | user = new User("user3", false); 25 | user.addGroups("group3", "group4"); 26 | session.save(user); 27 | user = new User("user4", true); 28 | user.addGroups("group4", "group5"); 29 | session.save(user); 30 | }); 31 | } 32 | 33 | @AfterMethod 34 | public void endTest() { 35 | SessionUtil.doWithSession((session) -> { 36 | session.disableFilter("byGroup"); 37 | session.disableFilter("byStatus"); 38 | 39 | // need to manually delete all of the Users since 40 | // HQL delete doesn't cascade over element collections 41 | Query query = session.createQuery("from User", User.class); 42 | for (User user : query.list()) { 43 | session.delete(user); 44 | } 45 | }); 46 | } 47 | 48 | @Test 49 | public void testSimpleQuery() { 50 | SessionUtil.doWithSession((session) -> { 51 | Query query = session.createQuery("from User", User.class); 52 | List users = query.list(); 53 | assertEquals(users.size(), 4); 54 | }); 55 | } 56 | 57 | @Test 58 | public void testActivesFilter() { 59 | SessionUtil.doWithSession((session) -> { 60 | Query query = session.createQuery("from User", User.class); 61 | session.enableFilter("byStatus").setParameter("status", Boolean.TRUE); 62 | List users = query.list(); 63 | assertEquals(users.size(), 3); 64 | }); 65 | } 66 | 67 | @Test 68 | public void testInactivesFilter() { 69 | SessionUtil.doWithSession((session) -> { 70 | Query query = session.createQuery("from User", User.class); 71 | 72 | session.enableFilter("byStatus").setParameter("status", Boolean.FALSE); 73 | List users = query.list(); 74 | assertEquals(users.size(), 1); 75 | }); 76 | } 77 | 78 | @Test 79 | public void testGroupFilter() { 80 | SessionUtil.doWithSession((session) -> { 81 | Query query = session.createQuery("from User", User.class); 82 | 83 | session.enableFilter("byGroup").setParameter("group", "group4"); 84 | List users = query.list(); 85 | assertEquals(users.size(), 2); 86 | session.enableFilter("byGroup").setParameter("group", "group1"); 87 | users = (List) query.list(); 88 | assertEquals(users.size(), 1); 89 | // should be user 1 90 | assertEquals(users.get(0).getName(), "user1"); 91 | }); 92 | } 93 | 94 | @Test 95 | public void testBothFilters() { 96 | SessionUtil.doWithSession((session) -> { 97 | Query query = session.createQuery("from User", User.class); 98 | 99 | session.enableFilter("byGroup").setParameter("group", "group4"); 100 | session.enableFilter("byStatus").setParameter("status", Boolean.TRUE); 101 | List users = query.list(); 102 | assertEquals(users.size(), 1); 103 | assertEquals(users.get(0).getName(), "user4"); 104 | }); 105 | } 106 | 107 | @Test 108 | public void testNoParameterFilter() { 109 | SessionUtil.doWithSession((session) -> { 110 | Query query = session.createQuery("from User", User.class); 111 | 112 | session.enableFilter("userEndsWith1"); 113 | List users = query.list(); 114 | assertEquals(users.size(), 1); 115 | assertEquals(users.get(0).getName(), "user1"); 116 | }); 117 | } 118 | } 119 | 120 | -------------------------------------------------------------------------------- /chapter11/src/test/java/chapter11/UserRoleTests.java: -------------------------------------------------------------------------------- 1 | package chapter11; 2 | 3 | import chapter11.userrole.Role1; 4 | import chapter11.userrole.User1; 5 | import com.autumncode.hibernate.util.SessionUtil; 6 | import org.testng.annotations.BeforeTest; 7 | import org.testng.annotations.Test; 8 | 9 | import java.util.HashMap; 10 | import java.util.HashSet; 11 | import java.util.Map; 12 | import java.util.Set; 13 | 14 | public class UserRoleTests { 15 | Map roleMap = new HashMap<>(); 16 | 17 | @BeforeTest 18 | void setupRoles() { 19 | SessionUtil.doWithSession(session -> { 20 | String[] names = {"role1", "role2", "role3"}; 21 | for (String name : names) { 22 | Role1 role1 = new Role1(name); 23 | session.save(role1); 24 | roleMap.put(name, role1.getId()); 25 | } 26 | }); 27 | } 28 | 29 | @Test 30 | void testUserWithRole() { 31 | SessionUtil.doWithSession(session -> { 32 | User1 user = new User1("foo", true); 33 | Set roles = new HashSet<>(); 34 | roles.add(session.byId(Role1.class).load(roleMap.get("role1"))); 35 | user.setRoles(roles); 36 | session.save(user); 37 | }); 38 | 39 | SessionUtil.doWithSession(session -> { 40 | System.out.println(session.createQuery("from User1 u").list()); 41 | }); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /chapter11/src/test/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | org.h2.Driver 9 | jdbc:h2:file:./db11 10 | sa 11 | 12 | org.hibernate.dialect.H2Dialect 13 | 14 | 10 15 | 16 | true 17 | true 18 | 19 | 20 | create-drop 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /chapter12/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | com.autumncode.books.hibernate 6 | chapter12 7 | 1.0-SNAPSHOT 8 | 4.0.0 9 | 10 | 11 | 12 | 13 | org.hibernate.ogm 14 | hibernate-ogm-bom 15 | 5.0.1.Final 16 | pom 17 | import 18 | 19 | 20 | 21 | 22 | 23 | 24 | org.testng 25 | testng 26 | ${testng.version} 27 | 28 | 29 | org.hibernate.ogm 30 | hibernate-ogm-mongodb 31 | ${hibernate-core.version} 32 | 33 | 34 | org.hibernate.ogm 35 | hibernate-ogm-infinispan 36 | ${hibernate-core.version} 37 | 38 | 39 | org.hibernate.javax.persistence 40 | hibernate-jpa-2.1-api 41 | 42 | 43 | org.jboss.spec.javax.transaction 44 | jboss-transaction-api_1.2_spec 45 | 46 | 47 | org.jboss.narayana.jta 48 | narayana-jta 49 | 50 | 51 | 52 | org.hibernate 53 | hibernate-core 54 | 55 | 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-compiler-plugin 61 | 3.5.1 62 | 63 | 1.8 64 | 1.8 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /chapter12/src/main/java/chapter12/Person.java: -------------------------------------------------------------------------------- 1 | package chapter12; 2 | 3 | import org.hibernate.search.annotations.Analyze; 4 | import org.hibernate.search.annotations.Field; 5 | import org.hibernate.search.annotations.Indexed; 6 | 7 | import javax.persistence.*; 8 | 9 | @Entity 10 | @Indexed 11 | public class Person { 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.AUTO) 14 | @Field(name = "person_id") 15 | Integer id; 16 | @Field(analyze = Analyze.NO) 17 | @Column 18 | String name; 19 | @Field(analyze = Analyze.NO) 20 | @Column 21 | Integer balance; 22 | 23 | public Person() { 24 | } 25 | 26 | public Person(String name, int balance) { 27 | this.name = name; 28 | this.balance = balance; 29 | } 30 | 31 | public Integer getId() { 32 | return id; 33 | } 34 | 35 | public void setId(Integer id) { 36 | this.id = id; 37 | } 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | public void setName(String name) { 44 | this.name = name; 45 | } 46 | 47 | public Integer getBalance() { 48 | return balance; 49 | } 50 | 51 | public void setBalance(Integer balance) { 52 | this.balance = balance; 53 | } 54 | 55 | @Override 56 | public boolean equals(Object o) { 57 | if (this == o) return true; 58 | if (!(o instanceof Person)) return false; 59 | 60 | Person person = (Person) o; 61 | 62 | if (getBalance() != null ? !balance.equals(person.getBalance()) : person.getBalance() != null) return false; 63 | if (getId() != null ? !getId().equals(person.getId()) : person.getId() != null) return false; 64 | if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) return false; 65 | 66 | return true; 67 | } 68 | 69 | @Override 70 | public int hashCode() { 71 | int result = getId() != null ? getId().hashCode() : 0; 72 | result = 31 * result + (getName() != null ? getName().hashCode() : 0); 73 | result = 31 * result + (getBalance() != null ? getBalance().hashCode() : 0); 74 | return result; 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | final StringBuilder sb = new StringBuilder("Person{"); 80 | sb.append("id=").append(id); 81 | sb.append(", name='").append(name).append('\''); 82 | sb.append(", balance=").append(balance); 83 | sb.append('}'); 84 | return sb.toString(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /chapter12/src/test/java/chapter12/hibernate/InfinispanTest.java: -------------------------------------------------------------------------------- 1 | package chapter12.hibernate; 2 | 3 | import chapter12.Person; 4 | import org.hibernate.Query; 5 | import org.hibernate.Session; 6 | import org.hibernate.Transaction; 7 | import org.hibernate.ogm.datastore.infinispan.Infinispan; 8 | import org.testng.annotations.BeforeMethod; 9 | 10 | import java.util.List; 11 | 12 | public class InfinispanTest extends BaseHibernateOGMTest { 13 | @Override String getConfigurationName() { 14 | return Infinispan.DATASTORE_PROVIDER_NAME; 15 | } 16 | 17 | @BeforeMethod 18 | public void clearInfinispan() { 19 | try (Session session = getSession()) { 20 | Transaction tx = session.beginTransaction(); 21 | Query query=session.createQuery("from Person"); 22 | for(Person p:(List)query.list()) { 23 | session.delete(p); 24 | } 25 | tx.commit(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapter12/src/test/java/chapter12/jpa/BaseJPAOGMTest.java: -------------------------------------------------------------------------------- 1 | package chapter12.jpa; 2 | 3 | import chapter12.Person; 4 | import org.hibernate.search.jpa.FullTextEntityManager; 5 | import org.hibernate.search.jpa.FullTextQuery; 6 | import org.hibernate.search.jpa.Search; 7 | import org.hibernate.search.query.DatabaseRetrievalMethod; 8 | import org.hibernate.search.query.ObjectLookupMethod; 9 | import org.hibernate.search.query.dsl.QueryBuilder; 10 | import org.testng.annotations.Test; 11 | 12 | import javax.persistence.EntityManager; 13 | import javax.persistence.EntityManagerFactory; 14 | import javax.persistence.Persistence; 15 | import javax.persistence.TypedQuery; 16 | import java.util.HashMap; 17 | import java.util.HashSet; 18 | import java.util.Map; 19 | import java.util.Set; 20 | 21 | import static org.jgroups.util.Util.assertEquals; 22 | import static org.testng.Assert.assertNotNull; 23 | import static org.testng.Assert.assertNull; 24 | 25 | public abstract class BaseJPAOGMTest { 26 | 27 | abstract String getPersistenceUnitName(); 28 | 29 | EntityManagerFactory factory = null; 30 | 31 | public synchronized EntityManager getEntityManager() { 32 | if (factory == null) { 33 | factory = Persistence.createEntityManagerFactory(getPersistenceUnitName()); 34 | } 35 | return factory.createEntityManager(); 36 | } 37 | 38 | @Test 39 | public void testQueryLucene() { 40 | Map people = new HashMap<>(); 41 | EntityManager em = getEntityManager(); 42 | em.getTransaction().begin(); 43 | 44 | for (int i = 7; i < 9; i++) { 45 | people.put(i, new Person("user " + i, i)); 46 | em.persist(people.get(i)); 47 | } 48 | 49 | em.getTransaction().commit(); 50 | em.close(); 51 | 52 | em = getEntityManager(); 53 | em.getTransaction().begin(); 54 | FullTextEntityManager ftem = Search.getFullTextEntityManager(em); 55 | 56 | //Optionally use the QueryBuilder to simplify Query definition: 57 | QueryBuilder b = ftem.getSearchFactory() 58 | .buildQueryBuilder() 59 | .forEntity(Person.class) 60 | .get(); 61 | org.apache.lucene.search.Query lq = 62 | b.keyword().onField("id").matching(people.get(7).getId()).createQuery(); 63 | 64 | //Transform the Lucene Query in a JPA Query: 65 | FullTextQuery ftQuery = ftem.createFullTextQuery(lq, Person.class); 66 | //This is a requirement when using Hibernate OGM instead of ORM: 67 | ftQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, 68 | DatabaseRetrievalMethod.FIND_BY_ID); 69 | 70 | Set resultList = new HashSet<>(ftQuery.getResultList()); 71 | System.out.println(resultList); 72 | // lucene can return multiple results for a given query! 73 | Set personSet = new HashSet<>(); 74 | personSet.addAll(resultList); 75 | assertEquals(personSet.size(), 1); 76 | em.getTransaction().commit(); 77 | em.close(); 78 | } 79 | 80 | @Test 81 | public void testQueryJPQL() { 82 | Map people = new HashMap<>(); 83 | EntityManager em = getEntityManager(); 84 | em.getTransaction().begin(); 85 | 86 | for (int i = 4; i < 7; i++) { 87 | people.put(i, new Person("user " + i, i)); 88 | em.persist(people.get(i)); 89 | } 90 | 91 | em.getTransaction().commit(); 92 | em.close(); 93 | 94 | em = getEntityManager(); 95 | em.getTransaction().begin(); 96 | TypedQuery query=em.createQuery("from Person p where p.balance = :balance", Person.class); 97 | query.setParameter("balance", 4); 98 | System.out.println(query.getResultList()); 99 | Person p = query.getSingleResult(); 100 | assertEquals(p, people.get(4)); 101 | em.getTransaction().commit(); 102 | em.close(); 103 | 104 | em = getEntityManager(); 105 | em.getTransaction().begin(); 106 | 107 | query=em.createQuery("from Person p where p.balance > :balance", Person.class); 108 | query.setParameter("balance", 4); 109 | Set peopleList = new HashSet(query.getResultList()); 110 | assertEquals(peopleList.size(), 2); 111 | 112 | em.getTransaction().commit(); 113 | em.close(); 114 | 115 | em = getEntityManager(); 116 | em.getTransaction().begin(); 117 | query=em.createQuery("from Person p where p.balance = :balance and p.name=:name", Person.class); 118 | query.setParameter("balance", 4); 119 | query.setParameter("name", "user 4"); 120 | p = query.getSingleResult(); 121 | assertEquals(p, people.get(4)); 122 | 123 | em.getTransaction().commit(); 124 | em.close(); 125 | } 126 | 127 | @Test 128 | public void testCR() { 129 | EntityManager em = getEntityManager(); 130 | em.getTransaction().begin(); 131 | Person person = new Person("user 1", 1); 132 | em.persist(person); 133 | em.getTransaction().commit(); 134 | em.close(); 135 | 136 | System.out.println(person); 137 | em = getEntityManager(); 138 | Person p2 = em.find(Person.class, person.getId()); 139 | em.close(); 140 | System.out.println(p2); 141 | 142 | assertNotNull(p2); 143 | assertEquals(p2, person); 144 | } 145 | 146 | @Test 147 | public void testUpdate() { 148 | EntityManager em = getEntityManager(); 149 | em.getTransaction().begin(); 150 | Person person = new Person("user 2", 1); 151 | em.persist(person); 152 | em.getTransaction().commit(); 153 | em.close(); 154 | 155 | em = getEntityManager(); 156 | em.getTransaction().begin(); 157 | Person p2 = em.find(Person.class, person.getId()); 158 | p2.setBalance(2); 159 | em.getTransaction().commit(); 160 | em.close(); 161 | 162 | em = getEntityManager(); 163 | em.getTransaction().begin(); 164 | Person p3 = em.find(Person.class, person.getId()); 165 | em.getTransaction().commit(); 166 | em.close(); 167 | 168 | assertEquals(p3, p2); 169 | } 170 | 171 | @Test 172 | public void testDelete() { 173 | EntityManager em = getEntityManager(); 174 | em.getTransaction().begin(); 175 | Person person = new Person("user 3", 1); 176 | em.persist(person); 177 | em.getTransaction().commit(); 178 | em.close(); 179 | 180 | em = getEntityManager(); 181 | em.getTransaction().begin(); 182 | Person p2 = em.find(Person.class, person.getId()); 183 | em.remove(p2); 184 | em.getTransaction().commit(); 185 | em.close(); 186 | 187 | em = getEntityManager(); 188 | em.getTransaction().begin(); 189 | Person p3 = em.find(Person.class, person.getId()); 190 | em.getTransaction().commit(); 191 | em.close(); 192 | 193 | assertNull(p3); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /chapter12/src/test/java/chapter12/jpa/InfinispanTest.java: -------------------------------------------------------------------------------- 1 | package chapter12.jpa; 2 | 3 | import org.hibernate.Query; 4 | import org.hibernate.Session; 5 | import org.testng.annotations.BeforeMethod; 6 | 7 | import javax.persistence.EntityManager; 8 | 9 | public class InfinispanTest extends BaseJPAOGMTest { 10 | @Override 11 | String getPersistenceUnitName() { 12 | return "chapter12-ispn"; 13 | } 14 | 15 | @BeforeMethod 16 | public void clearInfinispan() { 17 | EntityManager em = getEntityManager(); 18 | em.getTransaction().begin(); 19 | Session session = em.unwrap(Session.class); 20 | Query q = session.createQuery("from Person p"); 21 | for (Object p : q.list()) { 22 | System.out.println("removing " + p); 23 | em.remove(p); 24 | } 25 | em.getTransaction().commit(); 26 | em.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapter12/src/test/java/chapter12/jpa/MongoTest.java: -------------------------------------------------------------------------------- 1 | package chapter12.jpa; 2 | 3 | import com.mongodb.MongoClient; 4 | import com.mongodb.client.MongoDatabase; 5 | import org.testng.annotations.AfterMethod; 6 | 7 | public class MongoTest extends BaseJPAOGMTest { 8 | @AfterMethod 9 | public void clearDB() { 10 | try (MongoClient mongoClient = new MongoClient()) { 11 | MongoDatabase db = mongoClient.getDatabase("chapter12"); 12 | db.drop(); 13 | } 14 | } 15 | 16 | @Override 17 | String getPersistenceUnitName() { 18 | return "chapter12-mongo"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter12/src/test/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | org.hibernate.ogm.jpa.HibernateOgmPersistence 10 | chapter12.Person 11 | 12 | 14 | 15 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 24 | 25 | org.hibernate.ogm.jpa.HibernateOgmPersistence 26 | chapter12.Person 27 | 28 | 30 | 32 | 33 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /chapter12/src/test/resources/mongodb.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | org.h2.Driver 9 | jdbc:h2:file:./db11 10 | sa 11 | 12 | org.hibernate.dialect.H2Dialect 13 | 14 | 10 15 | 16 | true 17 | true 18 | 19 | 20 | create-drop 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /chapter13/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | hibernate-parent 7 | com.autumncode.books.hibernate 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | chapter13 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-envers 37 | 38 | 39 | -------------------------------------------------------------------------------- /chapter13/src/main/java/chapter13/model/User.java: -------------------------------------------------------------------------------- 1 | package chapter13.model; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import org.hibernate.envers.Audited; 6 | 7 | import javax.persistence.*; 8 | import java.util.Arrays; 9 | import java.util.HashSet; 10 | import java.util.Set; 11 | 12 | @Entity 13 | @Data 14 | @NoArgsConstructor 15 | public class User { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.AUTO) 18 | Integer id; 19 | @Audited 20 | @Column(unique = true) 21 | String name; 22 | @Audited 23 | boolean active; 24 | //@Audited 25 | @ElementCollection 26 | Set groups; 27 | @Audited 28 | String description; 29 | 30 | public User(String name, boolean active) { 31 | this.name = name; 32 | this.active = active; 33 | } 34 | 35 | public void addGroups(String... groupSet) { 36 | if (getGroups() == null) { 37 | setGroups(new HashSet<>()); 38 | } 39 | getGroups().addAll(Arrays.asList(groupSet)); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /chapter13/src/test/java/chapter13/EnversTest.java: -------------------------------------------------------------------------------- 1 | package chapter13; 2 | 3 | import chapter13.model.User; 4 | import com.autumncode.hibernate.util.SessionUtil; 5 | import org.hibernate.envers.AuditReader; 6 | import org.hibernate.envers.AuditReaderFactory; 7 | import org.hibernate.envers.query.AuditEntity; 8 | import org.hibernate.envers.query.AuditQuery; 9 | import org.testng.annotations.Test; 10 | 11 | import java.util.List; 12 | 13 | import static org.testng.Assert.assertEquals; 14 | import static org.testng.Assert.assertFalse; 15 | import static org.testng.Assert.assertTrue; 16 | 17 | public class EnversTest { 18 | int[] userId = {0}; 19 | 20 | @Test 21 | public void createUser() { 22 | SessionUtil.doWithSession((session) -> { 23 | User user = new User("user name", true); 24 | user.setDescription("first description"); 25 | user.addGroups("group1"); 26 | session.save(user); 27 | userId[0] = user.getId(); 28 | }); 29 | SessionUtil.doWithSession((session) -> { 30 | User user = session.byId(User.class).load(userId[0]); 31 | assertTrue(user.isActive()); 32 | assertEquals(user.getDescription(), 33 | "first description"); 34 | }); 35 | } 36 | 37 | @Test(dependsOnMethods = "createUser") 38 | public void updateUser() { 39 | SessionUtil.doWithSession((session) -> { 40 | User user = session.byId(User.class).load(userId[0]); 41 | user.addGroups("group2"); 42 | user.setDescription("other description"); 43 | }); 44 | 45 | SessionUtil.doWithSession((session) -> { 46 | User user = session.byId(User.class).load(userId[0]); 47 | user.setActive(false); 48 | }); 49 | 50 | SessionUtil.doWithSession((session) -> { 51 | User user = session.byId(User.class).load(userId[0]); 52 | assertFalse(user.isActive()); 53 | assertEquals(user.getDescription(), "other description"); 54 | }); 55 | } 56 | 57 | 58 | @Test(dependsOnMethods = "updateUser") 59 | public void validateRevisionData() { 60 | SessionUtil.doWithSession((session) -> { 61 | AuditReader reader = AuditReaderFactory.get(session); 62 | List revisions = reader.getRevisions(User.class, userId[0]); 63 | assertEquals(revisions.size(), 3); 64 | assertEquals( 65 | reader.find(User.class, userId[0], 1).getDescription(), 66 | "first description"); 67 | System.err.println(reader.find(User.class, userId[0], 2)); 68 | assertEquals( 69 | reader.find(User.class, userId[0], 2).getDescription(), 70 | "other description"); 71 | assertFalse( 72 | reader.find(User.class, userId[0], 3).isActive() 73 | ); 74 | }); 75 | } 76 | 77 | @Test(dependsOnMethods = "validateRevisionData") 78 | public void findLastActiveUserRevision() { 79 | SessionUtil.doWithSession((session) -> { 80 | AuditReader reader = AuditReaderFactory.get(session); 81 | AuditQuery query = reader.createQuery() 82 | .forRevisionsOfEntity(User.class, true, true) 83 | .addOrder(AuditEntity.revisionNumber().desc()) 84 | .setMaxResults(1) 85 | .add(AuditEntity.id().eq(userId[0])) 86 | .add(AuditEntity.property("active").eq(true)); 87 | 88 | User user = (User) query.getSingleResult(); 89 | 90 | assertEquals(user.getDescription(), "other description"); 91 | }); 92 | } 93 | 94 | @Test(dependsOnMethods = "findLastActiveUserRevision") 95 | public void revertUserData() { 96 | SessionUtil.doWithSession((session) -> { 97 | AuditReader reader = AuditReaderFactory.get(session); 98 | AuditQuery query = reader.createQuery() 99 | .forRevisionsOfEntity(User.class, true, true) 100 | .addOrder(AuditEntity.revisionNumber().desc()) 101 | .setMaxResults(1) 102 | .add(AuditEntity.id().eq(userId[0])) 103 | .add(AuditEntity.property("active").eq(true)); 104 | 105 | User auditUser = (User) query.getSingleResult(); 106 | assertEquals(auditUser.getDescription(), "other description"); 107 | 108 | // now we copy the audit data into the "current user." 109 | User user = session.byId(User.class).load(userId[0]); 110 | assertFalse(user.isActive()); 111 | user.setActive(auditUser.isActive()); 112 | user.setDescription(auditUser.getDescription()); 113 | user.setGroups(auditUser.getGroups()); 114 | }); 115 | 116 | // let's make sure the "current user" looks like what we expect 117 | SessionUtil.doWithSession((session) -> { 118 | User user = session.byId(User.class).load(userId[0]); 119 | assertTrue(user.isActive()); 120 | assertEquals(user.getDescription(), "other description"); 121 | }); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /chapter13/src/test/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | org.h2.Driver 9 | jdbc:h2:file:./db13 10 | sa 11 | 12 | org.hibernate.dialect.H2Dialect 13 | 14 | 10 15 | 16 | true 17 | true 18 | 19 | 20 | create-drop 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /util/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | hibernate-parent 7 | com.autumncode.books.hibernate 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | util 12 | 13 | 14 | 15 | org.hibernate 16 | hibernate-c3p0 17 | 18 | 19 | org.hibernate 20 | hibernate-entitymanager 21 | test 22 | 23 | 24 | com.mchange 25 | c3p0 26 | 27 | 28 | org.projectlombok 29 | lombok 30 | test 31 | 32 | 33 | org.testng 34 | testng 35 | test 36 | 37 | 38 | -------------------------------------------------------------------------------- /util/src/main/java/com/autumncode/hibernate/util/SessionUtil.java: -------------------------------------------------------------------------------- 1 | package com.autumncode.hibernate.util; 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.jboss.logging.Logger; 10 | 11 | import java.util.function.Consumer; 12 | import java.util.function.Function; 13 | 14 | public class SessionUtil { 15 | private static final SessionUtil instance = new SessionUtil(); 16 | private static final String CONFIG_NAME = "/configuration.properties"; 17 | private final SessionFactory factory; 18 | Logger logger = Logger.getLogger(this.getClass()); 19 | 20 | private SessionUtil() { 21 | StandardServiceRegistry registry = new StandardServiceRegistryBuilder() 22 | .configure() 23 | .build(); 24 | factory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); 25 | } 26 | 27 | public static Session getSession() { 28 | return getInstance().factory.openSession(); 29 | } 30 | 31 | private static SessionUtil getInstance() { 32 | return instance; 33 | } 34 | 35 | public static void doWithSession(Consumer command) { 36 | try (Session session = getSession()) { 37 | Transaction tx = session.beginTransaction(); 38 | 39 | command.accept(session); 40 | if (tx.isActive() && 41 | !tx.getRollbackOnly()) { 42 | tx.commit(); 43 | } else { 44 | tx.rollback(); 45 | } 46 | } 47 | } 48 | 49 | public static T returnFromSession(Function command) { 50 | try (Session session = getSession()) { 51 | Transaction tx = null; 52 | try { 53 | tx = session.beginTransaction(); 54 | 55 | return command.apply(session); 56 | } catch (Exception e) { 57 | throw new RuntimeException(e); 58 | } finally { 59 | if (tx != null) { 60 | if (tx.isActive() && 61 | !tx.getRollbackOnly()) { 62 | tx.commit(); 63 | } else { 64 | tx.rollback(); 65 | } 66 | } 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /util/src/main/java/com/autumncode/jpa/util/JPASessionUtil.java: -------------------------------------------------------------------------------- 1 | package com.autumncode.jpa.util; 2 | 3 | import org.hibernate.Session; 4 | 5 | import javax.persistence.EntityManager; 6 | import javax.persistence.EntityManagerFactory; 7 | import javax.persistence.Persistence; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | public class JPASessionUtil { 12 | private static Map persistenceUnits = new HashMap<>(); 13 | 14 | @SuppressWarnings("WeakerAccess") 15 | public static synchronized EntityManager getEntityManager(String persistenceUnitName) { 16 | persistenceUnits.putIfAbsent(persistenceUnitName, 17 | Persistence.createEntityManagerFactory(persistenceUnitName)); 18 | return persistenceUnits.get(persistenceUnitName) 19 | .createEntityManager(); 20 | } 21 | 22 | public static Session getSession(String persistenceUnitName) { 23 | return getEntityManager(persistenceUnitName).unwrap(Session.class); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /util/src/test/java/com/autumncode/hibernate/util/SessionBuilderTest.java: -------------------------------------------------------------------------------- 1 | package com.autumncode.hibernate.util; 2 | 3 | import com.autumncode.util.model.Thing; 4 | import org.hibernate.Session; 5 | import org.hibernate.query.Query; 6 | import org.testng.annotations.Test; 7 | 8 | import static org.testng.Assert.assertEquals; 9 | import static org.testng.Assert.assertNotNull; 10 | 11 | public class SessionBuilderTest { 12 | @Test 13 | public void testSessionFactory() { 14 | try (Session session = SessionUtil.getSession()) { 15 | assertNotNull(session); 16 | } 17 | } 18 | @Test 19 | public void testDoWithSession() { 20 | SessionUtil.doWithSession(session -> { 21 | session.createQuery("delete from Thing").executeUpdate(); 22 | 23 | Thing t=new Thing(); 24 | t.setName("thingName"); 25 | session.persist(t); 26 | }); 27 | Thing thing=SessionUtil.returnFromSession(session -> { 28 | Query query=session.createQuery("from Thing t where t.name=:name", Thing.class); 29 | query.setParameter("name", "thingName"); 30 | return query.getSingleResult(); 31 | }); 32 | assertNotNull(thing); 33 | System.out.println(thing); 34 | assertEquals(thing.getName(), "thingName"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /util/src/test/java/com/autumncode/jpa/util/JPASessionUtilTest.java: -------------------------------------------------------------------------------- 1 | package com.autumncode.jpa.util; 2 | 3 | import com.autumncode.util.model.Thing; 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 javax.persistence.EntityManager; 10 | import javax.persistence.TypedQuery; 11 | 12 | import static org.testng.Assert.*; 13 | 14 | public class JPASessionUtilTest { 15 | @Test 16 | public void getEntityManager() { 17 | EntityManager em = JPASessionUtil.getEntityManager("utiljpa"); 18 | em.close(); 19 | } 20 | 21 | @Test(expectedExceptions = {javax.persistence.PersistenceException.class}) 22 | public void nonexistentEntityManagerName() { 23 | JPASessionUtil.getEntityManager("nonexistent"); 24 | fail("We shouldn't be able to acquire an EntityManager here"); 25 | } 26 | 27 | @Test 28 | public void getSession() { 29 | Session session = JPASessionUtil.getSession("utiljpa"); 30 | session.close(); 31 | } 32 | 33 | @Test(expectedExceptions = {javax.persistence.PersistenceException.class}) 34 | public void nonexistentSessionName() { 35 | JPASessionUtil.getSession("nonexistent"); 36 | fail("We shouldn't be able to acquire a Session here"); 37 | } 38 | 39 | @Test 40 | public void testEntityManager() { 41 | EntityManager em = JPASessionUtil.getEntityManager("utiljpa"); 42 | em.getTransaction().begin(); 43 | Thing t = new Thing(); 44 | t.setName("Thing 1"); 45 | em.persist(t); 46 | em.getTransaction().commit(); 47 | em.close(); 48 | 49 | em = JPASessionUtil.getEntityManager("utiljpa"); 50 | em.getTransaction().begin(); 51 | TypedQuery q = em.createQuery("from Thing t where t.name=:name", Thing.class); 52 | q.setParameter("name", "Thing 1"); 53 | Thing result = q.getSingleResult(); 54 | assertNotNull(result); 55 | assertEquals(result, t); 56 | em.remove(result); 57 | em.getTransaction().commit(); 58 | em.close(); 59 | } 60 | 61 | @Test 62 | public void testSession() { 63 | Thing t=null; 64 | try(Session session = JPASessionUtil.getSession("utiljpa")) { 65 | Transaction tx = session.beginTransaction(); 66 | t = new Thing(); 67 | t.setName("Thing 2"); 68 | session.persist(t); 69 | tx.commit(); 70 | } 71 | 72 | try(Session session = JPASessionUtil.getSession("utiljpa")) { 73 | Transaction tx = session.beginTransaction(); 74 | Query q = 75 | session.createQuery("from Thing t where t.name=:name", Thing.class); 76 | q.setParameter("name", "Thing 2"); 77 | Thing result = q.uniqueResult(); 78 | assertNotNull(result); 79 | assertEquals(result, t); 80 | session.delete(result); 81 | tx.commit(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /util/src/test/java/com/autumncode/util/model/Thing.java: -------------------------------------------------------------------------------- 1 | package com.autumncode.util.model; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | 7 | @Entity(name = "Thing") 8 | @Data 9 | public class Thing { 10 | @Id 11 | @GeneratedValue(strategy = GenerationType.AUTO) 12 | Integer id; 13 | @Column 14 | String name; 15 | } 16 | -------------------------------------------------------------------------------- /util/src/test/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /util/src/test/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | org.h2.Driver 9 | jdbc:h2:./util 10 | sa 11 | 12 | org.hibernate.dialect.H2Dialect 13 | 14 | 15 | true 16 | 17 | update 18 | 19 | 20 | --------------------------------------------------------------------------------