Современные технологии баз данных

Slides:



Advertisements
Similar presentations
Class Scope class Student { private: string id; string firstName, lastName; float gpa; public: void Read() { cin >> id >> firstName >> lastName >> gpa;
Advertisements

Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
ODBC and JDBC O/R Mapping Amit Shabtay. June 2nd, 2004 Object Oriented Design Course 2 Objects And Databases Most of the applications today are written.
Session-01. Hibernate Framework ? Why we use Hibernate ?
An Introduction to Hibernate Matt Secoske
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
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
BEST PRACTICES - Java By Configuration Use global-forwards/results Helps to avoid duplicate jsp files and redundancy forward mapping.
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.
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.
Hibernate Query Language Make SQL be object oriented – Classes and properties instead of tables and columns – Polymorphism – Associations – Much less verbose.
Dr. Magdi AMER Unit 2 Introduction to Database. Intro Many programs need to save information on disk. The role of DB system is to provide a layer of abstraction.
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.
Object/Relational Mapping with Hibernate Practical ORM.
CS 160: Software Engineering November 5 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
РНР. Уровень 4. Проектирование и разработка сложных веб-проектов на РНР 5 PHP Data Objects.
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
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.
Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces.
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.
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.
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
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.
Enterprise Java v041109Container Managed Relationships1 Container Managed Relationships (CMR) Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.
Library Example February 2010 – August 2010
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying.
NHibernate что, где, когда Артур Дробинский ЗетаСофт Томск, 2012.
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
MANY-TO-MANY MAPPING. May 12, 2011  Implemented using a Set java collection  Mediator table is mandatory – Join table  Join table contains foreign.
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
 Who I am  What is NHibernate? ◦ Object Relational Mapper ◦ A framework for building advanced frameworks ◦ Ported from Java ◦ A wide NHibernate ecosystem.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Современные технологии баз данных Лекция 7. Объектно-реляционное отображение (ORM) Технология отображения объектов какого- либо объектно-ориентированного.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Service Provider Interface & Data Access Layers Technion – Institute of Technology
CS6320 – Java Persistence API
J2EE Lecture 8: Hibernate
JDBC 15-Apr-18.
A very brief introduction
Interfaces.
JDBC 21-Aug-18.
What is Encapsulation, Benefits, Implementation in Java
Object/Relational Mapping with Hibernate
מבוא ל Groovy אליהו חלסצ'י תכנות מתקדם תרגול מספר 12
Java Data Persistence Using Hibernate
JDBC 15-Nov-18.
null, true, and false are also reserved.
Hibernate Bayu Priyambadha, S.Kom.
Object/Relational Mapping with Hibernate
Week 5 Review & Announcement
Making Text for the Web part 6
plus content providers, loaders, recyclerview
SQL AUTO INCREMENT Field
Presentation transcript:

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

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

Традиционный подход Получение коллекции объектов: Недостатки: Формирование select запроса Выполнение запроса В цикле по курсору заполнение полей объектов Недостатки: Смешивание логики получения информации из б.д. и логики обработки полученной информации. У строки 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-mapping>   <class name=«logic.Bus» table=«buses»>     <id column=«bus_id» name=«id» type=«java.lang.Long»>       <generator class=«increment»/>     </id>     <property column=«number» name=«number» type=«java.lang.String»/>          <set name=«drivers» table=«busDriver» lazy=«false»>       <key column=«bus_id»/>       <many-to-many column=«driver_id» class=«logic.Driver»/>     </set>   </class> </hibernate-mapping>.

Hibernate. Настройка отображения <hibernate-mapping>   <class name=«logic.Driver» table=«drivers»>     <id column=«driver_id» name=«id» type=«java.lang.Long»>       <generator class=«increment»/>     </id>     <property column=«name» name=«name» type=«java.lang.String»/>     <property column=«surname» name=«surname» type=«java.lang.String»/>     <property column=«age» name=«age» type=«java.lang.Integer»/>     <set name=«busses» table=«busDriver» lazy=«false»>       <key column=«driver_id»/>       <many-to-many column=«bus_id» class=«logic.Bus»/>     </set>   </class> </hibernate-mapping>

Hibernate. Настройка отображения <hibernate-mapping>   <class name=«logic.Route» table=«routes»>     <id column=«route_id» name=«id» type=«java.lang.Long»>       <generator class=«increment»/>     </id>     <property column=«name» name=«name» type=«java.lang.String»/>     <property column=«number» name=«number» type=«java.lang.Integer»/>     <set name=«buses» lazy=«false»>       <key column=«route_id»/>       <one-to-many class=«logic.Bus»/>     </set>   </class> </hibernate-mapping>

Hibernate. Настройка отображения <hibernate-configuration>   <session-factory>     <property name=«connection.url»>jdbc:mysql://localhost/autopark</property>     <property name=«connection.driver_class»>com.mysql.jdbc.Driver</property>     <property name=«connection.username»>root</property>     <property name=«connection.password»/>     <property name=«connection.pool_size»>1</property>     <property name=«current_session_context_class»>thread</property>     <property name=«show_sql»>true</property>     <property name=«dialect»>org.hibernate.dialect.MySQL5Dialect</property>     <mapping resource=«logic/Bus.hbm.xml»/>     <mapping resource=«logic/Driver.hbm.xml»/>     <mapping resource=«logic/Route.hbm.xml»/>   </session-factory>    </hibernate-configuration>

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().openSession();       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<Bus>();     try {       session = HibernateUtil.getSessionFactory().openSession();       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().openSession();       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<Bus>();     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<Bus>) 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<Bus>();     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<Bus>) query.list();       session.getTransaction().commit();     } finally {       if (session != null && session.isOpen()) {         session.close();       }     }     return busses;   } }

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

Hibernate. Наследование <hibernate-mapping> <class name="eg.hibernate.mapping.dataobject.Person" table="TB_PERSON" polymorphism="implicit"> <id name="id" column="ID"> <generator class="assigned"/> </id> <set name="rights" lazy="false"> <key column="REF_PERSON_ID"/> <one-to-many class="eg.hibernate.mapping.dataobject.Right" /> </set> <joined-subclass name="eg.hibernate.mapping.dataobject.Individual" table="TB_INDIVIDUAL"> <key column="id"/> <property name="firstName" column= "FIRST_NAME" type="java.lang.String" /> <property name="lastName" column= "LAST_NAME" type="java.lang.String" /> </joined-subclass> <joined-subclass name= "eg.hibernate.mapping.dataobject.Corporation" table="TB_CORPORATION"> <property name="name" column="NAME" type="string" /> <property name="registrationNumber" column ="REGISTRATION_NUMBER" type="string" /> </class> </hibernate-mapping>

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

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

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

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

LINQ

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

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

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

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

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