Современные технологии баз данных Лекция 7. Объектно-реляционное отображение (ORM) Технология отображения объектов какого- либо объектно-ориентированного.

Slides:



Advertisements
Similar presentations
1 juni 30, 2005 Spring JDBC. 2 juni 30, 2005 Doel Database acties Flexibel Gecontroleerd Productief.
Advertisements

Software Engineering Implementation Lecture 3 ASPI8-4 Anders P. Ravn, Feb 2004.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Introduction to Programming with Java, for Beginners Arrays of Objects.
An Introduction to Hibernate Matt Secoske
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
The Easiest Way To Learn Hibernate: YouTube Videos and the Online Tutorial
Object Persistence using Hibernate
Fresher Technology Specific - JAVA Stream Hibernate Framework
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
1 The Seven Relationship Types Seven types of relationships can exist between entity beans. There are four types of cardinality: one-to- one, one-to-many,
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
JDBC and Hibernate Joshua Scotton. Connecting to Relational DBs.
EJB Entity Beans “Modeling your data”.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Slide 1 EE417: Web Application Development Lecturer: David Molloy Room: XG19 Mondays 10am-1pm Notes: Mailing.
CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Purdue Pride Joe Gutierrez Tung Ho Janam Jhaveri 4/7/2010Purdue Pride1.
JBoss Seam Presented by Andy Nguyen Truc Pham. What is JBoss Seam? Created by Gavin King Created by Gavin King A lightweight framework for Java EE 5.0.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Robert Greiner CSE7330 Southern Methodist University Getting Things Done with Hibernate.
Seminar on. Overview Hibernate. What is it? Hibernate. How does it work? Hibernate Tools.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
Object/Relational Mapping with Hibernate Practical ORM.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
CS 160: Software Engineering November 5 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
자바빈즈와 폼파라미터 처리 Internet Computing KUT Youn-Hee Han.
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CECS 220 Java Test Review. Variable Names 0 May Contain: a-z, A-Z, 0-9, _, $, characters from other languages. 0 May not start with Legal: 0 MyVariable.
CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Enterprise JavaBeans Understanding EJB Components Version 0.1 Kamal Wickramanayake
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
Programming in R SQL in R. Running SQL in R In this session I will show you how to: Run basic SQL commands within R.
10-Nov-15 Java Object Oriented Programming What is it?
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
Hibernate Thuy, Le Huu Pentalog HAN. What is Hibernate? Hibernate is a free, open source Java package that makes it easy to work with relational databases.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Tasks Needed for MissionMapEditor Martin Q. Zhao September 18, 2010.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Library Example February 2010 – August 2010
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
ECE452/CS446/SE464 Design Patterns: Part I Questions A Tutorial by Peter Kim Based on slides prepared by Krzysztof Pietroszek.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying.
IMPLEMENTATION OF CLASS EXTENT by Paweł Świetlicki.
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
1 EJB 3.0: There’s Something Different About You Martin Jäkle, TSBU Middleware.
Современные технологии баз данных
CS6320 – Java Persistence API
OBJECT ORIENTED PROGRAMMING
Object/Relational Mapping with Hibernate
מבוא ל Groovy אליהו חלסצ'י תכנות מתקדם תרגול מספר 12
Java Data Persistence Using Hibernate
null, true, and false are also reserved.
Everything the light touches, Simba, will be yours
Advanced Programming Behnam Hatami Fall 2017.
Internet Computing KUT Youn-Hee Han
Encapsulation.
Presentation transcript:

Современные технологии баз данных Лекция 7

Объектно-реляционное отображение (ORM) Технология отображения объектов какого- либо объектно-ориентированного языка на структуры реляционных баз данных. Поля Отношения

Традиционный подход Получение коллекции объектов: 1.Формирование select запроса 2.Выполнение запроса 3.В цикле по курсору заполнение полей объектов Недостатки: – Смешивание логики получения информации из б.д. и логики обработки полученной информации. – У строки SQL-запроса отсуствует семантика. – Проблема рассогласования схемы данных б.д. и структуры классов приложения.

Объектно-реляционное отображение (ORM) Основные аспекты: Сохранение Загрузка объектов Выборка объектов

ORM. Библиотеки Java: EJB, Hibernate.Net: NHibernate, LINQ Python: SQLAlchemy

Hibernate. Пример Схема данных Схема данных

Hibernate. Класс автобус package logic; import java.util.Set; import java.util.HashSet; public class Bus { private Long id; private String number; private Set drivers = new HashSet(); private Long route_id; public Bus() { } public void setId(Long id) { this.id = id; } public void setNumber(String number) { this.number = number; } public void setDrivers(Set drivers) { this.drivers = drivers; } public void setRoute_id(Long route_id) { this.route_id = route_id; } public Long getId() { return id; } public String getNumber() { return number; } public Set getDrivers() { return drivers; } public Long getRoute_id() { return route_id; } }

