Softlogia S.R.L. Formación de Recursos Humanos Hibernate Core Instructor: Martin R. Baspineiro.

Slides:



Advertisements
Presentaciones similares
JEE Entity Enterprise Beans Herencia. 2009Ing. de Sistemas II2 Herencia y Polimorfismo en Entity Beans Los Entity Beans son clases Java comunes que soportan.
Advertisements

Programación orientada a objetos en Visual Basic .NET
Rocío Contreras Águila Primer Semestre 2010
El uso de Internet con software libre y fuentes abiertas para colaborar en la toma de decisiones espaciales: la herramienta MapChat G. Brent Hall Michael.
Desarrollo de una Aplicación Web sobre tecnología Microsoft .NET
ESP 29/2/12 ObjectiveBell work Students will be able to use the imperfect tense When do we use the preterite tense? Share this with your partner.
ACCESO A BASES DE DATOS ORACLE CON PHP
Teoría de los lenguajes Proyecto SIGU Equipo Nº3 Universidad Argentina J. F. Kennedy Sede: Don Bosco Integrantes: Irene Arias Fernández Mariana Pacheco.
Lenguaje de consulta de Hibernate
Francisco Moreno Bases de Datos II Universidad Nacional
JAVA Persistence API (JPA)
Editing Slides With Polaris Office, you can create new .ppt and .pptx presentations or edit your presentation with ease.
Tema 3 J2EE Java Database Connectivity Temas Selectos de Cómputo Grupo 912.
Java Persistance API JPA.
¿Qué hora es? What time is it?. ¿Qué hora es? It’s 1:00 Es la una (notice we do not say uno for time but una) 1:00 is the ONLY time where we say “Es la…”
ARQUITECTURA DISTRIBUIDA ARQUITECTURA DISTRIBUIDA.
Persistencia de Objetos. Definicion Persistencia : El la capacidad de un objecto to continuar existiendo despues que su creador (programa que crea este)
Programación orientada a objetos
Bases de Datos Relacionales
Ms. Martinez September 3, 2014 Spanish 1 Instructions:  You need to write the notes in your Spanish journals.  Write the translation next to the Spanish.
D Copyright © 2010, Oracle y/o sus filiales. Todos los derechos reservados. Uso de SQL*Plus.
Bases de datos en la Web n Las bases de datos permiten almacenar de una forma estructurada y eficiente toda la información de un sitio web n Ventajas –Proporcionar.
UNITA - IBARRA TRIGGERS
Telling Time.
¿Qué hora es? Son las diez.
SPRING JDBC Curso: Programación orientada a objetos
4.1 Continuidad en un punto 4.2 Tipos de discontinuidades 4.3 Continuidad en intervalos.
El Pretérito The preterite tense is used to express actions that began and ended at a definite time in the past.
-AR Verbs In Spanish, there are three classes (or conjugations) of verbs: those that end in –AR, those that end in –ER, and those that end in –IR. This.
Frameworks de Persistencia Java Prof. Ing. Esteban Ramírez
Informatic Topics M. Sc. Juan Carlos Olivares Rojas February, 2009.
MORE CONVERSATION TOOLS
--AR verb conjugations in the Present tense.   Remember!  While watching the tutorial, take notes in your Spanish notebook.  You can pause, stop and.
REFERENCIA DIRECTA INSEGURA A OBJETOS
Arquitectura de Oracle
Servlets Servlets son módulos que extienden a servidores orientados a request/response, como por ejemplo Servidores Web “java-enabled”. Un servlet puede.
Curso de Java y Aplicaciones Web Facultad Politécnica – U.N.A. Ing. Esteban Ramírez Persistencia Java.
Los Adjetivos. Hoy veremos… How adjectives work in Spanish Practice the use of adjectives.
The Future Tense -original PowerPoint created by Mrs. Shirley of North Intermediate High School in Broken Arrow, OK.
Tener -= to have. Tener Tener is a new verb, but you have already seen two of the forms from TENER in the last chapter. Tener is a new verb, but you have.
Persistencia de Objetos. Definicion Persistencia : El la capacidad de un objecto to continuar existiendo despues que su creador (programa que crea este)
JUEVES, EL 10 DE SEPTIEMBRE LT: I WILL RECOGNIZE SOME NEW VOCABULARY WORDS. Go over tests & retake procedures Interpretive Assessment: numbers & alphabet.
CLASE DE NUTRICION MAESTRA MARTA. TITLE AND CONTENT LAYOUT WITH LIST ▪ Add your first bullet point here ▪ Add your second bullet point here ▪ Add your.
JDBC. Definición Java Database Conectivity El acceso a bases de datos JDBC implica abrir una conexión ejecutar comandos SQL en un sentencia procesar los.
Calentamiento Read the hand-out from the sub and answer the following questions: 1)¿Qué tiempo hace en Ecuador? 2)¿Cuántas clases tiene Ramón? 3)¿Qué.
Review. REVIEW from ALL classes! Greet us! Your name Your age Your birthday Your telephone number Where you are from How many brothers you have –Tengo.
Essential question: How do I say what I like and what interests/bores me?
Programación en Visual Basic
Sentencias DDL y DML PostgreSQL. Base de Datos I – Fundamentos Básicos PostgreSQL PostgreSQL es un servidor de base de datos relacional libre bajo la.
6 Triggers ORACLE - II Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega.
Motor de Persistencia - Mapeos. El mapeo Objeto - Relacional es un acercamiento entre el Modelo de Objetos y el Modelo Relacional, para poder persistir.
Programación orientada a objetos Capítulo 3 Interacción de objetos.
DML Transact SQL Sesión X Triggers. Duración 2 Horas.
Saber Vs. Conocer Sra. Altamirano Español II. First, we need to learn the conjugation of the verb SABER Yo sé Tú Sabes él, ella,ud. Sabe Nosotros Sabemos.
Softlogia S.R.L. Formación de Recursos Humanos Spring Instructor: Martin R. Baspineiro.
Softlogia S.R.L. Formación de Recursos Humanos Hibernate Core Instructor: Martin R. Baspineiro.
6 Triggers ORACLE - III Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega.
C39 – Gestión de campañas Lean Diagrama de proceso EHP3 para SAP CRM 7.0.
C62: Gestión de actividades mediante la conexión de escritorio para SAP CRM Diagrama de proceso EHP3 para SAP CRM 7.0.
Welcome! Conversation Classes. Remembering Names Everyone Stand! Introduce yourself to class and give your name an action! Go around the class and try.
Bienvenidos.
Canciones.
Getting to know you more!
Base de Datos II 2da Parte. Propiedad ACID  La propiedad ACIDa es una carácterística de un DBMS para poder compartir datos en forma segura.  A :
JKSimMet Software (windows & buttons) Split Engineering Chile Ltda. General Salvo #331 oficina 201 Casilla Sucursal Panorámico Providencia – Santiago,
Fundamentals of Web Development - 2 nd Ed.Randy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar © 2017 Pearson.
Día 2 –Español 4 NS (HL) y NM (SL)
Spanish I Chapter 1 Gramática 1-2 Page 24
Miss Gabriela García and miss carolina ortiz
ACTIVITY 2 Information, their names, where they are from and what they do for a living.
Transcripción de la presentación:

