JavaPersistence

advertisement
The Java Persistence API
Edel Sherratt
Contents
• Revisit applications programming
• Using Java Persistence API
Applications Programming Alternatives
• Extend a high level language by embedding
SQL statements in it
• Extend SQL with programming language
constructs
• Provide a call level interface (CLI) from a
programming language
Applications Programming with a
Call Level Interface
• Obtain a handle on the database
• Send SQL queries to the database
management system using query functions
• Process the results of those queries
– Results are tables and must be transformed into
types that the application program can use
– Use a cursor to access rows of the result set
– Fetch each row in turn; represent as an array or
associative array or other suitable structure
PHP connection to a database
• Obtain a database handle: e.g., pg_connect,
mysql_connect, sqlite_open
• Execute queries: e.g. pg_query, sqlite_query,
mysql_query
• Process results of the query: e.g.
mysql_fetch_array, pg_fetch_array,
sqlite_fetch_array, and many others
Java JDBC
• Driver manager provides implementations of
Connection, Statement and ResultSet
• Connection acts as database handle
• Statement enables creation and execution of
SQL queries
• ResultSet maintains a cursor, enabling access
to current row of data returned by query
Example from the Java Dungeon
• this.connection =
DriverManager.getConnection("jdbc:sqlite:"+dbn
ame);
• statement.executeUpdate(
"create table character (" +
"name varchar(20) primary key," +
"description text," +
"kind varchar(20)," +
"location varchar(20) references
location(name));");
Processing the result set
• ResultSet things = whats_at(my_location);
if (things.next()) {
System.out.println
("\nYou consider taking:");
do {
System.out.println(
things.getString("name") );
} while (things.next());
}
Java Persistence
• With a CLI, there is a clear and explicit
translation between database tables and
programming language constructs
• The database and the application program are
designed separately and made to work
together.
• The Java Persistence API allows us to design
with objects, and have the library functions
deal with the translation to and from tables.
From CS12220 – Contacts.java
• http://www.aber.ac.uk/~dcswww/Dept/Teachi
ng/CourseNotes/current/CS12230/code/1week1-in-lab/0-simple-examples/
• A simple example, but wouldn’t it be good to
have contacts persist in a database
Java Persistence API – main elements
• Entity – like Contact; instances are
represented as rows in a table
• And an EntityManager – to interact with the
database
• And a Persistence Unit – to group related
entities together
Files, Directories and Jars
• Contact.java – a class definition with some
extra annotations
• AddContacts.java – includes an EntityManager
that allows me to place contacts in the
database
• META-INF – a directory containing
MANIFEST.MF and persistence.xml
• lib – a directory containing necessary jar files
Contact.java
• Original example by Lynda, with annotations: @blah
• @Entity(name= "Contact")
public class Contact {
@Id // the primary key
@Column (name = "name", nullable = false)
private String name; //name of contact
public String getName() { return
this.name; }
@Column (name="phone")
private String phone; //phone of contact
… etc.
• The annotations are defined in javax.persistence
AddContact.java
• EntityManagerFactory – creates an entity
manager factory for the persistence unit –
must match the persistence unit named in
META-INF/persistence.xml
• EntityManager – interacts with the database
• A loop that reads in names and numbers and
stores them in the database
• Notice how transactions are defined and used
META-INF/persistence.xml
•
•
•
•
Names the persistence unit
And the persistence provider
And the class to be persisted
And various properties like those we saw in
connection strings previously
META-INF/MANIFEST.MF
• The class path
• The main class
Compiling, Packaging and Running the
Application
• java <source files> -cp <classpath to
javax.persistence> <destination for classes>
• jar cvmf META-INF/MANIFEST.MF <jar to be
created> <classes to be packaged> META-INF
• java –jar <the jar that was created>
• NB: you can run the jar anywhere, but do
make sure the library jars are where
MANIFEST/META-INF says they will be!
Changing to another database
• The java sources stay the same
• The Class Path entry in
META-INF/MANIFEST.MF changes to reflect
the new database connection jar
• Some properties in META-INF/persistence.xml
are changed to reflect the new database
Using an IDE
• Normally, you would use an IDE like Netbeans
or Eclipse to build your JPA application
• Netbeans will create a directory called dist
containing your executable jar and a lib
directory
• You can zip the jar and the lib into a single file
that can be run anywhere
Annotating relationships
•
•
•
•
•
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
None of these is bidirectional
Bidirectional Relationships
• Every relationship has an owning side
• and an inverse side that maps to the owning
side
• Annotate both sides to form a bidirectional
relationship
• Design options like those for object-oriented
database systems
A more complete example with
relationships
•
•
•
•
Neil Taylor
Department-Employee
Run as a Netbeans project
Or zip the distribution to run standalone
Online tutorials
• http://www.javaworld.com/javaworld/jw-012008/jw-01-jpa1.html
• http://www.javaworld.com/javaworld/jw-012008/jw-01-jpa2.html
• http://www.roseindia.net/jpa/
In Summary
• There are many ways to construct database
applications
• The Java Persistence API allows us to focus on
object oriented design
• Modern IDE’s automate much of the process
of creating database applications
Download