|
1
|
|
|
2
|
|
|
3
|
|
|
4
|
- Uses OO query language called HQL
- Uses objects instead of tables and fields instead of columns
- Provides object-to-relational mapping for most DBs
- Separates data layer from business logics
- Uses DB connection info to retrieve DB schema
- Generates DAO beans with data fields mapping table columns
- Generates Insert/Update/Delete/Select statements for DB tables
|
|
5
|
|
|
6
|
|
|
7
|
|
|
8
|
|
|
9
|
- /**
- * @hibernate.class
table="GT_NOTES"
- */
- public class NoteImpl implements Note {
- ….
- }
|
|
10
|
- /**
- * Constructor needed for
hibernate.
- */
- private NoteImpl()
- {
- super();
- }
- /**
- * Constructor used to
construct a note.
- */
- public NoteImpl(String
theNote)
- {
- this.note = theNote;
- }
|
|
11
|
- /**
- * @hibernate.id
column="NOTE_ID" generator-class="sequence"
- * @hibernate.generator-param
name="sequence" value="GT_NOTES_NOTE_ID_S"
- */
- public Integer getId() {
- return id;
- }
- private void setId(Integer id)
{
- this.id = id;
- }
|
|
12
|
- /**
- * @hibernate.many-to-one
- *
class="com.its.ebiz.ddm.model.RecipientImpl"
- * column="RECIPIENT_ID"
not-null="true"
- */
- public Recipient
getRecipient()
- {
- return this.recipient;
- }
- public void setRecipient
(Recipient recipient)
- {
- this.recipient =
recipient;
- }
|
|
13
|
- public String
getRecipientName()
- {
- return this.recipient ==
(null? ”” :
-
this.recipient.getName());
- }
- public void
setWhatever(Whatever w)
- {
- return this.whatever = w;
- }
|
|
14
|
- <!-- Hibernate SessionFactory -->
- <bean
id="sessionFactory"class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
- …
- <property name="mappingResources">
- <list>
-
<value>com/jeppesen/ebiz/ddm/model/NoteImpl.hbm.xml</value>
-
<value>com/jeppesen/ebiz/ddm/model/PkgImpl.hbm.xml</value>
- </list>
- …
- </bean>
|
|
15
|
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE hibernate-mapping>
- - <hibernate-mapping default-cascade="none"
default-access="property" auto-import="true">
- - <class name="com.its.ebiz.ddm.model.NoteImpl"
table="GT_NOTES" mutable="true" polymorphism="implicit"
dynamic-update="false" dynamic-insert="false"
batch-size="1" select-before-update="false"
optimistic-lock="version">
- - <id name="id" column="NOTE_ID" type="java.lang.Integer"
unsaved-value="null">
- - <generator class="sequence">
- <param name="sequence">GT_NOTES_NOTE_ID_S</param>
- </generator>
- </id>
- <many-to-one name="recipient" class="com.its.ebiz.ddm.model.RecipientImpl"
cascade="none" outer-join="auto" update="true"
insert="true" column="RECIPIENT_ID" not-null="true"
unique="false" />
- </class>
- </hibernate-mapping>
|
|
16
|
- <!-- Transactional proxy for
the Recipient primary business object -->
- <bean id="domain" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
- <property name="transactionAttributes">
- <props>
- <prop
key="delete*">PROPAGATION_REQUIRED</prop>
- <prop
key="find*">PROPAGATION_REQUIRED,readOnly</prop>
- </props>
- </property>
- </bean>
|
|
17
|
- ApplicationContext context = new ClassPathXmlApplicationContext (
- "applicationContext-test.xml");
- Façade f = context.getBean(“facadeFactory”);
- Whatever w = f.findWhatever();
- Note n = new NoteImpl(“The note”);
- f.store(n);
|
|
18
|
- <context-param>
- <param-name>
- contextConfigLocation
- </param-name>
- <param-value>
- /WEB-INF/applicationContext.xml
- </param-value>
- </context-param>
|
|
19
|
- Concepts
- Persistance as a Framework for Services
- Let's Consider RDBMS:
- Relational Database Management Systems (RDBMs)
- Often the platform of choice to persist application data
- Mature, stable, portable
- Multi user capabilities
- Security
- Robustness
- Transactional (data integrity)
- Maintain referential integrity
- COTS/OSS Utilities and Tools for reporting and maintenance
|
|
20
|
- Concepts (cont.)
- Object Oriented Programming Languages (OOPLs)
- Often the choice for implementing SOA’s.
- Rich libraries available for web and message based service processing
- All the benefits of an object oriented approach
- Inheritance
- Re-use, reduces duplication of code
- Encapsulation
- Polymorphism
- Reduces coupling between software components
- Makes software more extensible
|
|
21
|
- Concepts (cont.)
- So, we want to use and RDBMS with OOPL… What’s the problem?
- Object-relational Impedance Mismatch
|
|
22
|
- Concepts (cont.)
- Object Relational Modeling (ORM)
- Bridges the gap between object based software and relational
persistence
- Maintain data as objects in software which provides:
- Inheritance, Encapsulation, Polymorphism
- Persist data in a Relational Database that is useful for:
- Reporting / Extracts
- Ad Hoc Queries
- Maintain Referential and Data Integrity
- Automated (transparent) mapping of in memory objects to associated
relational database tables for CRUD and search operations.
- Allows programmers inside of code to treat the data as standard
objects and maintain object oriented design principles and patterns
|
|
23
|
- Concepts (cont.)
- Example: map object oriented software to a relational database
|
|
24
|
- ORM Basic Concepts
- Mapping of database rows to objects
- Entities and their Attributes
- Entity Associations
- Multiplicity
- One-to-One, One-to-Many, Many-to-Many
- Directional relationships
- Inheritance
- Table-per-class, table-per-subclass, table-per-concrete-class
- Mapping Metadata
- Describes the objects and their mapping to underlying database tables
- Type conversion
- Automatic Type conversion
- Ex. Varchar2 à String à Varchar2
- User defined type conversion
- Locking schemes
|
|
25
|
- ORM Basic Concepts (cont.)
- Lazy association loading
- Collection classes (Maps, Sets, Ordered Sets, etc…)
- Support Transactions (unit of work)
- Caching
- Queries
- Specialized Query Languages
(i.e. HQL, JPAQL)
- Support for Native SQL
- Named Queries
- Encapsulation of SQL generation
- Database platform becomes a configuration item
- Transitive Persistence (Cascade)
- Automatic “dirty checking”
|
|
26
|
- Hibernate
- ORM solution
- Provides persistence for Plain Old Java Objects (POJOs)
- Persistence mechanism for Java (standalone) and J2EE (application
server)
- Supports inheritance, polymorphism, encapsulation, composition
- Open Source (GNU Lesser General Public License)
- Doesn’t require preprocessing or extra code generation
- Accessible through Hibernate API or Java Persistence API (EJB 3.0)
- “Hibernate's goal is to relieve the developer from 95 percent of common
data persistence related programming tasks, compared to manual coding
with SQL and the JDBC API.”
|
|
27
|
- Hibernate (cont.)
- Hibernate Core Hibernate for Java, native APIs and XML mapping metadata
- Hibernate Annotations Map classes with JDK 5.0 annotations
- Hibernate EntityManager Standard Java Persistence API for Java SE and
Java EE
|
|
28
|
- Hibernate (cont.)
- Hibernate API
- Hibernate Queries
- Hibernate Query Language (HQL)
- Object based, not schema based
- Results are retrieved as objects or sets of objects
- Support for major SQL functions and operators (i.e. left|right outer
join, group by, min, max, sum, subselects, etc…)
- Support for dynamic fetch parameters
- Criteria based queries
- Polymorphic queries
- Native Queries
- Option to write your own JDBC SQL queries
- Hibernate still provides a translation of results into objects
|
|
29
|
- Hibernate (cont.)
- Hibernate API (cont.)
- Additional features:
- Automated support for conversion between database variants and Java
datatypes
- Support for custom data types
- Automatic “dirty checking”
- Supports long-lived persistence contexts through detach/reattach
- Support for extensive subset of the Java Collections API (with
indexing)
- Inheritance (Table-per-class, table-per-subclass,
table-per-concrete-class)
- Transitive persistence (cascades)
- Optimistic and Pessimistic locking
|
|
30
|
- Hibernate (cont.)
- Hibernate API (cont.)
- SessionFactory
- Heavyweight object created once.
- Reads configuration files and metadata mapping files
- Provides access to the Hibernate Session
- Session
- Lightweight object used to perform most persistent operations
- Provides Persistence Context (cache)
- Responsible for keeping registered persistent objects in sync with
the database
|
|
31
|
|
|
32
|
- EJB3.0 / JPA Overview
- EJB 3.0 is not EJB 2.0 (Entity Beans)
- Standardizes Java ORM into a common API
- Vendors provide implementations of the API
- Hibernate, TopLink, OpenJPA, Kodo, etc…
- Consortium of industry leading experts contributed
- Shows a clear influence from Spring in its use of POJO’s and dependency
injection
- Hibernate’s influence is even more obvious.
- JPA API is very similar to Hibernate
- Most features in Hibernate were incorporated into the JPA
- You do not need an EJB container or Java EE application server in order
to run applications that use JPA persistence.
|
|
33
|
- EJB3.0 / JPA Specifics
- EntityManagerFactory
- EntityManager
|
|
34
|
- EJB3.0 / JPA Specifics (cont.)
- JPA vs. Native Hibernate
- Configuration
- Criteria Based Queries
- Custom Data Types
- JPA QL
- Subset of HQL
- All queries in JPA QL are valid in HQL
- Optimistic Locking
- Vendor extensions
|
|
35
|
|
|
36
|
- @Entity
- @Table(name=‘EMPLOYEE’)
- public abstract class Employee {
- @Id
- @Column(name=‘TAX_ID’)
- private Long employeeId;
- @Column(name=‘FIRST_NAME’)
- private String firstName;
- @Column(name=‘LAST_NAME’)
- private String lastName;
- .
- .
- .
- }
|
|
37
|
- @Entity
- @Table(name=‘EMPLOYEE’)
- @Inheritance( strategy = InheritanceType.SINGLE_TABLE )
- @DiscriminatorColumn (
name=‘SOURCE_RQST_TYPE’,
-
discriminatorType=DiscriminatorType.STRING )
- public abstract class Employee {
- @Id
- @Column(name=‘TAX_ID’)
- private Long employeeId;
- @Column(name=‘FIRST_NAME’)
- private String firstName;
- @Column(name=‘LAST_NAME’)
- private String lastName;
- .
- .
- .
- }
|
|
38
|
- @Entity
- @DiscriminatorValue( ‘SAL‘ )
- public abstract class SalariedEmployee
- extends Employee {
- @Column(name=‘ANNUAL_SALARY’)
- private Double annualSalary;
- .
- .
- .
- }
|
|
39
|
- @Entity
- @DiscriminatorValue( ‘HRLY‘ )
- public abstract class HourlyEmployee
- extends Employee {
- @Column(name=‘HOURLY_RATE’)
- private Double hourlyRate;
- @OneToMany( mappedBy=‘employee‘, cascade = CascadeType.ALL)
- public Collection<Timecard> timecards;
- .
- .
- .
- }
|
|
40
|
- @Entity
- @Table(name=‘TIMECARD’)
- public class Timecard {
- @Id
- @Column(name=‘TIMECARD_ID’)
- private Long timecardId;
- @Column(name=‘HOURS_WORKED’)
- private float hoursWorked;
- @ManyToOne
- @JoinColumn( name=‘TAX_ID‘ )
- Private Employee employee;
- .
- .
- .
- }
|
|
41
|
- <persistence xmlns="http://java.sun.com/xml/ns/persistence"
-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
xsi:schemaLocation=http://java.sun.com/xml/ns/persistence
-
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd
version="1.0">
- <persistence-unit
name="payroll-entities"
transaction-type="RESOURCE_LOCAL">
-
<provider>org.hibernate.ejb.HibernatePersistence</provider>
-
<class>com.company.payroll.Employee</class>
-
<class>com.company.payroll.SalariedEmployee</class>
-
<class>com.company.payroll.HourlyEmployee</class>
-
<class>com.company.payroll.Timecard</class>
- <properties>
- <property
name="hibernate.dialect"
value="org.hibernate.dialect.OracleDialect"/>
- <property
name="hibernate.show_sql" value="true" />
- </properties>
- </persistence-unit>
- </persistence>
|
|
42
|
- EntityManagerFactory entityFactory =
Persistence.createEntityManagerFactory(‘manager’);
- EntityManager em = entityFactory.createEntityManager();
- Employee employee =
- new
HourlyEmployee(12345,‘Ben’,’Franklin’,7.55d);
- em.persist(employee);
- Timecard t1 = new Timecard(1, 50.00);
- Timecard t2 = new Timecard(2, 80.00);
- employee.addTimecard(t1);
- employee.addTimecard(t2);
- em.flush()
|
|
43
|
- Query aQuery = em.createQuery(‘from Employee where firstName=‘John’’);
- List<Employee> results = aQuery.getResultList();
- Iterator<Employee> listIter = results.iterator();
- While (listIter.hasNext()) {
- Employee e = listIter.next();
- System.out.println(e. getFirstName() +
- ‘earned: ‘ +
e.calculatePay());
- }
|
|
44
|
- Resources
- Java Persistence with Hibernate, Gavin King and Christian Bauer,
Manning Publications, C 2007
- http://www.hibernate.org/5.html, JBoss Labs hibernate website – User /
developer documentation
- Sun Microsystems Java Persistence API website – User / developer
documentation:
- http://java.sun.com/javaee/technologies/persistence.jsp
|