Softlogia S.R.L. Formación de Recursos Humanos Hibernate Core Instructor: Martin R. Baspineiro

Hibernate Core – Clase 2 Temario  Conceptos  Mapeo de Relaciones Asociación unidireccional Trabajando con la asociación unidireccional Colección de valores Asociación bidireccional Trabajando con la asociación bidireccional  Configuración  Criteria Query Concepto Filtrando una tabla Asociaciones Ordenación Projections  Practica

Hibernate Core – Clase 2 Conceptos  Flushing: es el proceso de sincronización del estado de un objeto persistente en memoria con la base de datos. Usualmente ocurre al final de una transacción.  Eager Fetch: carga ansiosa.  Lazy Fetch: carga perezosa.

Hibernate Core – Clase 2 Mapeo de Relaciones  Agregando una Colección de objetos de una clase de dominio a nuestra clase de dominio basada en una relación de la base de datos es posible navegar fácilmente a través de la asociación.  Hibernate representa las asociaciones multivaluadas por medio de una Collection del jdk.

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Es una asociación establecida únicamente desde un extremo de la asociación. Ejemplo, modelo de datos: _____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | |_____________| |__________________| | PERSON | | | | | |_____________| | *EVENT_ID | | *EVENT_ID | | | | EVENT_DATE | | *PERSON_ID | | *PERSON_ID | | TITLE | |__________________| | AGE | |_____________| | FIRSTNAME | | LASTNAME | |_____________| < Asociación unidireccional

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Ejemplo, clase de dominio: Agregando una collection de Eventos a la clase Person, podemos navegar a través de los eventos de una persona particular sin necesidad de realizar una query. public class Person { private Set events = new HashSet(); public Set getEvents() { return events; } public void setEvents(Set events) { this.events = events; }

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Ejemplo, archivo de mapeo: Se requiere la tabla relacionada many-to-many marca la multiplicidad.

Hibernate Core – Clase 2 Mapeo de relaciones  Asociación unidireccional Ejemplo, trabajando con la asociación bidireccional: Automatic dirty checking, Hibernate automáticamente detecta si hubo un cambio y lo persiste, sin necesidad de un update o save, mientras que su estado sea persistente. private void addPersonToEvent(Long personId, Long eventId) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); Event anEvent = (Event) session.load(Event.class, eventId); aPerson.getEvents().add(anEvent); session.getTransaction().commit(); }

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unilateral Ejemplo, trabajando con una asociación bidireccional: private void addPersonToEvent(Long personId, Long eventId) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session.createQuery("select p from Person p left join fetch p.events where p.id = :pid")‏.setParameter("pid", personId)‏.uniqueResult(); // Eager fetch the collection so we can use it detached Event anEvent = (Event) session.load(Event.class, eventId); session.getTransaction().commit(); // End of first unit of work aPerson.getEvents().add(anEvent); // aPerson (and its collection) is detached // Begin second unit of work Session session2 = HibernateUtil.getSessionFactory().getCurrentSession(); session2.beginTransaction(); session2.update(aPerson); // Reattachment of aPerson session2.getTransaction().commit(); }

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Colección de valores, se trata de una colección de valores y no de objetos de dominio como por ejemplo Eventos. Ejemplo, modelo de datos: _____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | ___________________ |_____________| |__________________| | PERSON | | | | | | | |_____________| | PERSON_ _ADDR | | *EVENT_ID | | *EVENT_ID | | | |___________________| | EVENT_DATE | | *PERSON_ID | | *PERSON_ID | | *PERSON_ID | | TITLE | |__________________| | AGE | | * _ADDR | |_____________| | FIRSTNAME | |___________________| | LASTNAME | |_____________|

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Colección de valores, se trata de una colección de valores y no de objetos de dominio como por ejemplo Eventos. Ejemplo, clase de dominio Person: private Set Addresses = new HashSet(); public Set get Addresses() { return Addresses; } public void set Addresses(Set Addresses) { this. Addresses = Addresses; }

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Colección de valores Ejemplo, archivo de mapeo:

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación unidireccional Colección de valores Ejemplo, trabajando con una colección de valores: private void add ToPerson(Long personId, String Address) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); // adding to the Address collection might trigger a lazy load of the collection aPerson.get Addresses().add( Address); session.getTransaction().commit(); }

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación bidireccional Es una asociación establecida desde ambos extremos de la asociación. Ejemplo, modelo de datos: _____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | |_____________| |__________________| | PERSON | | | | | |_____________| | *EVENT_ID | | *EVENT_ID | | | | EVENT_DATE | | *PERSON_ID | | *PERSON_ID | | TITLE | |__________________| | AGE | |_____________| | FIRSTNAME | | LASTNAME | |_____________| < Asociación unidireccional > Asociación unidireccional Asociación bidireccional

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación bidireccional Ejemplo, clase de dominio Event: private Set participants = new HashSet(); public Set getParticipants() { return participants; } public void setParticipants(Set participants) { this.participants = participants; }