Hibernate. Класс водитель package logic; import java.util.Set; import java.util.HashSet; public class Driver { private Long id; private String name; private String surname; private int age; private Set busses = new HashSet(); public Driver() { } public void setBusses(Set busses) { this.busses = busses; } public Set getBusses() { return busses; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSurname(String surname) { this.surname = surname; } public void setAge(int age) { this.age = age; } public Long getId() { return id; } public String getName() { return name; } public String getSurname() { return surname; } public int getAge() { return age; } }

Hibernate. Класс маршрут package logic; import java.util.Set; import java.util.HashSet; public class Route { private Long id; private String name; private int number; private Set busses = new HashSet(); public Route(){ } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setNumber(int number) { this.number = number; } public void setBusses(Set busses) { this.busses = busses; } public Long getId() { return id; } public String getName() { return name; } public int getNumber() { return number; } public Set getBusses() { return busses; } }

Hibernate. На классы отображаются таблицы-сущности. Таблицы отношения отображаются на атрибуты коллекции соответствующих классов.

Hibernate. Настройка отображения.

Hibernate. Настройка отображения

Hibernate. Настройка отображения

Hibernate. Настройка отображения jdbc:mysql://localhost/autopark com.mysql.jdbc.Driver root 1 thread true org.hibernate.dialect.MySQL5Dialect

Hibernate. Интерфейс методов модификации package DAO; import logic.Bus; import logic.Driver; import logic.Route; import java.util.Collection; import java.sql.SQLException; public interface BusDAO { public void addBus(Bus bus) throws SQLException; public void updateBus(Long bus_id, Bus bus) throws SQLException; public Bus getBusById(Long bus_id) throws SQLException; public Collection getAllBusses() throws SQLException; public void deleteBus(Bus bus) throws SQLException; public Collection getBussesByDriver(Driver driver) throws SQLException; public Collection getBussesByRoute(Route route) throws SQLException; }

Hibernate. Реализация модификации данных public class BusDAOImpl implements BusDAO { public void addBus(Bus bus) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession (); session.beginTransaction(); session.save(bus); session.getTransaction().commit(); } catch (Exception e) { …… } finally { if (session != null && session.isOpen()) { session.close(); } } } public void updateBus(Long bus_id, Bus bus) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().ope nSession(); session.beginTransaction(); session.update(bus); session.getTransaction().commit(); } catch (Exception e) { …. } finally { if (session != null && session.isOpen()) { session.close(); } } }

Hibernate. Реализация модификации данных public Collection getAllBusses() throws SQLException { Session session = null; List busses = new ArrayList (); try { session = HibernateUtil.getSessionFactory().open Session(); busses = session.createCriteria(Bus.class).list(); } catch (Exception e) { …. } finally { if (session != null && session.isOpen()) { session.close(); } } return busses; } public void deleteBus(Bus bus) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().open Session(); session.beginTransaction(); session.delete(bus); session.getTransaction().commit(); } catch (Exception e) { …. } finally { if (session != null && session.isOpen()) { session.close(); } } }

Hibernate. Реализация модификации данных public Collection getBussesByDriver(Driver driver) throws SQLException { Session session = null; List busses = new ArrayList (); try { session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Long driver_id = driver.getId(); Query query = session.createQuery( " select b " + " from Bus b INNER JOIN b.drivers driver" + " where driver.id = :driverId " ).setLong(«driverId», driver_id); busses = (List ) query.list(); session.getTransaction().commit(); } finally { if (session != null && session.isOpen()) { session.close(); } } return busses; } public Collection getBussesByRoute(Route route){ Session session = null; List busses = new ArrayList (); try { session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Long route_id = route.getId(); Query query = session.createQuery(«from Bus where route_id = :routeId „).setLong(“routeId», route_id); busses = (List ) query.list(); session.getTransaction().commit(); } finally { if (session != null && session.isOpen()) { session.close(); } } return busses; } }

Hibernate. Наследование Реализация отображения наследуемых классов на таблицы

Hibernate. Наследование <class name="eg.hibernate.mapping.dataobject.Person" table="TB_PERSON" polymorphism="implicit">

Hibernate. Наследование. Запрос HQL

Hibernate. Использование хранимых процедур

LINQ Language Integrated Query LINQ к SQL LINQ к объектам LINQ к XML

LINQ. Выборка данных

LINQ

LINQ. Определние классов Класс Customer Свойтво Customer для класса Order

LINQ. Модификация данных Изменение Удаление

LINQ. Сравнение запросов на выборку с SQL SQL LINQ к SQL

LINQ. Конструирование запроса

LINQ к объектам Подсчет числа строк