20
ORM with ORM with JPA/Hibernate JPA/Hibernate overview overview Petar Milev

ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Embed Size (px)

Citation preview

Page 1: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

ORM with ORM with JPA/Hibernate overviewJPA/Hibernate overview

Petar Milev

Page 2: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

ContentsContentsContentsContents

1.1. ORM ConceptsORM Concepts• Java class to database tableJava class to database table

• Java object to database table’s rowJava object to database table’s row

• Classes vs. tablesClasses vs. tables

2.2. (OR) Mapping with Hibernate(OR) Mapping with Hibernate• Two ways to goTwo ways to go

• Annotations vs. XMLAnnotations vs. XML

3.3. Create, Retrieve, Update, Delete and Create, Retrieve, Update, Delete and JPA QLJPA QL

1.1. ORM ConceptsORM Concepts• Java class to database tableJava class to database table

• Java object to database table’s rowJava object to database table’s row

• Classes vs. tablesClasses vs. tables

2.2. (OR) Mapping with Hibernate(OR) Mapping with Hibernate• Two ways to goTwo ways to go

• Annotations vs. XMLAnnotations vs. XML

3.3. Create, Retrieve, Update, Delete and Create, Retrieve, Update, Delete and JPA QLJPA QL

Page 3: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

ORM ConceptsORM Concepts

Page 4: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Class To TableClass To TableClass To TableClass To Table

• Associate Java POJO with database tableAssociate Java POJO with database tableTable: PERSON (SQL may be generated by Hibernate)Table: PERSON (SQL may be generated by Hibernate)

• You can do it without even using SQLYou can do it without even using SQL

• Associate Java POJO with database tableAssociate Java POJO with database tableTable: PERSON (SQL may be generated by Hibernate)Table: PERSON (SQL may be generated by Hibernate)

• You can do it without even using SQLYou can do it without even using SQL

IDID NAMENAME DESCRIPTIONDESCRIPTION11 PeshoPesho Java manJava man

22 GoshoGosho Just manJust man

class Personclass Person{{Long id;Long id;String name;String name;String description;String description;//getter, setters//getter, setters

}}

Page 5: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Instances Are RowsInstances Are RowsInstances Are RowsInstances Are Rows

• Java instances are represented as rows in the Java instances are represented as rows in the tabletable

• Java instances are represented as rows in the Java instances are represented as rows in the tabletable

IDID NAMENAME DESCRIPTIONDESCRIPTION

11 PeshoPesho Java manJava man

22 GoshoGosho Just manJust man

void mymethod(Person p){void mymethod(Person p){ System.out.println(p.getId()); //1System.out.println(p.getId()); //1 System.out.println(p.getName()); //’Pesho’System.out.println(p.getName()); //’Pesho’ System.out.println(p.getDescription());//’JavaSystem.out.println(p.getDescription());//’Java

man’man’}}

Page 6: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Classes vs. TablesClasses vs. TablesClasses vs. TablesClasses vs. Tables

• Classes inherit from each otherClasses inherit from each other

• Classes have associations between themClasses have associations between them

• What about tables?What about tables?

• The differences lead to the need for meta The differences lead to the need for meta informationinformation

• Classes inherit from each otherClasses inherit from each other

• Classes have associations between themClasses have associations between them

• What about tables?What about tables?

• The differences lead to the need for meta The differences lead to the need for meta informationinformation

Page 7: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

(OR) Mappings(OR) Mappings

Page 8: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Ways To Go - XMLWays To Go - XMLWays To Go - XMLWays To Go - XML

• XML files for every mapped classXML files for every mapped class• XML files for every mapped classXML files for every mapped class

<class name=“<class name=“www.com.Personwww.com.Person" table=“" table=“PERSONPERSON">  ">   <id column=“<id column=“IDID" name="id" type="java.lang." name="id" type="java.lang.LongLong““//>> <property column=“<property column=“NAMENAME" name=“" name=“namename" " type="java.lang.String"/>type="java.lang.String"/> <property column=“<property column=“DESCRIPTIONDESCRIPTION" name=“" name=“descriptiondescription" "

type="java.lang.String"/>type="java.lang.String"/> <set name=“<set name=“hairshairs">"> <key column=“<key column=“PERSON_IDPERSON_ID" not-null="true"/>" not-null="true"/> <one-to-many class=“<one-to-many class=“www.com.Hairwww.com.Hair"/>"/> </set></set></class></class>