Hibernate Core – Clase 2 Mapeo de Relaciones  Asociación bidireccional Ejemplo, archivo de mapeo

Hibernate Core – Clase 2 Configuración  Hibernate esta diseñado para trabajar con varios entornos diferentes, debido a esto posee una amplia colección de parámetros de configuración.  Es posible configurar a Hibernate a través de los siguientes puntos Vía programación Vía archivo.properties Vía archivo.xml

Hibernate Core – Clase 2 Configuración  Hibernate JDBC Properties Property name Purpose hibernate.connection.driver_class JDBC driver class hibernate.connection.url JDBC URL hibernate.connection.username database user hibernate.connection.password database user password hibernate.connection.pool_size maximum number of pooled connections

Hibernate Core – Clase 2 Configuración  Hibernate Datasource Properties Property name Purpose hibernate.connection.datasource datasource JNDI name hibernate.jndi.url URL of the JNDI provider (optional)‏ hibernate.jndi.class class of the JNDI InitialContextFactory (optional)‏ hibernate.connection.username database user (optional)‏ hibernate.connection.password database user password (optional)‏

Hibernate Core – Clase 2 Configuración  Hibernate SQL Dialects (hibernate.dialect)‏  RDBMSDialect  DB2org.hibernate.dialect.DB2Dialect  DB2 AS/400org.hibernate.dialect.DB2400Dialect  DB2 OS390org.hibernate.dialect.DB2390Dialect  PostgreSQLorg.hibernate.dialect.PostgreSQLDialect  MySQLorg.hibernate.dialect.MySQLDialect  MySQL with InnoDBorg.hibernate.dialect.MySQLInnoDBDialect  MySQL with MyISAMorg.hibernate.dialect.MySQLMyISAMDialect  Oracle (any version)org.hibernate.dialect.OracleDialect  Oracle 9iorg.hibernate.dialect.Oracle9iDialect  Oracle 10gorg.hibernate.dialect.Oracle10gDialect  Sybaseorg.hibernate.dialect.SybaseDialect  Sybase Anywhereorg.hibernate.dialect.SybaseAnywhereDialect  Microsoft SQL Serverorg.hibernate.dialect.SQLServerDialect  SAP DBorg.hibernate.dialect.SAPDBDialect  Informixorg.hibernate.dialect.InformixDialect  HypersonicSQLorg.hibernate.dialect.HSQLDialect

