View
217
Download
0
Category
Preview:
Citation preview
8/13/2019 Hibenate With Annotations
1/36
Hibernate With Annotations
Joe McTee
Software Engineermcjoe@jeklsoft.com
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
2/36
About Me 20 years of experience. Aerospace, Test &
Measurement. Biomed, and Telecom
BSEE from U of Wyo, MSEE from CU-Boulder
Wrote firmware for real-time systems for manyyears (assembly, C, and C++)
Moved to pure software job 2 years ago
Employee of Avaya Inc. by day
Working on commercial app for competitivehockey market by night
My website, www.jeklsoft.comwill have a copy ofthis presentation, along with the code
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
3/36
The JPA Java Persistence API
Part of JSR 220, EJB 3.0, see jcp.org
For this talk, the importance is the addition ofannotations and the javax.persistence package
Requires Java 5
Hibernate implements JPA
Be careful regarding overlap betweenjavax.persistence and org.hibernate.annotations
Favor javax package unless you really want theHibernate customization.
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
4/36
My Goals Im not a DB guru, but I need
persistence for my hockey app
Hibernate seemed to be a good solution
Annotations interested me as a way toget away from XML
This talk will cover what I learnedexploring hibernate
but it wont cover everything in depth
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
5/36
My Goals (cont.) In particular, my solution is not very
enterprisey Enterpriseyis a derogatory term describing
sophisticated software architecture which isclaimed to be good enough (robust, flexible, etc.)for use in enterprise applications, but in fact ismerely excessively complex and baroque.
Wikipedia (flagged for removal as a neologism)
If you do have enterprise needs, considerVirtuas for consulting support(http://www.virtuas.com/) Presented excellent talk on JPA in November
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
6/36
POAJOs? A colleague once asked, Is an annotated
POJO still a POJO?
Kind of Zen-like question I tend to think yes, but we can refer to them as
POAJOs if we want.
Outside of the Hibernate environment, they act likenormal POJOs
But They do have dependencies on bothimports and on Java 5
Good topic for discussing over a beer
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
7/36
The Problem
Need to persistently store information
about hockey teams for use in my app
I am using Hibernate defaults as much
as possible, so I am not specifying
everything (convention over config)
A subset of the data I need to storefollows
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
8/36
Class Diagram
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
9/36
Annotating
The POJO
@Entity@Table(name="tbl_pojo")
public class MyPojo
{
Copyright 2007 JEKLsoft
@Entity - required, flags the class as
persistent (makes it an entity bean)
@Table, optional, can be used to map classto existing schema
Default is to use class name
8/13/2019 Hibenate With Annotations
10/36
Annotating
The Class Variables First, need to decide whether you want to
annotate the variables, or the getter methods
Either is OK, but Hibernate doc warns not to mixthe two
Hibernate guesses the strategy based on the
location of @ID annotation
I use variable annotations I like having the persistence code grouped
together
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
11/36
@Id
Defines the primary key for table
Auto generation type lets DB generate
id
Other generation type available
AUTO, TABLE, IDENTITY, SEQUENCE
Also some Hibernate extensions
Copyright 2007 JEKLsoft
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
8/13/2019 Hibenate With Annotations
12/36
@Basic Optional annotation flags variable as persistent
Any non-static, non-transient variable is persisted by
default
Good to use anyway as a documentation aid Also useful if you need to declare fetching strategy (not
covered in this talk)
@Column allows size of VARCHAR to be specified
Copyright 2007 JEKLsoft
@Basic
@Column(length=32)
private String field1;
8/13/2019 Hibenate With Annotations
13/36
@Transient
Tells Hibernate that this variable should
not be persisted
Copyright 2007 JEKLsoft
@Transient
private String field2;
8/13/2019 Hibenate With Annotations
14/36
@OneToOne One to One mapping of two objects
By default, the primary key of Foo object will
be stored in this classes table
Other exotic options I didnt explore
Cascade type ALL indicates that when this
class is persisted, object referenced by
field3 should be automatically persisted
Copyright 2007 JEKLsoft
@OneToOne(cascade = CascadeType.ALL)
private Foo field3;
8/13/2019 Hibenate With Annotations
15/36
Persistent
Collections
Collections used by Hibernate to one-
to-many and many-to-many mappings
Collection, List, Map, and Set supported
I have only used List (in particular
LinkedList)
Specify in the code using java.util.* Under the hood, Hibernate will substitute
its own version of the container
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
16/36
@OneToMany One To Many Mapping
Results in a new table, in this case, MyPojo_Bar
DELETE_ORPHAN, Hibernate extension Not part of JPA
If item removed from list and no other
references, it is removed from DB
Copyright 2007 JEKLsoft
@OneToMany(cascade = CascadeType.ALL)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List field4;
8/13/2019 Hibenate With Annotations
17/36
@ManyToMany Many To Many Mapping
Results in new table
In this case, explicitly named
Copyright 2007 JEKLsoft
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name=mapped_foos")
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List field5;
8/13/2019 Hibenate With Annotations
18/36
Time for the Code Hibernate requires a no-arg constructor
Can be protected or private
Private is less efficient
Favor simple beans, but not required
Copyright 2007 JEKLsoft
public MyPojo()
{
...
}
// getters and setters go here, along with rest of code
}
8/13/2019 Hibenate With Annotations
19/36
Inheritance
Three types SINGLE_TABLE
Entire inheritance hierarchy is stored in a single table
New column, DTYPE, added to table to discriminate subtype
Unused columns are nulled (does not allow non-NULL constraint on
columns of sub-classes)
TABLE_PER_CLASS Each concrete class is stored in a separate table
JOINED Multiple tables are used to store each piece of the inheritance hierarchy
with sub-class tables containing the primary key of the base class table For a great discussion of Pros/Cons of each of the above,
see Inheritance Hierarchies in JPA, Kodali andWetherbee, Java Developers Journal, October 2006 http://eclipse.sys-con.com/read/286901.htm
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
20/36
The Base Class Specify inheritance strategy here
Could be considered a con for annotations versus XML
You need to decide ahead of time that you will be sub-classing
(actually, SINGLE_TABLE is default, so only a con if you use one
of the other strategies).
Copyright 2007 JEKLsoft
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class BaseFoo
{ @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
}
8/13/2019 Hibenate With Annotations
21/36
The Sub-Class Sub-classes do not need to have @ID
The base class ID is used
Copyright 2007 JEKLsoft
@Entity
public class SubFoo extends BaseFoo
{
}
8/13/2019 Hibenate With Annotations
22/36
Remember This?
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
23/36
This is the Schema
Hibernate Generates
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
24/36
The Test Data Following slides show the test data that
is populated in the database
Good way to visualize what Hibernate is
doing
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
25/36
Person Table
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
26/36
Address Table
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
27/36
E-Mail Table
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
28/36
Phone Number
Table
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
29/36
Other Tables
Copyright 2007 JEKLsoft
Person_Email
Person_PhoneNumber
Players_Guardians
8/13/2019 Hibenate With Annotations
30/36
Deleting a Persons
Phone Number
Copyright 2007 JEKLsoft
Person_PhoneNumber PhoneNumber
Not only is phone number
removed for person, it is
removed from database.
This is a result of
DELETE_ORPHANcascade policy (Hibernate
specific).
Result after running TestDelete
8/13/2019 Hibenate With Annotations
31/36
So How Was
The Schema Generated? Class ApplicationRegistry provides the
services necessary to
Generate the schema
Create a database from scratch (mostly)
Open an existing database
Get a SessionFactory object Uses the Hibernate Tools package
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
32/36
Customizable ApplicationRegistry is passed a
SetupPeristence object that contains
database specific information
SetupPeristence is an interface
Concrete implementations supplied for
both HSQLDB and MySql addComponents() method is customized
per application to add all persistent classes
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
33/36
The Test Cases Class HwaTest provides good examples of howto use the various pieces of the example.
testCreate Creates and populates database from scratch
testLoadPlayer Demonstrates use of session.get to load object by
primary key testPlayerQuery
Demonstrates use of simple HQL query to obtain a listof player objects
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
34/36
Tests (cont) testPhoneQuery
Demonstrates use of HQL with parameters toobtain a subset of all PhoneNumber objects
testLazyInitialization Demonstrates how Hibernate lazily fetches data
testRollback Demonstrates how to rollback a transaction
testDelete Demonstrates deleting an object from the
database
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
35/36
References Hibernate
http://hibernate.org/5.html
See doc for Core, Annotations, and Tools
HSQLDB
http://hsqldb.org/web/hsqlDocsFrame.html
Copyright 2007 JEKLsoft
8/13/2019 Hibenate With Annotations
36/36
Time to look at the code!
Pay particular attention to code flagged
with TODO
Thanks for your time!
Feel free to contact me with questions,
comments, and suggestions mcjoe@jeklsoft.com
Copyright 2007 JEKLsoft
Recommended