260 likes | 502 Views
Architecture Entity Beans Java Persistence API. eric.gerlofsma@hu.nl www.ericgerlofsma.nl. JPA ?. This new API simplifies the development of Java EE and Java SE applications using data persistence. The Java Persistence API is a POJO persistence API for object/relational mapping.
E N D
Architecture Entity BeansJava Persistence API eric.gerlofsma@hu.nl www.ericgerlofsma.nl
JPA ? • This new API simplifies the development of Java EE and Java SE applications using data persistence. • The Java Persistence API is a POJO persistence API for object/relational mapping. • It supports the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. • You can obtain the open source GlassFish project implementation of the Java Persistence API for stand-alone applications.. www.ericgerlofsma.nl
New Style • Next example will show you, • the difference between old style database access, • and new JPA style database access. www.ericgerlofsma.nl
META-INF/persistence.xml <?xml version="1.0" encoding="UTF-8" ?> <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="CIJFERLIJST"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <class>efg.rmi.server.Student</class> <properties> <property name="toplink.target-database" value="oracle.toplink.essentials.platform.database.AccessPlatform"/> <property name="toplink.jdbc.driver" value="sun.jdbc.odbc.JdbcOdbcDriver"/> <property name="toplink.jdbc.user" value="efg"/> <property name="toplink.jdbc.password" value="geheim"/> <property name="toplink.jdbc.url" value="jdbc:odbc:CIJFERLIJST"/> </properties> </persistence-unit> </persistence> You need a driver to a database ! www.ericgerlofsma.nl
POJO Entity Bean Import ... @Entity @Table( name = CijferlijstImpl.tablename ) public class Student implements Serializable { private String name = null; private String cijfer = null; public Student() {} public Student(String newName, String newCijfer) { name = newName; cijfer = newCijfer; } @Id @Column( name = "S_Name" ) public String getName() { return name; } public void setName(String newName) { name = newName; } @Column( name = "S_Cijfer" ) public String getCijfer() { return cijfer; } public void setCijfer(String newCijfer) { cijfer = newCijfer; } } You need a POJO mapping to a database table-entry! www.ericgerlofsma.nl
Entity Manager public void update(String name, String newName, String newCijfer) { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("CIJFERLIJST"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); Student student = entityManager.find(Student.class, name); student.setName(newName); student.setCijfer(newCijfer); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close(); } You need a database connection ! This is a stand-alone example! www.ericgerlofsma.nl
JPA Cijferlijst Application Student Java-bean Entity Manager Database database wrapper www.ericgerlofsma.nl
Java Bean uses 4 annotations • @Entity ( For defining an Entity Bean) • @Table ( For defining the table name ) • @Id ( For defining the primary key ) • @Column ( For defining the column name ) • There are 64 annotations more in JPA! www.ericgerlofsma.nl
javax.persistence.Entity @Target(value=TYPE) @Retention(value=RUNTIME) public @interface Entity { String name; } The optional name of an entity. Defaults to the unqualified name of the entity class. This name is used to refer to the entity in queries. The name must not be a reserved literal in the Java Persistence query language. www.ericgerlofsma.nl
javax.persistence.Table @Target(value=TYPE) @Retention(value=RUNTIME) public @interface Table { String catalog; // The catalog of the table String name; // The name of the table String schema; // The schema of the table UniqueConstraints[] uniqueConstraints; // Unique constraints that are to be placed on the table } This annotation specifies the primary table for the annotated entity. Additional tables may be specified using SecondaryTable or SecondaryTables annotation. If no Table annotation is specified for an entity class, the default values apply. www.ericgerlofsma.nl
javax.persistence.UniqueConstraint @Target(value={}) @Retention(value=RUNTIME) public @interface UniqueConstraint { String[] columnNames; } Required Element An array of the column names that make up the constraint. www.ericgerlofsma.nl
javax.persistence.Id @Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface Id Specifies the primary key property or field of an entity. www.ericgerlofsma.nl
javax.persistence.Column @Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface Column { String columnDefinition; boolean insertable; int length; String name; boolean nullable; int precision; int scale; String table; boolean unique; boolean updatable } Is used to specify a mapped column for a persistent property or field. If no Column annotation is specified, the default values are applied. www.ericgerlofsma.nl
Entity Manager • javax.persistence.Persistence • BootStrap class that is used to obtain an EntityManagerFactory • javax.persistence.EntityManagerFactory • The EntityManagerFactory interface is used by the application to obtain an application-managed entity manager. When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state. • javax.persistence.EntityManager • Interface used to interact with the persistence context. • An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. This interface defines the methods that are used to interact with the persistence context. • The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database. www.ericgerlofsma.nl
Entity Manager Methods • void clear() • void close() • boolean contains(Object entity) • Query createNamedQuery(String name) • Query createNativeQuery(...) • Query createQuery(String qlString) • <T> T find(Class<T> entityClass, Object primaryKey) • void flush() • Object getDelegate() • FlushModeType getFlushMode() • <T> T getReference(Class<T> entityClass, Object primaryKey) • EntityTransaction getTransaction() • boolean isOpen() • void joinTransaction() • void lock(Object entity, LockModeType lockMode) • <T> T merge(T entity) • void persist(Object entity) • void refresh(Object Entity) • void remove(Object Entity) • void setFlushMode(FlushModeType flushMode) Red methods reflect the Lifecycle Blue refers to Identity Management Green refers to Cache Management www.ericgerlofsma.nl
Entity Transaction Methods • void begin() • void commit() • boolean getRollbackOnly() • boolean isActive() • void rollback() • void setRollbackOnly() Red methods reflect the Lifecycle www.ericgerlofsma.nl
Entity Lifecycle Management uit: http://docs.solarmetric.com/full/html/ejb3_overview_em_lifecycle.html http://java.boot.by/scbcd5-guide/ch06.html www.ericgerlofsma.nl
Seven Relationship Types • One-to-one unidirectional • One-to-one bidirectional • One-to-many unidirectional • One-to-many bidirectional • Many-to-one unidirectional • Many-to-one bidirectional • Many-to many bidirectional www.ericgerlofsma.nl
Example ABC-Library Book package efg.library; import . . . @Entity @Table(name = "books", schema = "library") public class Book implements Serializable { private String title = ""; private Customer lendTo = null; @Id @Column(name = "book_title") public String getTitle() { return title; } public void setTitle(String newTitle) { title = newTitle; } @ManyToOne @JoinColumn(name = "book_lendTo") public Customer getLendTo() { return lendTo; } public void setLendTo(Customer customer){ lendTo = customer; } } www.ericgerlofsma.nl
Example ABC-Library Customer package efg.library; import . . . @Entity @Table(name = "customers", schema = "library") public class Customer implements Serializable { private String name = ""; private int credits = 0; private Collection<Book> books = null; @Id @Column(name = "customer_name") public String getName(){return name; } public void setName(String newName){name = newName; } @Column(name = "customer_credits") public int getCredits(){return credits; } public void setCredits(int newCredits){credits = newCredits; } @OneToMany(mappedBy = "lendTo") public Collection<Book> getBooks(){return books; } public void setBooks(Collection<Book> newBooks){books = newBooks; } } www.ericgerlofsma.nl
relationships Book Customer title: String lendTo: Customer name: String credits: int books: Collection n 1 @ManyToOne @JoinColumn( name = "Book_LendTo" ) public Customer getLendTo() { return lendTo; } @OneToMany( mappedBy = "lendTo" ) public Collection<Book> getBooks() { return books; } www.ericgerlofsma.nl
Annotations • @ManyToOne • This annotation defines a single-valued association to another entity class that has many-to-one multiplicity • @OneToMany • Defines a many-valued association with one-to-many multiplicity www.ericgerlofsma.nl
javax.persistence.OneToMany @Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface OneToMany { String mappedBy; CascadeType[] cascade; FetchType fetch; Class targetEntity; } If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified. Enum CascadeType = { ALL, MERGE, PERSIST, REFRESH, REMOVE } Enum FetchType = { EAGER, LAZY } www.ericgerlofsma.nl
javax.persistence.ManyToOne @Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface ManyToOne { boolean optional; CascadeType[] cascade; FetchType fetch; Class targetEntity; } It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced www.ericgerlofsma.nl
Obtaining an EntityManager An EntityManager should be injected directly into an EJB using the @javax.persistence.PersistenceContext annotation. @PersistenceContext( unitName = "LIBRARY" ) private EntityManager em; www.ericgerlofsma.nl
META-INF/persistence.xml <?xml version="1.0" encoding="UTF-8" ?> <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="LIBRARY"> <jta-data-source>java:/DefaultDS</jta-data-source> <class>efg.library.entity.Book</class> <class>efg.library.entity.Customer</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> </properties> </persistence-unit> </persistence> or or update create org.hibernate.dialect.MySQLDialect org.hibernate.dialect.Oracle9Dialet ... www.ericgerlofsma.nl