Hibernate Core – Clase 2 Configuración  Hibernate SQL Dialects (hibernate.dialect)‏  Ingresorg.hibernate.dialect.IngresDialect  Progressorg.hibernate.dialect.ProgressDialect  Mckoi SQLorg.hibernate.dialect.MckoiDialect  Interbaseorg.hibernate.dialect.InterbaseDialect  Pointbaseorg.hibernate.dialect.PointbaseDialect  FrontBaseorg.hibernate.dialect.FrontbaseDialect  Firebirdorg.hibernate.dialect.FirebirdDialect

Hibernate Core – Clase 2 Configuración  Hibernate Log Categories Category Function org.hibernate.SQL Log all SQL DML statements as they are executed org.hibernate.type Log all JDBC parameters org.hibernate.tool.hbm2ddlLog all SQL DDL statements as they are executed org.hibernate.pretty Log the state of all entities (max 20 entities) associated with the session at flush time org.hibernate.cache Log all second-level cache activity org.hibernate.transaction Log transaction related activity org.hibernate.jdbc Log all JDBC resource acquisition org.hibernate.hql.ast.AST Log HQL and SQL ASTs during query parsing org.hibernate.secure Log all JAAS authorization requests org.hibernate Log everything. This is a lot of information but it is useful for troubleshooting

Hibernate Core – Clase 2 Criteria Query  La interfaz org.hibernate.Criteria representa una consulta (query) para una clase persistente en particular.  La instancia de Session es una factory para Criterias  Ejemplo: Criteria crit = sess.createCriteria(Cat.class); crit.setMaxResults(50); List cats = crit.list();

Hibernate Core – Clase 2 Criteria Query  Filtrando una tabla Ejemplo 1: List cats = sess.createCriteria(Cat.class)‏.add( Restrictions.like("name", "Fritz%") )‏.add( Restrictions.between("weight", minWeight, maxWeight) )‏.list(); Ejemplo 2: List cats = sess.createCriteria(Cat.class)‏.add( Restrictions.like("name", "Fritz%") )‏.add( Restrictions.or( Restrictions.eq( "age", new Integer(0) ), Restrictions.isNull("age") ) )‏.list();

Hibernate Core – Clase 2 Criteria Query  Filtrando una tabla Ejemplo 3: Property age = Property.forName("age"); List cats = sess.createCriteria(Cat.class)‏.add( Restrictions.disjunction()‏.add( age.isNull() )‏.add( age.eq( new Integer(0) ) )‏.add( age.eq( new Integer(1) ) )‏.add( age.eq( new Integer(2) ) )‏ ) )‏.add( Property.forName("name").in( new String[] { "Fritz", "Izi", "Pk" } ) )‏.list();

Hibernate Core – Clase 2 Criteria Query  Ordenando resultados Ejemplo 1: List cats = sess.createCriteria(Cat.class)‏.add( Restrictions.like("name", "F%")‏.addOrder( Order.asc("name") )‏.addOrder( Order.desc("age") )‏.setMaxResults(50)‏.list(); Ejemplo 2: List cats = sess.createCriteria(Cat.class)‏.add( Property.forName("name").like("F%") )‏.addOrder( Property.forName("name").asc() )‏.addOrder( Property.forName("age").desc() )‏.setMaxResults(50)‏.list();

Hibernate Core – Clase 2 Criteria Query  Asociaciones Ejemplo 1: List cats = sess.createCriteria(Cat.class)‏.add( Restrictions.like("name", "F%") )‏.createCriteria("kittens")‏.add( Restrictions.like("name", "F%") )‏.list(); Ejemplo 2: List cats = sess.createCriteria(Cat.class)‏.createAlias("kittens", "kt")‏.createAlias("mate", "mt")‏.add( Restrictions.eqProperty("kt.name", "mt.name") )‏.list();

Hibernate Core – Clase 2 Criteria Query  Projections Ejemplo 1: List results = session.createCriteria(Cat.class)‏.setProjection( Projections.rowCount() )‏.add( Restrictions.eq("color", Color.BLACK) )‏.list(); Ejemplo 2: List results = session.createCriteria(Cat.class)‏.setProjection( Projections.projectionList()‏.add( Projections.rowCount() )‏.add( Projections.avg("weight") )‏.add( Projections.max("weight") )‏.add( Projections.groupProperty("color") )‏ )‏.list();

Hibernate Core – Clase 2 Referencias:  Hibernate reference Documentation.

Hibernate Core – Clase 2 Practica  Realizar el ejemplo definido en el tutorial de hibernate  Sección 1.3. Part 3 - The EventManager web application