Page 9: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Ways To Go – Java AnnotationsWays To Go – Java AnnotationsWays To Go – Java AnnotationsWays To Go – Java Annotations

• Java Annotations used at the mapped classesJava Annotations used at the mapped classes• Java Annotations used at the mapped classesJava Annotations used at the mapped classes

@Entity(“PERSON”)@Entity(“PERSON”)public class Person {public class Person {

private Long id;private Long id; private String name;private String name; private String description;private String description; private Set<Hair> hairs;private Set<Hair> hairs;

//..code continued//..code continued

Page 10: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Java Annotations 2Java Annotations 2Java Annotations 2Java Annotations 2

• Java Annotations used at the mapped classesJava Annotations used at the mapped classes• Java Annotations used at the mapped classesJava Annotations used at the mapped classes

//... @Id@Id public Long getId() { return id; }public Long getId() { return id; }

@Column(name=“NAME”)@Column(name=“NAME”) public String getName() { return name; }public String getName() { return name; }

@Column(name=“DESCRIPTION”)@Column(name=“DESCRIPTION”) public String getDescription(){ return description; }public String getDescription(){ return description; }

@OneToMany(mappedBy=“person”)@OneToMany(mappedBy=“person”) public Set<Hair> getHairs(){ return hairs; }public Set<Hair> getHairs(){ return hairs; } //normal setters//normal setters}}

Page 11: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Annotations vs. XMLAnnotations vs. XMLAnnotations vs. XMLAnnotations vs. XML

• Annotations advantagesAnnotations advantages

• Everything is in one placeEverything is in one place

• Annotations are refactoring-friendly for Annotations are refactoring-friendly for renaming and moving of classesrenaming and moving of classes

• Annotations are controlled by the compilerAnnotations are controlled by the compiler

• Annotations shortcomingsAnnotations shortcomings

• Cluttered source codeCluttered source code

• Annotations advantagesAnnotations advantages

• Everything is in one placeEverything is in one place

• Annotations are refactoring-friendly for Annotations are refactoring-friendly for renaming and moving of classesrenaming and moving of classes

• Annotations are controlled by the compilerAnnotations are controlled by the compiler

• Annotations shortcomingsAnnotations shortcomings

• Cluttered source codeCluttered source code

Page 12: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

XML vs. AnnotationsXML vs. AnnotationsXML vs. AnnotationsXML vs. Annotations

• XML advantagesXML advantages

• Java code is more readableJava code is more readable

• XML shortcomingsXML shortcomings

• More things to writeMore things to write

• Support simultaneously two files: .xml Support simultaneously two files: .xml and .javaand .java

• XML advantagesXML advantages

• Java code is more readableJava code is more readable

• XML shortcomingsXML shortcomings

• More things to writeMore things to write

• Support simultaneously two files: .xml Support simultaneously two files: .xml and .javaand .java

Page 13: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

More about mappings in JPAMore about mappings in JPAMore about mappings in JPAMore about mappings in JPA

• Configuration by exceptionConfiguration by exception

• You can tell JPA how to fetch the You can tell JPA how to fetch the relationsrelations

• Transient propertiesTransient properties

• Map relationsMap relations

• Map mapsMap maps

• Embedded objectsEmbedded objects

• Compound primary keysCompound primary keys

• Configuration by exceptionConfiguration by exception

• You can tell JPA how to fetch the You can tell JPA how to fetch the relationsrelations

• Transient propertiesTransient properties

• Map relationsMap relations

• Map mapsMap maps

• Embedded objectsEmbedded objects

• Compound primary keysCompound primary keys

Page 14: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Create, Read, Update, DeleteCreate, Read, Update, DeleteCreate, Read, Update, DeleteCreate, Read, Update, Delete

Page 15: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

(CR)UD(CR)UD(CR)UD(CR)UD

• CreateCreate

• ReadRead

• CreateCreate

• ReadRead

void create(EntityManager entityManager){void create(EntityManager entityManager){ Person person = new Person(“pesho”, “java programmer”);Person person = new Person(“pesho”, “java programmer”); entityManager.persist(person);entityManager.persist(person);}}

void read(EntityManager entityManager){void read(EntityManager entityManager){ Person person = entityManager.find(Person.class, 1);Person person = entityManager.find(Person.class, 1);}}

void query(EntityManager entityManager){void query(EntityManager entityManager){ Query query = entityManager.createQuery(“from Person where name Query query = entityManager.createQuery(“from Person where name like ‘pesho’ ”);like ‘pesho’ ”); List persons = query.getResultList();}List persons = query.getResultList();}

• QueryQuery• QueryQuery

Page 16: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

CR(UD)CR(UD)CR(UD)CR(UD)

• UpdateUpdate• UpdateUpdate

void update(EntityManager entityManager){void update(EntityManager entityManager){ Person person = entityManager.find(Person.class, 1); Person person = entityManager.find(Person.class, 1); person.setDescription(“new description”);person.setDescription(“new description”); … ….. entityManager.getTransaction().commit();entityManager.getTransaction().commit();}}

void delete(EntityManager entityManager){void delete(EntityManager entityManager){ Person person = entityManager.find(Person.class, 1);Person person = entityManager.find(Person.class, 1); entityManager.remove(person);entityManager.remove(person);}}

• DeleteDelete• DeleteDelete

Page 17: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

Query Language ExamplesQuery Language ExamplesQuery Language ExamplesQuery Language Examples

• Polymorphic queriesPolymorphic queries• Polymorphic queriesPolymorphic queries

from Shape; //where Shape is an abstract classfrom Shape; //where Shape is an abstract class

from java.lang.Object; //get the whole database, why not?from java.lang.Object; //get the whole database, why not?

• Where, like, in, functionsWhere, like, in, functions• Where, like, in, functionsWhere, like, in, functions

from Person p from Person p where p.name like ‘P%’ and p.description like ‘J%’where p.name like ‘P%’ and p.description like ‘J%’ or p.name in (‘John’, ‘Ben’, ‘Petar’)or p.name in (‘John’, ‘Ben’, ‘Petar’) or lower(p.name) = ‘pesho’or lower(p.name) = ‘pesho’

Page 18: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

More Query ExamplesMore Query ExamplesMore Query ExamplesMore Query Examples

• ProjectionProjection• ProjectionProjection

select a, b from Animal a, Banica b; //returns List of Object[], the array is select a, b from Animal a, Banica b; //returns List of Object[], the array is with 2 elements with 2 elements

• Sub selects with ‘any’, ‘some’, ‘all’ and ‘in’Sub selects with ‘any’, ‘some’, ‘all’ and ‘in’• Sub selects with ‘any’, ‘some’, ‘all’ and ‘in’Sub selects with ‘any’, ‘some’, ‘all’ and ‘in’

from Box b where 10 <= any ( select b.amount from i.bets b )

from Box b where 10 > all ( select b.amount from i.bets b )

from Box b where 10 = some ( select b.amount from i.bets b )

from Box b where 10 in ( select b.amount from i.bets b )

Page 19: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

More Query ExamplesMore Query ExamplesMore Query ExamplesMore Query Examples

• Implicit joinsImplicit joins• Implicit joinsImplicit joins

from Bet betwhere bet.item.category.name like ‘hundred%'and bet.item.firstBet.quantity > 10

• SQL alternativeSQL alternative• SQL alternativeSQL alternative

select . . . .from BET Binner join ITEM I on B.ITEM_ID = I.ITEM_IDinner join CATEGORY C on I.CATEGORY_ID = C.CATEGORY_IDinner join BET SB on I.FIRST_BET_ID = SB.BET_IDwhere C.NAME like ‘hundred%'and SB.QUANTITY > 100

Page 20: ORM with JPA/Hibernate overview Petar Milev. ContentsContents 1.ORM Concepts Java class to database tableJava class to database table Java object to database

More Query ExamplesMore Query ExamplesMore Query ExamplesMore Query Examples

• Normal joinsNormal joins• Normal joinsNormal joinsfrom Person pleft join p.hairs hwith h.length > 10where p.description like '%Foo%'

• Dynamic instantiationDynamic instantiation• Dynamic instantiationDynamic instantiation

select new BetInfo( bet.item.id, count(bet), avg(bet.amount))from Bet betwhere bet.current.ammount is nullgroup by bet.current.id