240 likes | 421 Views
The Java Persistence API. Edel Sherratt. Application and its persistent data. An application has a data model It needs persistent data The persistent data store has a different data model Impedence mismatch How do we deal with impedence mismatch?. Applications Programming Alternatives.
E N D
The Java Persistence API Edel Sherratt
Application and its persistent data • An application has a data model • It needs persistent data • The persistent data store has a different data model • Impedence mismatch • How do we deal with impedence mismatch?
Applications Programming Alternatives • Extend a high level language by embedding query language statements in the language • Extend the query language with with programming language constructs; e.g. SQL procedural language PL/SQL, PL/pgSQL • Provide a call level interface (CLI) from a programming language – e.g. JDBC, XQJ • Use a persistence layer to separate the application logic from the persistent data storage
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
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:"+dbname); • 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 explicit translation between database tables and programming language constructs • The database and the application program are designed separately and made to work together. • The queries are represented as strings in the application and are passed to the database management system. • A persistence layer provides a clearer separation between the application logic and the database. • 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/Teaching/CourseNotes/current/CS12230/codeExamples/0-simple-examples/ • Previously, Contact was made to persist • using a html5 browser cache • using a SQLite database engine, with php and with Java • Next we’ll see how this works with the Java Persistence API
Java Persistence API – main elements • Entity – e.g. Contact; instances are represented as rows in a table • EntityManager– to interact with the database • Persistence Unit – to group related entities together
Contacts Example: files, directories, jars • Contact.java – a class definition with annotations • @Entity says that a class is a persistence object • ContactsGUI.java – includes an EntityManager • EntityManager interacts with the database • in the context of transactions • META-INF – contains persistence.xml • persistence.xml indicates what is to be stored and where • lib – a directory containing necessary jar files
Contact.java • Original example by Lynda, with annotations: @... • @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
If you don’t have an IDE - • 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-01-2008/jw-01-jpa1.html • http://www.javaworld.com/javaworld/jw-01-2008/jw-01-jpa2.html • http://www.roseindia.net/jpa/
In Summary • Most applications need persistent data • The data model that works well for an application is likely to differ from the data model that works well for data storage • The Java Persistence API allows us to separate application design from the persistent data model • Modern IDE’s automate much of the process of creating applications with their persistent data storage