SlideShare une entreprise Scribd logo
1  sur  43
Hibernate Introduction Hello World and the Hibernate APIs
Hello World I ,[object Object],[object Object],[object Object],package hello; public class Message { private Long id; private String text; public String getText()  { return text; } public void setText(String text)  { this.text = text; } … }
Hello World II ,[object Object],[object Object],[object Object],[object Object],Message message = new Message("Hello World"); System.out.println( message.getText() );
Hello World VI ,[object Object],<?xml version=&quot;1.0&quot;?> <! DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD//EN&quot; &quot;http://hibernate.sf.net/hibernate-mapping-2.0.dtd&quot;> <hibernate-mapping> <class name=&quot;hello.Message&quot; table=&quot; MESSAGES &quot;> <id>...</id> <property name=&quot;text&quot; column=&quot; MESSAGE_TEXT &quot;/> </class> </hibernate-mapping>
Hello World III ,[object Object],[object Object],Session  session  = getSessionFactory().openSession(); Transaction  tx  = session.beginTransaction(); Message message = new Message(&quot;Hello World&quot;); session .save(message); tx .commit(); session .close(); insert into MESSAGES (MESSAGE_ID, MESSAGE_TEXT) values (1, 'Hello World')
Hello World IV ,[object Object],Session  newSession  = getSessionFactory().openSession(); Transaction  newTransaction  = newSession.beginTransaction(); List messages =  newSession .find(&quot;from Message&quot;); System.out.println( messages.size() + &quot; message(s) found:&quot; ); for ( Iterator iter = messages.iterator(); iter.hasNext(); ) { Message message = (Message) iter.next(); System.out.println( message.getText() ); } newTransaction .commit(); newSession .close(); select m.MESSAGE_ID, m.MESSAGE_TEXT from MESSAGES m
Hello World V ,[object Object],Notice that we did not explicitly call any update() method - automatic dirty checking gives us more flexibility when organizing data access code! Session  session  = getSessionFactory().openSession(); Transaction  tx  = session.beginTransaction(); // 1 is the generated id of the first message Message message =  session .load( Message.class, new Long(1) ); message.setText(&quot;Greetings Earthling&quot;); tx .commit(); session .close(); select m.MESSAGE_TEXT from MESSAGES m where m.MESSAGE_ID = 1 update MESSAGES set MESSAGE_TEXT = ‘Greetings Earthling'
Using C3P0 with hibernate.properties ,[object Object],[object Object],Don't forget to set the SQL dialect! hibernate.connection.driver_class = org.postgresql.Driver hibernate.connection.url = jdbc:postgresql://localhost/auctiondb hibernate.connection.username = auctionuser hibernate.connection.password = secret hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect hibernate.c3p0.min_size = 5 hibernate.c3p0.max_size = 20 hibernate.c3p0.timeout = 1800 hibernate.c3p0.max_statements = 50 Hibernate.c3p0.validate = true
Starting Hibernate ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],SessionFactory sessionFactory = new Configuration() .addResource(&quot;hello/Message.hbm.xml&quot;) .buildSessionFactory();
Other configuration options ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hibernate Architecture Hibernate Architecture Transaction Query Application Session Session   Factory Configuration Hibernate.cfg.xml Hibernate.properties Mapping   files
Hibernate Architecture Hibernate Architecture
Hibernate Architecture
Hibernate Architecture
Understanding the interfaces ,[object Object],Business Layer Persistence Layer Lifecycle Validatable UserType Persistent Classes Persistent Classes SessionFactory Configuration Session Transaction Query JNDI JDBC JTA Interceptor
SessionFactory SessionFactory (org.hibernate.SessionFactory) A thread safe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of Connection Provider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.
Session Session (org.hibernate.Session) A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.
Persistent Objects and Collections Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation).
Transient and detached objects and collections Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. .
Transaction Transaction (org.hibernate.Transaction) (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional! .
ConnectionProvider ConnectionProvider  (org.hibernate.connection.ConnectionProvider) (Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.
TransactionFactory TransactionFactory  (org.hibernate.TransactionFactory) (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.
Extension Interfaces Extension Interfaces Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer.(Ex. Primary key generation,SQL Dialet , Caching,JDBC connection, Proxy creationetc., Given a &quot;lite&quot; architecture, the application bypasses the  Transaction/TransactionFactory and/or ConnectionProvider APIs to talk to JTA or JDBC directly.
Instance States Instance states An instance of a persistent classes may be in one of three different states, which are defined with respect to a  persistence context .
Instance States Instance states An instance of a persistent classes may be in one of three different states, which are defined with respect to a  persistence context .
Instance States Transient The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).
Instance States Persistent The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate  guarantees  that persistent identity is equivalent to Java identity (in-memory location of the object).
Instance States Detached The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.
Managed environments ,[object Object],Hibernate Managed environment Resource Manager Application EJB EJB EJB Session Transaction Query Transaction Manager Each database has it's own  SessionFactory !
Configuration: “non-managed” environments ,[object Object],[object Object],Hibernate Non-managed environment Connection Pool Application JSP Servlet main() Session Transaction Query
Managed environment with XML configuration file <hibernate-configuration> <session-factory name=&quot; java:hibernate/SessionFactory &quot;> <property name=&quot;show_sql&quot;>true</property> <property name=&quot;connection.datasource&quot;> java:/comp/env/jdbc/HelloDB </property> <property name=&quot;transaction.factory_class&quot;> net.sf.hibernate.transaction.JTATransactionFactory </property> <property name=&quot; transaction.manager_lookup_class &quot;> net.sf.hibernate.transaction.JBossTransactionManagerLookup </property>   <property name=&quot;dialect&quot;> net.sf.hibernate.dialect.PostgreSQLDialect </property> <mapping resource=&quot;hello/Message.hbm.xml&quot;/> </session-factory> </hibernate-configuration>
Session Cache ,[object Object],[object Object],[object Object],[object Object],[object Object]
Session Cache ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Session Cache – Common problem ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Session Cache – Object Information ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
XDoclet ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
XDoclet @hibernate.class tag ,[object Object],[object Object],[object Object],[object Object],[object Object]
XDoclet - @hibernate.id tag The default size for the field type. Specified the size of the database column length Null. If we use a String or Long as the primary key, you don’t need to specify this.Specify the unsaved-value=0 for primitive types. Contains a value that will distinguish transient instances from persistent ones unsaved-value The property name Contains the name of the column column The return type of the field. Specifies the Hibernate type for this field type None. native will work for most databases Contains the key generation that Hibernate will use to insert new instances generator-class Default Description Attribute
The @hibernate.property tag Return type of the field Specifies the hibernate type type false Specifies that a unique constraint should be enforced unique false Specifies that a not-null constraint should be enforced not-null The default length for a field. Specifies the column size length The name of the field Contains the name of the column column Default Description Attribute
The @hibernate.column tag The type implied by the length Specifies database-specific column type, like TEXT or LONGBLOG sql-type No constraint created Creates a uniquely named constraint with this name unique-key No named index created Contains the name of a table index for this column index false Specifies that a unique constraint should be enforced unique False Specifies that a not-null constraint should be enforced not-null The default length for a field. Specifies the column size length It’s mandatory, so no default Contains the name of the column this property maps to name Default Description Attribute
The @hibernate.many-to-one attributes None. Acceptable values include all, none,save-update or delete Specifies how cascading operations should be handled from parent to child Cascade false Specifies that a unique constraint should be enforced Unique False Specifies that a not-null constraint should be enforced not-null The class of the field Contains the associated persistent class Class The name of the field Contains the name of the column in the database column Default Description Attribute
Hibernate mapping elements to XDoclet tags  @hibernate.collection-one-to-many A nested <one-to-many> @hibernate.collection-key A nested <key /> @hibernate.set <set / > XDoclet tag Mapping element
The @hibernate.set tag false Specifies whether the collection is inverse(determines which end of the collection is the parent) Inverse No ORDERBY  added Specifies whether the query to fetch the collection should ad a SQL ORDER BY(asc/desc)  Order-by None. Acceptable values include all, none,save-update or delete Specifies how cascading operations should be handled from parent to child Cascade Not sorted by default Specifies whether the collection should be sorted in memory.  Sort False Specifies whether the collection should be lazily initialized Lazy For a many-to-many, it uses the name of the field For the man-to-many association only,contains the association table name for joins Table None. Acceptable values include all,none,save-update, all-delete-orphan and delete Specifies how cascading operations should be handled from parent to child Cascade Default Description Attribute

Contenu connexe

Tendances

Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 

Tendances (19)

Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 
Deployment
DeploymentDeployment
Deployment
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answers
 

En vedette

jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 

En vedette (16)

Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS +27631229624
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS  +27631229624 THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS  +27631229624
THE WORLDS NO.1 BLACK MAGIC EXPERT WITH POWERFUL LOVE SPELLS +27631229624
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Hibernate an introduction
Hibernate   an introductionHibernate   an introduction
Hibernate an introduction
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Introduction To Hibernate
Introduction To HibernateIntroduction To Hibernate
Introduction To Hibernate
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Similaire à 02 Hibernate Introduction

02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
patinijava
 
Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
achraf_ing
 

Similaire à 02 Hibernate Introduction (20)

Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Spring 2
Spring 2Spring 2
Spring 2
 
Hibernate interview questions
Hibernate interview questionsHibernate interview questions
Hibernate interview questions
 
Jdbc
JdbcJdbc
Jdbc
 
Hibernate
HibernateHibernate
Hibernate
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
 

Plus de Ranjan Kumar (20)

Introduction to java ee
Introduction to java eeIntroduction to java ee
Introduction to java ee
 
Fantastic life views ons
Fantastic life views  onsFantastic life views  ons
Fantastic life views ons
 
Lessons on Life
Lessons on LifeLessons on Life
Lessons on Life
 
Story does not End here
Story does not End hereStory does not End here
Story does not End here
 
Whata Split Second Looks Like
Whata Split Second Looks LikeWhata Split Second Looks Like
Whata Split Second Looks Like
 
Friendship so Sweet
Friendship so SweetFriendship so Sweet
Friendship so Sweet
 
Dedicate Time
Dedicate TimeDedicate Time
Dedicate Time
 
Paradise on Earth
Paradise on EarthParadise on Earth
Paradise on Earth
 
Bolivian Highway
Bolivian HighwayBolivian Highway
Bolivian Highway
 
Chinese Proverb
Chinese ProverbChinese Proverb
Chinese Proverb
 
Warren Buffet
Warren BuffetWarren Buffet
Warren Buffet
 
Dear Son Dear Daughter
Dear Son Dear DaughterDear Son Dear Daughter
Dear Son Dear Daughter
 
Jara Sochiye
Jara SochiyeJara Sochiye
Jara Sochiye
 
Blue Beauty
Blue BeautyBlue Beauty
Blue Beauty
 
Alaska Railway Routes
Alaska Railway RoutesAlaska Railway Routes
Alaska Railway Routes
 
Poison that Kills the Dreams
Poison that Kills the DreamsPoison that Kills the Dreams
Poison that Kills the Dreams
 
Horrible Jobs
Horrible JobsHorrible Jobs
Horrible Jobs
 
Best Aviation Photography
Best Aviation PhotographyBest Aviation Photography
Best Aviation Photography
 
Role of Attitude
Role of AttitudeRole of Attitude
Role of Attitude
 
45 Lesons in Life
45 Lesons in Life45 Lesons in Life
45 Lesons in Life
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

02 Hibernate Introduction

  • 1. Hibernate Introduction Hello World and the Hibernate APIs
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11. Hibernate Architecture Hibernate Architecture Transaction Query Application Session Session Factory Configuration Hibernate.cfg.xml Hibernate.properties Mapping files
  • 15.
  • 16. SessionFactory SessionFactory (org.hibernate.SessionFactory) A thread safe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of Connection Provider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.
  • 17. Session Session (org.hibernate.Session) A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.
  • 18. Persistent Objects and Collections Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation).
  • 19. Transient and detached objects and collections Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. .
  • 20. Transaction Transaction (org.hibernate.Transaction) (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional! .
  • 21. ConnectionProvider ConnectionProvider (org.hibernate.connection.ConnectionProvider) (Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.
  • 22. TransactionFactory TransactionFactory (org.hibernate.TransactionFactory) (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.
  • 23. Extension Interfaces Extension Interfaces Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer.(Ex. Primary key generation,SQL Dialet , Caching,JDBC connection, Proxy creationetc., Given a &quot;lite&quot; architecture, the application bypasses the Transaction/TransactionFactory and/or ConnectionProvider APIs to talk to JTA or JDBC directly.
  • 24. Instance States Instance states An instance of a persistent classes may be in one of three different states, which are defined with respect to a persistence context .
  • 25. Instance States Instance states An instance of a persistent classes may be in one of three different states, which are defined with respect to a persistence context .
  • 26. Instance States Transient The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).
  • 27. Instance States Persistent The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).
  • 28. Instance States Detached The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.
  • 29.
  • 30.
  • 31. Managed environment with XML configuration file <hibernate-configuration> <session-factory name=&quot; java:hibernate/SessionFactory &quot;> <property name=&quot;show_sql&quot;>true</property> <property name=&quot;connection.datasource&quot;> java:/comp/env/jdbc/HelloDB </property> <property name=&quot;transaction.factory_class&quot;> net.sf.hibernate.transaction.JTATransactionFactory </property> <property name=&quot; transaction.manager_lookup_class &quot;> net.sf.hibernate.transaction.JBossTransactionManagerLookup </property> <property name=&quot;dialect&quot;> net.sf.hibernate.dialect.PostgreSQLDialect </property> <mapping resource=&quot;hello/Message.hbm.xml&quot;/> </session-factory> </hibernate-configuration>
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38. XDoclet - @hibernate.id tag The default size for the field type. Specified the size of the database column length Null. If we use a String or Long as the primary key, you don’t need to specify this.Specify the unsaved-value=0 for primitive types. Contains a value that will distinguish transient instances from persistent ones unsaved-value The property name Contains the name of the column column The return type of the field. Specifies the Hibernate type for this field type None. native will work for most databases Contains the key generation that Hibernate will use to insert new instances generator-class Default Description Attribute
  • 39. The @hibernate.property tag Return type of the field Specifies the hibernate type type false Specifies that a unique constraint should be enforced unique false Specifies that a not-null constraint should be enforced not-null The default length for a field. Specifies the column size length The name of the field Contains the name of the column column Default Description Attribute
  • 40. The @hibernate.column tag The type implied by the length Specifies database-specific column type, like TEXT or LONGBLOG sql-type No constraint created Creates a uniquely named constraint with this name unique-key No named index created Contains the name of a table index for this column index false Specifies that a unique constraint should be enforced unique False Specifies that a not-null constraint should be enforced not-null The default length for a field. Specifies the column size length It’s mandatory, so no default Contains the name of the column this property maps to name Default Description Attribute
  • 41. The @hibernate.many-to-one attributes None. Acceptable values include all, none,save-update or delete Specifies how cascading operations should be handled from parent to child Cascade false Specifies that a unique constraint should be enforced Unique False Specifies that a not-null constraint should be enforced not-null The class of the field Contains the associated persistent class Class The name of the field Contains the name of the column in the database column Default Description Attribute
  • 42. Hibernate mapping elements to XDoclet tags @hibernate.collection-one-to-many A nested <one-to-many> @hibernate.collection-key A nested <key /> @hibernate.set <set / > XDoclet tag Mapping element
  • 43. The @hibernate.set tag false Specifies whether the collection is inverse(determines which end of the collection is the parent) Inverse No ORDERBY added Specifies whether the query to fetch the collection should ad a SQL ORDER BY(asc/desc) Order-by None. Acceptable values include all, none,save-update or delete Specifies how cascading operations should be handled from parent to child Cascade Not sorted by default Specifies whether the collection should be sorted in memory. Sort False Specifies whether the collection should be lazily initialized Lazy For a many-to-many, it uses the name of the field For the man-to-many association only,contains the association table name for joins Table None. Acceptable values include all,none,save-update, all-delete-orphan and delete Specifies how cascading operations should be handled from parent to child Cascade Default Description Attribute