JPA2 BRIEF INTRO                                by Tiziano Lattisimercoledì 13 febbraio 13
WHAT IS JPA2               Java Persistence API               JPA2 in Java EE 6 (JPA1 in Java EE 5)               It’s a O...
AND...               annotation || XML descriptor (configuration by exception)               POJO (Plain Old Java Object) ...
CASE STUDY: LIBRARY               The library contains several books               The library can loan one or more books ...
O/RM                public class Person {                    private Long id;                                          PER...
O/RM                    to map variables to database columns                    to handle data types between database and ...
PERSISTENCE.XML         <?xml version="1.0" encoding="UTF-8"?>         <persistence version="2.0" xmlns:xsi="http://java.s...
IDE HELPS US               example:               PU setup in               Netbeans 7.2 IDEmercoledì 13 febbraio 13
BY ANNOTATION      @Entity      @Table(name = "person")      public class Person implements Serializable {             @Id...
BY XML DESCRIPTOR        <entity-mappings>            ...            <entity class="com.axiastudio.pypapi.demo.entities.Pe...
SEQUENCE              by annotation             @SequenceGenerator(name="genBook", sequenceName="book.book_id_seq",       ...
INSERT        import         javax.persistence.EntityManager;        import         javax.persistence.EntityManagerFactory...
SELECT           CriteriaBuilder cb = em.getCriteriaBuilder();           CriteriaQuery<Book> cq = cb.createQuery(Book.clas...
SELECT (CRITERIA)           CriteriaBuilder cb = em.getCriteriaBuilder();           CriteriaQuery<Book> cq = cb.createQuer...
UPDATE           CriteriaBuilder cb = em.getCriteriaBuilder();           CriteriaQuery<Person> cq = cb.createQuery(Person....
DELETE             Person person = new Person();             person("Tiziano");             person("Lattisi");            ...
AND NOW...                                          Thank you.                                        Tiziano Lattisi     ...
Upcoming SlideShare
Loading in …5
×

JPA2 - a brief intro

631 views
538 views

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
631
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
6
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

JPA2 - a brief intro

  1. 1. JPA2 BRIEF INTRO by Tiziano Lattisimercoledì 13 febbraio 13
  2. 2. WHAT IS JPA2 Java Persistence API JPA2 in Java EE 6 (JPA1 in Java EE 5) It’s a O/RM (Object Relational Mapping) Framework to provide persistence An object is a row in a master table (...)mercoledì 13 febbraio 13
  3. 3. AND... annotation || XML descriptor (configuration by exception) POJO (Plain Old Java Object) based Outside container (no server required) No Bean interface required (no implements Serializable) Different persistence providers (Hibernate, EclipseLink, ...)mercoledì 13 febbraio 13
  4. 4. CASE STUDY: LIBRARY The library contains several books The library can loan one or more books to a person Actors: Library, Book, Person, Loanmercoledì 13 febbraio 13
  5. 5. O/RM public class Person { private Long id; PERSON private String name; PK ID private String surname; private Date birthday; ? NAME private Collection<Loan> loanCollection; SURNAME public Person() {} GENRE /* accessor methods */ } LOAN public class Loan { PK ID private Long id; FROMDATE private Date fromdate; private Date todate; TODATE private Person person; FK PERSON private Book book; FK BOOK public Loan(){ } } BOOK public class Book { PK ID private Long id; private String title; TITLE private String description; DESCRIPTION public Book(){ } GENRE }mercoledì 13 febbraio 13
  6. 6. O/RM to map variables to database columns to handle data types between database and Java to map tables references in relationship between objects to manage the cycle of life of the objectmercoledì 13 febbraio 13
  7. 7. PERSISTENCE.XML <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns:xsi="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_2_0.xsd"> <persistence-unit name="DemoPU" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:demo"/> <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/> <property name="javax.persistence.jdbc.user" value=""/> <property name="javax.persistence.jdbc.password" value=""/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> <class>com.axiastudio.pypapi.demo.entities.Book</class> <class>com.axiastudio.pypapi.demo.entities.Loan</class> <class>com.axiastudio.pypapi.demo.entities.Person</class> </persistence-unit> </persistence>mercoledì 13 febbraio 13
  8. 8. IDE HELPS US example: PU setup in Netbeans 7.2 IDEmercoledì 13 febbraio 13
  9. 9. BY ANNOTATION @Entity @Table(name = "person") public class Person implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "birthday") @Temporal(TemporalType.DATE) private Date birthday; @OneToMany(mappedBy = "person", orphanRemoval = true, cascade=CascadeType.ALL) private Collection<Loan> loanCollection; public Person() { } /* accessor methods */ }mercoledì 13 febbraio 13
  10. 10. BY XML DESCRIPTOR <entity-mappings> ... <entity class="com.axiastudio.pypapi.demo.entities.Person" metadata-complete="true"> <table-name="PERSON"/> <attributes> <id name="id"/> <id name="name"/> <id name="surname"/> <id name="birthday"/> <id name="id"/> </attributes> </entity> </entity-mappings>mercoledì 13 febbraio 13
  11. 11. SEQUENCE by annotation @SequenceGenerator(name="genBook", sequenceName="book.book_id_seq", initialValue=1, allocationSize=1) @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="genBook") private Long id; by descriptor <id name="id"> <generated-value strategy="SEQUENCE" generator="genBook"/> <sequence-generator name="genBook" sequence-name="book.book_id_seq"/> </id>mercoledì 13 febbraio 13
  12. 12. INSERT import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.axiastudio.pypapi.demo.entities.Book; import com.axiastudio.pypapi.demo.entities.Genre; EntityManagerFactory emf = Persistence.createEntityManagerFactory("DemoPU"); em = emf.createEntityManager(); Book book = new Book(); book.setTitle("Dubliners"); book.setDescription("a collection of 15 short stories"); book.setGenre(Genre.ROMANCE); em.getTransaction().begin(); em.persist(book); em.getTransaction().commit();mercoledì 13 febbraio 13
  13. 13. SELECT CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Book> cq = cb.createQuery(Book.class); TypedQuery<Book> tq = em.createQuery(cq); List<Book> books = tq.getResultList(); for( Book book: books ){ switch (book.getDescription()) { case "Anna Karenina": assert "ROMANCE".equals(book.getGenre().toString()); break; case "Pro JPA": assert "REFERENCE".equals(book.getGenre().toString()); break; } } }mercoledì 13 febbraio 13
  14. 14. SELECT (CRITERIA) CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Book> cq = cb.createQuery(Book.class); Root from = cq.from(Book.class); // from.get("description") Predicate predicate = cb.like(from.get(Book_.description), "%very%"); cq = cq.where(predicate); TypedQuery<Book> tq = em.createQuery(cq); List<Book> books = tq.getResultList(); assert books.size() == 1; assert "Anna Karenina".equals(books.get(0).getTitle()); Book book = tq.getSingleResult(); assert "Anna Karenina".equals(book.getTitle());mercoledì 13 febbraio 13
  15. 15. UPDATE CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Person> cq = cb.createQuery(Person.class); Root from = cq.from(Person.class); cq = cq.where(cb.and(cb.equal(from.get(Person_.name), "Tiziano"), cb.equal(from.get(Person_.surname), "Lattisi"))); TypedQuery<Person> tq = em.createQuery(cq); Person person = tq.getSingleResult(); assert "Tiziano".equals(person.getName()); assert person.getEmail() == null; Long key = person.getId(); person.setEmail("tiziano.lattisi@gmail.com"); Person personByKey = em.find(Person.class, key); assert "tiziano.lattisi@gmail.com".equals(personByKey.getEmail()); em.detach(person); person = em.find(Person.class, key); assert ! "tiziano.lattisi@gmail.com".equals(person.getEmail()); person.setEmail("tiziano.lattisi@gmail.com"); em.getTransaction().begin(); em.merge(person); em.getTransaction().commit(); Person personByKey2 = em.find(Person.class, key); assert "tiziano.lattisi@gmail.com".equals(personByKey2.getEmail());mercoledì 13 febbraio 13
  16. 16. DELETE Person person = new Person(); person("Tiziano"); person("Lattisi"); em.getTransaction().begin(); em.persist(person); em.getTransaction().commit(); Long aPrimaryKey = person.getId(); [...] Person person = em.find(Person.class, aPrimaryKey); em.getTransaction().begin(); em.remove(person); em.getTransaction().commit(); person = em.find(Person.class, aPrimaryKey); assert person == null;mercoledì 13 febbraio 13
  17. 17. AND NOW... Thank you. Tiziano Lattisi Me: http://www.linkedin.com/in/tizianolattisi/ Slides: http://www.slideshare.net/lattisi/ Examples: http://tinyurl.com/crn3wwqmercoledì 13 febbraio 13

×