Java Persistence and Hibernate tutorial

java persistence with hibernate second edition pdf free download and java persistence hibernate and jpa fundamentals download, java persistence with hibernate jar
LexiWills Profile Pic
LexiWills,United Kingdom,Professional
Published Date:01-08-2017
Your Website URL(Optional)
Comment
Guide to Java Persistence and Hibernate Sebastian HennebruederGuide to Java Persistence and Hibernate Sebastian HennebruederTable of Contents About the author, book and versions ................................................................................................ viii 1. The author . ............................................................................................................................ viii 2. The book ................................................................................................................................ viii 3. Library Versions ...................................................................................................................... ix I. Introduction . ....................................................................................................................................... 1 1. Introduction to Hibernate . ........................................................................................................ 2 1.1. A first Hibernate example ............................................................................................. 2 1.2. Hibernate basics . .......................................................................................................... 19 2. Hibernate Concepts - State of Objects . .................................................................................. 21 2.1. The three states of objects . .......................................................................................... 21 2.2. Lazy initialization, a Hibernate problem . .................................................................... 23 3. Working with Objects . ............................................................................................................ 27 3.1. Java Persistence versus Hibernate ............................................................................... 27 3.2. Hibernate API .............................................................................................................. 27 3.3. EntityManager API ...................................................................................................... 34 4. A more complex example – web application ......................................................................... 40 4.1. Summary ...................................................................................................................... 49 II. Mapping, Queries ........................................................................................................................... 51 5. Basic Mappings ...................................................................................................................... 52 5.1. Annotation versus XML .............................................................................................. 52 5.2. Annotation mapping ..................................................................................................... 53 5.3. XML Mapping . ............................................................................................................ 58 6. Primary key mapping . ............................................................................................................ 63 6.1. Natural versus Surrogate Ids . ...................................................................................... 63 6.2. Assigned Id .................................................................................................................. 64 6.3. Generated with Auto Strategy ..................................................................................... 64 6.4. Other Annotation Strategies ........................................................................................ 64 6.5. Composite Id . ............................................................................................................... 65 6.6. Equals and Hashcode ................................................................................................... 68 6.7. Other XML Id tags ...................................................................................................... 72 7. Relation mapping .................................................................................................................... 75 7.1. Selecting between List, Set, Map or array to hold many side . .................................... 75 7.2. Uni- and Bi-directional relations . ................................................................................ 84 7.3. Cascading ..................................................................................................................... 86 7.4. 1:1 relation . .................................................................................................................. 88 7.5. 1:n . ............................................................................................................................... 94 7.6. m:n ............................................................................................................................. 104 7.7. 1:n:1 . .......................................................................................................................... 109 7.8. Recursive relation . ..................................................................................................... 111 7.9. Typed relation (XML only) ....................................................................................... 113 7.10. Typed relation (annotation workaround) ................................................................. 115 8. Components = Composition mapping .................................................................................. 119 8.1. Composition versus entity relations . .......................................................................... 119 8.2. Composed class in one table ..................................................................................... 120 8.3. Composition as set of many classes .......................................................................... 123 8.4. Equals implementation . .............................................................................................. 124 8.5. Composition as list of many classes .......................................................................... 125 iiiGuide to Java Persistence and Hibernate 8.6. Advanced details . ....................................................................................................... 127 8.7. Composition 1:n:1 ...................................................................................................... 127 8.8. Not included mappings .............................................................................................. 129 9. Inheritance ............................................................................................................................. 131 9.1. Use Case . ................................................................................................................... 131 9.2. Overview on mapping approaches ............................................................................. 131 9.3. Single Table . .............................................................................................................. 134 9.4. Joined Inheritance . ..................................................................................................... 137 9.5. Joined Inheritance with Discriminator . ...................................................................... 140 9.6. Mixing Single table and Joined . ................................................................................ 142 9.7. Union Inheritance ...................................................................................................... 142 9.8. XML Includes ............................................................................................................ 145 9.9. Mapped Super Class . ................................................................................................. 147 10. Lob with Oracle and PostgreSQL ...................................................................................... 150 10.1. PostgreSQL .............................................................................................................. 150 10.2. Oracle ....................................................................................................................... 152 11. Querying data ...................................................................................................................... 156 11.1. Useful tools . ............................................................................................................. 156 11.2. HQL ......................................................................................................................... 157 11.3. Criteria Queries ........................................................................................................ 165 11.4. Native SQL . ............................................................................................................. 170 III. Building applications and Architecture ...................................................................................... 176 12. Data Access Objects . .......................................................................................................... 177 12.1. Best practices and DAO . ......................................................................................... 177 12.2. Data Access Objects DAO ...................................................................................... 177 12.3. Weaving the application structure ........................................................................... 178 13. Session and Transaction Handling ..................................................................................... 185 13.1. Hibernate Session ..................................................................................................... 185 13.2. JTA versus JDBC Transactions . .............................................................................. 186 13.3. Transaction handling – default pattern .................................................................... 186 13.4. JDBC transactions with ThreadLocal ...................................................................... 187 13.5. JTA transaction with a single database ................................................................... 188 13.6. JDBC or JTA with the Spring framework ............................................................... 190 13.7. Conversations and Session Lifetime . ....................................................................... 190 13.8. Concurrent Access ................................................................................................... 194 14. Integration with other technologies . ................................................................................... 199 14.1. Hibernate and Spring . .............................................................................................. 199 14.2. Hibernate and Struts . ............................................................................................... 205 IV. Configuration, Performance, Validation and Full Text Search . ................................................. 208 15. Hibernate Full Text Search . ................................................................................................ 209 16. Performance Tuning ........................................................................................................... 212 16.1. Analysing performance problem .............................................................................. 212 16.2. Iterating through relations – batches ....................................................................... 213 16.3. Iterating through relations – subqueries .................................................................. 214 16.4. Iterating through relations – single query ................................................................ 214 16.5. Reporting queries . .................................................................................................... 215 16.6. Iterating through large resultsets ............................................................................. 216 16.7. Caches ...................................................................................................................... 217 17. Configuration ...................................................................................................................... 224 ivGuide to Java Persistence and Hibernate 17.1. Connection Pools . .................................................................................................... 224 A. Appendix ...................................................................................................................................... 226 A.1. Annotation Reference . ...................................................................................................... 226 Index .................................................................................................................................................. 245 vList of Figures 7.1. Table structure ............................................................................................................................. 75 7.2. Supported Collections and Maps ................................................................................................. 76 viList of Tables 6.1. Example of a table having a unique Integer as primary key . ...................................................... 63 6.2. Example of a table having name and surname as primary key . .................................................. 63 6.3. Example of a table having a natural primary key . ...................................................................... 63 6.4. Id Generator Strategies . ............................................................................................................... 65 7.1. Sample hash . ................................................................................................................................ 77 7.2. JPA Annotation Cascade Types . ................................................................................................. 87 7.3. Hibernate Annotation and XML cascade types . .......................................................................... 87 14.1. Transaction types . .................................................................................................................... 205 viiAbout the author, book and versions Revision Mai 2013 1. The author Well, my name is Sebastian Hennebrueder. I am a freelancer and work as trainer, software developer and architect. I am located at Bad Vilbel, a small town close to Frankfurt in Germany. I am passionated about technologies, publish articles and participate in conferences like JavaOne in San Francisco or Devoxx in Antwerpen. You can contract me for your projects. Hibernate, Java Persistence and JEE training I offer basic and advanced training in Europe, the training can happen onsite in your company but you will find as well a regular schedule for Frankfurt, Germany on my website http://www.laliluna.de With more than 25 trainings in Europe in the last 3 years, I have a solid experience. I can teach in German, English and French. Software development I am a freelancer and you can contract me as software developer and/or architect. I have a vast experience as software developer and architect in Hibernate / Java Persistence, Jboss Seam, Spring, GWT and a number of other web framework. 2. The book I want to provide you with an easy-to-follow introduction to Java Persistence and Hibernate including not only code snippets but complete working examples. For this reason the guide is based on the following principles: Explanations with complete working examples Whenever something is explained you will find a complete sample application. If a specific mapping is demonstrated you can find a sample application, too. It shows how to insert, update, delete or query the classes included in this mapping. Larger sample applications show the implementation of real applications using Hibernate in detail. Each application has an increasing complexity. Cache configurations, deployment configurations for particular application server rounds off the examples. Altogether the book provides about 30 mapping examples + variations, 4 real projects and some smaller projects showing a specific configuration. Potential problems are investigated in detail Hibernate has some problem zones where you can easily make mistakes. These are covered in detail to help you to avoid these problems. Some topics are LazyLoading, Session and transaction handling, optimistic concurrency and version handling. viiiAbout the author, book and versions Best Practices One chapter is completely focussing on how to implement well designed Hibernate applications. DAO patterns and business layers are discussed. Pros and cons and the logic behind this structure are explained. Focus on important features Deliberately, I did not explain some rare concepts which I consider to be either not stable or very rarely used. Instead I referred to the corresponding chapters of the Hibernate reference - the documentation available with Hibernate. In my opinion the Hibernate reference is far too complex for people learning Hibernate. However, it is a valuable resource for people who already know Hibernate. What this book is not… The texts are short and frequently you are referred to parts of sample applications. If you prefer larger narrative parts you should not read this book. Feel free to contact me and to comment on the book in the forum at http://www.laliluna.de Best Regards / Viele Grüße Sebastian Hennebrueder 3. Library Versions This book covers Java Persistence 2 and Hibernate 4. ixPart I. IntroductionChapter 1. Introduction to Hibernate Hibernate is a solution for object relational mapping and a persistence management solution or persistence layer. This is probably not understandable for anybody learning Hibernate. What you can imagine is probably that you have your application with some functions (business logic) and you want to save data in a database. Using Java, the business logic normally works with objects of different class types. Your application is object-oriented. Your database tables are not object oriented but relational. The basic idea of object relation mapping - ORM is to map database tables to a class. One row of the database data is copied to a class instance. On the other hand, if an object is saved, one row is inserted in the database table. Saving data to a storage is called persistence. The process of copying of table rows to objects and vice versa is called object relational mapping. 1.1. A first Hibernate example As it is easier to explain something after having shown a real example, we will develop our first Hibernate application now. 2Introduction to Hibernate 1.1.1. Introduction Our use case is sweet. We will use an example from the honey production. You need a lot of bees to get honey. Our use case includes Honey and Bee as model and a 1:n relation from Bee to Honey. Using object oriented terms: There is a 1:n association between the class Bee and Honey. We will create a class Honey which is mapped to the table honey in the database and a class Bee mapped to the table bee. The following picture shows our database schema. In order to get complete our application, we must undertake the following steps: • create classes • create mapping from classes to tables • configure Hibernate libraries • configure the Hibernate datasource • write code to use our mapped classes Source code For this example you will find the complete source code in the ebook. Normally, I show only the relevant part of the source code in the ebook. But you can find the complete source code in the provided sources. 1.1.2. Creating Java Project and classes Create a new project using your development environment. I used Eclipse for this example. Using Eclipse press the keys Ctrl+n (Strg+n) to create a new project. Select Java project. We will call it FirstHibernateExample. Create a new class named Honey in the package de.laliluna.example. Our class has four fields: • Integer id – an Integer value as primary key • String name – name of the honey 3Introduction to Hibernate • String taste – description of the taste • java.util.SetBee bees – bees, having produced the honey Furthermore we need: • Getter and setter methods for our fields. In eclipse you can generate them (Context menu Source → Generate Getter and Setter). → • A default constructor • Implementation of the Serializable interface • Overwrite the toString method. We will need it for debugging. Java version: I used Java generics, which was introduced with Version 5 (alias 1.5). Annotations always starts with . Your source code should look like the code below: Honey class. package de.laliluna.example; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class Honey implements Serializable private Integer id; private String name; private String taste; private SetBee bees = new HashSetBee(); public Honey() public Honey(String name, String taste) this.name = name; this.taste = taste; public Integer getId() return id; public void setId(Integer id) this.id = id; public String getName() return name; public void setName(String name) this.name = name; public String getTaste() return taste; 4Introduction to Hibernate public void setTaste(String taste) this.taste = taste; public SetBee getBees() return bees; public void setBees(SetBee bees) this.bees = bees; public String toString() return "Honey: " + getId() + " Name: " + getName() + " Taste: " + getTaste(); Requirements of domain classes There are a couple of requirements for a mapped class, you should always consider to meet: • An id property • A default constructor (= no parameter) with at least protected scope. Either omit the constructor or create an empty one. • Implementation of the Serializable interface, if and only if you want to serialize your entity. This may happen indirectly if you put an entity for example into a HTTPSession. Hibernate does not require the Serializable interface in entities. • A useful toString method for debugging. (recommendation) Create a class Bee with the fields: • Integer id • String name • Honey honey The field id is once again the primary key. Please don’t forget the important requirements, I stated above. Bee class. package de.laliluna.example; import java.io.Serializable; import java.text.MessageFormat; public class Bee implements Serializable private Integer id; private String name; private Honey honey; public Bee() 5Introduction to Hibernate public Bee(String name) this.name = name; public Integer getId() return id; public void setId(Integer id) this.id = id; public String getName() return name; public void setName(String name) this.name = name; public Honey getHoney() return honey; public void setHoney(Honey honey) this.honey = honey; public String toString() return MessageFormat.format("0: id=1, name=2", new Object getClass().getSimpleName(), id, name ); 1.1.3. Hibernate configuration The Hibernate configuration will define • which database we connect to • the type of database (MySQL, PostgreSQL, Oracle, …) • Hibernate configuration settings • classes or XML mapping files holding our mappings. Create a new file named hibernate.cfg.xml in your src directory. 1.1.4. Annotation or XML You have to choices to map documents: Annotations and XML. They’ll be discussed later in this book. I explain both approaches for this example. If you can use Java 1.5 alias 5 or later, I recommend to use annotations. Below you can find a configuration for PostgreSQL using annotation based mapping. Afterwards, I will explain required changes for other databases and XML based mapping. Do not forget to change the username and the password to suit your database configuration. 6Introduction to Hibernate hibernate.cfg.xml. ?xml version='1.0' encoding='UTF-8'? DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" hibernate-configuration session-factory postgre SQL configuration property name="connection.url" jdbc:postgresql://localhost:5432/learninghibernate /property property name="connection.username"postgres/property property name="connection.password"p/property property name="connection.driver_class" org.postgresql.Driver /property property name="dialect" org.hibernate.dialect.PostgreSQLDialect /property property name="cache.provider_class" org.hibernate.cache.NoCacheProvider /property property name="current_session_context_class"thread/property property name="hibernate.show_sql"true/property property name="hibernate.hbm2ddl.auto"create/property mapping class="de.laliluna.example.Honey" / mapping class="de.laliluna.example.Bee" / /session-factory /hibernate-configuration At the beginning of the configuration, you can find the database connection. Afterwards, the dialect is specified. Hibernate will translate all queries into this dialect. Then, I configured the cache implementation and the session and transaction behaviour. The setting hbm2ddl.auto instructs Hibernate to update or create the table schema when the configuration is initialized. You only have to create the database. The tag mapping class at the end of the file defines which classes are mapped using annotations. If you want to use XML based mappings then you need to reference the XML mapping files instead: mapping resource="de/laliluna/example/Honey.hbm.xml" / mapping resource="de/laliluna/example/Bee.hbm.xml" / Other databases A configuration for MySQL requires the following changes: property name="connection.url"jdbc:mysql://localhost/learninghibernate/property property name="connection.username"root/property property name="connection.password"r/property property name="connection.driver_class"com.mysql.jdbc.Driver/property property name="dialect"org.hibernate.dialect.MySQLDialect/property If you want to use another database, you must find out the name of the driver class and the name of the dialect. You can find all available dialects in the java package org.hibernate.dialect of the hibernate.jar file. 7Introduction to Hibernate A short extract of frequently used dialects: • MySQL5Dialect • OracleDialect • SybaseDialect • SQLServerDialect • HSQLDialect • DerbyDialect The connection.url is a normal JDBC connection URL. 1.1.5. Mapping With the mapping we define in which table column a field of a class is saved. As already stated, we have two options for the mapping. The first one is based on annotation, it is new and the future and I recommend to use it. But it requires Java 5. The second one is based on XML mapping files. I will explain both: Annotation mapping An annotation always starts with an . You just have to add annotations to your java file. Annotations must be imported just like other classes. Honey class with annotations. ..... import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; Entity SequenceGenerator(name = "honey_seq", sequenceName = "honey_id_seq") public class Honey implements Serializable Id GeneratedValue(strategy=GenerationType.SEQUENCE, generator="honey_seq") private Integer id; private String name; private String taste; OneToMany(mappedBy="honey") private SetBee bees = new HashSetBee(); The annotation Entity defines that our class is a mapped class. The primary key is defined by the Id annotations. It is generated by Hibernate using a database sequence. It is defined with SequenceGenerator before it is used by the id (GeneratedValue). The annotation OneToMany describes that the field bees is a 1:n association to the class Bee. The foreign key is defined in the class Bee. Therefore, we have to add the parameter mappedBy. 8Introduction to Hibernate The class Bee uses two other annotations. ManyToOne describes the association/relation from class Bee to Honey. With the annotation JoinColumn we configure that the table bee contains a foreign key column. We did not specify a column name, so Hibernate will choose honey_id. Bee class with annotations. ....... import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; Entity public class Bee implements Serializable Id GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "bee_gen") SequenceGenerator(name = "bee_gen", sequenceName = "bee_id_seq") private Integer id; private String name; ManyToOne JoinColumn private Honey honey; Other databases If your database does not support sequences, you might try Id GeneratedValue(strategy=GenerationType.AUTO) private Integer id; This selects a generator depending on the configured database dialect. XML mapping You only need the XML mapping files, if you don’t use annotations. In the mapping file the mapping from our class Honey to the database table honey is configured. Create a file Honey.hbm.xml in the package de.laliluna.example. Honey.hbm.xml. ?xml version="1.0" encoding="UTF-8"? DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" hibernate-mapping package="de.laliluna.example" class name="Honey" table="thoney" id name="id" column="id" generator class="sequence" param name="sequence"honey_id_seq/param /generator 9Introduction to Hibernate /id property name="name" column="name" type="string" / property name="taste" column="taste" type="string" / set name="bees" inverse="true" key column="honey_id"/key one-to-many class="Honey" / /set /class /hibernate-mapping The tag id specifies the primary key and how it is generated. Normal fields are mapped to a column using the property tag. If we didn’t specify a column name (column=”xyz”), than Hibernate would have chosen the name of the field as default column name. set describes the relation to the class Bee. Our example used a sequence to generate the id. If your database does not support sequences, you might try generator class="native"/ This will choose a generator depending on your database dialect. Why using type=”string” and not type=”java.lang.String”? The Hibernate type can be more precise than the java types. A database field like date, timestamp, time is always handled by a java.util.Date. When you define a type as java.util.Date Hibernate does not know which kind of database type to choose when it generates tables. This is why I use Hibernate types in general. In most cases you don’t need to set the type. Hibernate will guess the column type from the Java class. Needed Libraries To use Hibernate, we need a couple of libraries, alias JAR files. Maven Setup In the sample projects, I have used Maven dependencies. If you know Maven, just copy the POM from the source code and use it. I have declared all dependencies in a parent pom.xml, which is in the root of the workspace. Just switch into the FirstHibernateAnnotation directory and input mvn dependency:resolve in a shell. Alternatively, you can choose a run task from within Eclipse as well by right-clicking on a pom.xml and choosing "Run…" Non Maven Setup If you want to add the libraries manually, here is a list of required libraries and versions. 10Introduction to Hibernate In Eclipse Open your project properties, select “Java Build Path”, click on “Add External Jars” and add at least the libraries shown below to your project path. Included in the Hibernate Core Download. +- junit:junit:jar:4.5:test +- org.slf4j:slf4j-log4j12:jar:1.6.0:compile +- org.slf4j:slf4j-api:jar:1.6.0:compile \- log4j:log4j:jar:1.2.14:compile +- c3p0:c3p0:jar:0.9.1.2:compile +- org.hibernate:hibernate-core:jar:3.6.4.Final:compile +- antlr:antlr:jar:2.7.6:compile +- commons-collections:commons-collections:jar:3.1:compile +- dom4j:dom4j:jar:1.6.1:compile +- org.hibernate:hibernate-commons-annotations:jar:3.2.0.Final:compile +- org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.0.Final:compile \- javax.transaction:jta:jar:1.1:compile +- javassist:javassist:jar:3.9.0.GA:compile Some projects use caching and Hibernate validation. Included in Hibernate Core, Hibernate Validator and Ehcache Download. +- org.hibernate:hibernate-ehcache:jar:3.6.4.Final:compile +- net.sf.ehcache:ehcache-core:jar:2.4.2:compile +- org.hibernate:hibernate-validator:jar:4.1.0.Final:compile \- javax.validation:validation-api:jar:1.0.0.GA:compile Database Driver. +- postgresql:postgresql:jar:8.3-603.jdbc3:compile \- hsqldb:hsqldb:jar:1.8.0.7:compile Database Driver We need a database driver as well. Find the appropriate JDBC Driver for your database and add it to the project libraries. I used PostgreSQL. You can get the driver from http://jdbc.postgresql.org/ . You can use the JDBC 3 driver if you are running a current j2sdk like 1.4 and 1.5/5.0. For MySQL you can use the MySQL connector which can be found at http://www.mysql.com/ products/connector/j/ An Oracle database driver is available at Oracle: http://www.oracle.com 1.1.6. Create a session factory A session factory is important for Hibernate. As the name already indicates, it creates Hibernate sessions for you. A session is all you need to access a database using Hibernate. In addition, a session factory initialises your Hibernate configuration. We need to distinguish Annotation and XML once again. Here comes the Annotation version: 11

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.