
08_ORM.pptx
- Количество слайдов: 49
Java Lecture #8 Database Usage in Java: Object-Relational Mapping Saint Petersburg, 2012
JDBC Overview 1. 2. 3. 4. 5. 6. 7. Load driver or obtain datasource Establish connection using a JDBC URL Create statement Execute statement Optionally, process results in result set Close database resources Optionally, commit/rollback transaction 2
Boiler code 3
Agenda § § Что такое ORM и зачем он нужен? Как использовать ORM в Java? Java Persistence API Hibernate 4
N-Tier Architecture 5
Problem § Согласно ООП, объекты программы = объекты реального мира. class Human { 2. private String name; 3. private List<String> phone. List; 4. private List<String> address. List; 5. } 1. § Такие объекты должны быть преобразованы в форму, в которой они могут быть сохранены в БД ID Имя 1 John 2 Moritz Телефон Адрес +7 9998887777 St. Petersburg, … +49 9998887777 Berlin, … 6
Why to use Object-Relational Mapping (ORM) ? § § § Java objects database tables JDBC – потенциальный источник ошибок и слишком сложен Возможности современного ORM: § Прозрачное хранение объектов (Java. Beans) § Транзитивное хранение § Проверка изменения данных (dirty checking) § Inheritance mapping § Lazy fetching § Outer join fetching § Runtime SQL generation 7
Why to use Object-Relational Mapping (ORM) ? Part II § § § § Естественная модель объектов Более компактный код, поэтому: § Быстрее пишется § Проще читается и поддерживается Код может быть протестирован вне контейнеров Классы могут быть повторно использованы в non-persistent context Оптимальные запросы к БД (smart fetching strategies) Возможности кеширования Бóльшая гибкость при изменении структуры данных/объектов 8
ORM Persistence Subsystem Object Layer Storage Layer Physical Storage System 9
ORM in Java § Использование дополнительных библиотек и шаблонов проектирования § Например, для Java: § Active. JDBC § Enterprise Java Beans § Hibernate § Eclipse. Link JPA § … 10
Active Record § 1. 2. 3. 4. 5. 6. 7. 8. Active. JDBC – реализация шаблона проектирования Active Record Human human = new Human(); human. set. Name("John"); human. get. Address. List(). add("St. Petersburg"); human. get. Phone. List(). add("+79998887777"); human. save(); Human. find. By. Name("John"); INSERT INTO humans(name, address, phone) VALUES ('John', 'St. Petersburg', '+79998887777'); SELECT * FROM humans WHERE name = 'John'; 11
Data Access Object (DAO) § 1. 2. 3. § § § Объект, предоставляющий абстрактный интерфейс к какому-либо типу базы данных или механизму хранения interface My. Dao { List<String> get. All. Names(); } can be used in a large percentage of applications - anywhere data storage is required. hide all details of data storage from the rest of the application. act as an intermediary between the application and the database. They move data back and forth between objects and database records. 12
What is JPA? § § Java Persistence API A specification for generic ORM • • § Based on Annotations • § Metadata Developed out of EJB 3 Specification (since 2006) • • § Not an implementation Vendor-neutral Replacement for train wreck EJB 2 persistence Stand alone specification (does not require JEE container) JPQL • SELECT * FROM Human human WHERE human. name = 'John'; 13
JPA 14
JPA Criteria API § Удобно при создании сложных запросов § Основные классы: § § § javax. persistence. criteria. Criteria. Builder javax. persistence. criteria. Criteria. Query javax. persistence. criteria. Expression javax. persistence. criteria. Predicate javax. persistence. criteria. Path Пример: List cats = sess. create. Criteria(Cat. class). add( Restrictions. like("name", "Fritz%") ). add( Restrictions. or( Restrictions. eq( "age", new Integer(0) ), Restrictions. is. Null("age") ) ). list(); 15
Hibernate 16
What is Hibernate? § § § Very popular open source Java ORM tool Originally developed by Gavin King Now maintained by Redhat (JBoss Group) Implements JPA specification Predates JPA • Has its own custom API for persisting mapped objects 17
Overview § § § JPA Benefits • Standard • Vendor-neutral • Works with EJB 3 Hibernate Benefits • More mature (fully developed) • Works with Java 1. 4 and older Best practice • Use JPA when you can • Use Hibernate API when you need it 18
Hibernate: Architecture § Session. Factory – Singleton, создает объекты Session § Session – взаимодействие между приложением и Hibernate § Transaction. Factory – создает транзакции § Transaction – обертка для транзакций (JTA, JDBC) 19
Using Download Hibernate Components Prepare Database, and Download JDBC Driver Implemented POJO entities and add annotations Implemented client side code via Entity. Manager Persistence. x ml 20
Hibernate: Mapping § § § Hibernate legacy • XML configuration files • Each file mapped a class and it’s persistent fields JPA and Hibernate 3. 2 and above • Annotations (javax. persistence package) • Class-level: marks a class as persistent • Method/File level: configure field and relationship persistence Hibernate still supports XML configuration 21
JPA Annotations § § § § § @Entity @Id @Generated. Value @Column @Join. Column @One. To. One @One. To. Many @Many. To. One @Many. To. Many 22
JPA Annotation Rules § § Any persistent class must be annotated with @Entity (or inherit from a class that does) All persistent classes must have a field annotated by @Id signifying the primary key All instance fields in a persistent class are assumed to be mapped to columns with the same name as the field • @Transient will remove a field from mapping Relationships are not automatically mapped • Relationships are modeled as aggregate members • Require an @One. To. One, @One. To. Many, @Many. To. One, or @Many. To. Many 23
JPA Defaults § § Class annotation @Table defines specific table mappings • Name Field annotation @Column defines specific column mappings • Name • Nullability • Size • Uniqueness 24
Hibernate: Entity § § § Основа Hibernate - Entity Обязательно в каждой Entity должен быть id Entity – Java. Bean: § Конструктор по умолчанию § Геттеры/сеттеры для всех полей Маппинг может осуществляться автоматически или вручную к колонке Аннотировать можно поля или геттеры 25
@One. To. One 26
@One. To. Many 27
@Many. To. One 28
@Many. To. Many 29
Features § § Lazy Loading Cascading Fetch Polymorphic 30
Lazy loading § § § Performance optimization Related items are not retrieved until they are first accessed • Field level access Limited to work only within the Session or Entity. Manager that loaded the parent object • Causes a big problem in web applications 31
Fetch § § § Fetch mode • Lazy • Eager • disable lazy loading Mode can be configured on each relationship Consider performance and use when configuring fetch 32
Cascade § § Tells Hibernate whether to follow the path of the relationship on • Insert • Update • Delete • All Hibernate adds options • Delete All Orphans 33
Inheritance § § JPA and Hibernate support mapping Class inheritance to relational tables Three approaches provided: • Table per class hierarchy • Table per sub class • Table per concrete class 34
Core classes § § Hibernate • Configuration -> Session. Factory -> Session • Session is gateway to persistence functions JPA • Persistence -> Entity. Manager. Factory -> Entity. Manager • Entity. Manager is gateway to persistence functions 35
Entity Manager § § § persist(Obect o) • Saves or updates the specified object tree remove(Object o) • Deletes the specified object find(Class type, Serializable id) • Retrieves the item of the specified type by id merge(Object o) • Attaches a detached instance to the manager (required for update on item retrieved from a different manager) get. Transaction() • Provides a transaction object to perform commit and rollback functions 36
Hibernate: Configuration § § Used to define application persistence properties • Database connection information • Dialect (database-specific language) • Logging • Schema creation parameters Default location is in CLASSPATH JPA • META-INF/persistence. xml Hibernate • hibernate. cfg. xml 37
Hibernate: Configuration 38
Hibernate: Пример 39
Querying § § § JPAQL/HQL Named Queries Criteria By Example Native SQL 40
JPAQL & HQL § § Query languages that are similar to SQL but are more object-centric Supports • Selection of object instances from persistent types • Selection of properties (rather than columns) • Polymorphic selection • Automatic joining for nested properties Should be very comfortable for those familiar with SQL JPAQL is a subset of HQL • Hibernate implementation will support both 41
Example JPAQL § § § § § “from Item i where i. name = ‘foobar’” “from Item i where i. bidder. name = ‘Mike’” // Implicit join “from Car c where c. coupe = true” “from Item i where i. bids is not empty” “from Item i where size(i. bids) > 3” // Implicit join “from Item i order by i. name asc, i. entry. Date asc” “from Item i join i. bids b where b. amount > 100” // will return rows with an array “select distinct(i) from Item i join i. bids b where b. amount > 100” // returns Items “select i. name, i. description from Item i where entry. Date > ? ” 42
Features JPAQL § § § String functions • upper, lower, length, substring, concat, trim Aggregation functions • count, min, max, sum, avg • Can require “group by” clause • Also supports “having” on “group by” Subselects 43
Query parameters JPAQL § § Work just like JDBC Parameters • ? Will act as a placeholder for an indexed parameter • : name will designate a parameter with the name of “name” Examples • select i from Item where name like ? • select i from Item where name like : name 44
How To JPAQL § § § Must be created from the Entity. Manager or Session • Entity. Manger. create. Query(String jpaql) • Session. create. Query(String hql) Query objects can be configured • Maximum number of results • Parameters set Query objects can then be used to list out the results of the query • list() returns a java. util. List 45
Named queries JPAQL § § § Predefined queries that can be executed by name • Standard QL used for query Defined using @Named. Query • Typically above the persistent class the query is for • Defined with name and query values Running the query • Entity. Manager. create. Named. Query(name) • Session. get. Named. Query(name) 46
Criteria and Example Queries § § § Hibernate only feature Full API for programmatically defining the query structure using objects Created by Session Criteria maps all logical restrictions to a query as objects and methods Example query uses an example object as the basis to find other objects • Based on Criteria API 47
Native SQL Queries § § Both JPA and Hibernate support running raw SQL • Session. create. SQLQuery(sql) • Entity. Manager. create. Native. Query(sql) Supports specifying the entity type to convert the results to 48
References § § § § George Reese. Java Database Best Practices John O'Donahue. Java Database Programming Bible Christian Bauer, Gavin King. Hibernate in Action Christian Bauer, Gavin King. Java Persistence with Hibernate JPA in Java. EE 6 Tutorial: http: //docs. oracle. com/javaee/6/tutorial/doc/bnbpy. html Using the Criteria API to Create Queries: http: //docs. oracle. com/javaee/6/tutorial/doc/gjitv. html http: //hibernate. org/docs 49
08_ORM.pptx