Hibernate, JAVA, JDBC, Synergetics India
Upcoming SlideShare
Loading in...5
×
 

Hibernate, JAVA, JDBC, Synergetics India

on

  • 3,667 views

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.

Statistics

Views

Total Views
3,667
Views on SlideShare
3,634
Embed Views
33

Actions

Likes
5
Downloads
468
Comments
0

2 Embeds 33

http://localhost 31
http://127.0.0.1 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • General slide (not title slide)
  • General slide (not title slide)
  • General slide (not title slide)
  • General slide (not title slide)
  • General slide (not title slide)
  • General slide (not title slide)
  • Session Factory: thread-safe (immutable) A Hibernate Session provides transaction-scoped identity. Hibernate affords process-scoped identity through an optional second-level cache.
  • These can be a part of your build process, or a one-off process to jumpstart the development effort.
  • These can be a part of your build process, or a one-off process to jumpstart the development effort.
  • To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations.
  • to minimize the amount of information needed in a mapping
  • to minimize the amount of information needed in a mapping
  • Save and saveOrUpdate associates object with a Persistence Manager
  • Persistance by Reachability: Automatically persisted when referenced by a persistent object and deleted when unreferenced A Hibernate-mapped collection is used just as a normal Java Collection
  • First level cache takes care of giving the application the same java object each time the corresponding persistent object is accessed Cache strategy may be typically read-only, read-write etc. It can be set per class. Second-level cache can be per JVM, on disc or clustered (ip-multicast)
  • For cases when the generated SQL is not sufficient, you can tell Hibernate the exact SQL to use for insert, updates and deletes
  • For cases when the generated SQL is not sufficient, you can tell Hibernate the exact SQL to use for insert, updates and deletes
  • For cases when the generated SQL is not sufficient, you can tell Hibernate the exact SQL to use for insert, updates and deletes
  • For cases when the generated SQL is not sufficient, you can tell Hibernate the exact SQL to use for insert, updates and deletes
  • Table defaults to the class name if not annotated We choose to explicitly specify the table for each mapped class
  • Remember that all Entities require a unique identifier We put this in the ancestor class of all Persistent classes You don’t need to do this however, your domain classes don’t need a common ancestor (well besides java.lang.Object)
  • @Basic is the default @Column needed only if column name != field name Again we choose to explicity specify the persistence and column of each field
  • No example of this in MAUI but it’s important to realize that @Basic is the default So any field that is unannotated in your class will be persisted (or at least attempted) For fields that don’t need persistenting – they must be marked with @Transient
  • EnumType.String will cause the Enum name to be persisted The default is to persist the enum id value (0, 1, 2 ...) Persisting the name makes the database more readable
  • Without this annotations ancestor fields won’t get persisted
  • Single Table -All superclass and subclass properties are in a single table -All instances are persisted in this single table with a discriminator column to indicate which class the row is an instance of -Advantages simple schema – easy to understand single SQL statement for CRUD allows for polymorphic queries -Disadvantages nullable columns needed Joined Subclass (Table per subclass) -Table for each concrete subclass as well as abstract super classes -PK are shared -Advantages normalized easy to extend hierarchy (just add a new table) -Disadvantages Querying requires join(s) insert/update/delete requires multiple statements Table Per Concrete Class -Disadvantages polymorphic foreign keys are not possible polymorphic queries are difficult each concrete class contains columns for all inherited attributes
  • @DiscriminatorFormula is a hibernate extension – allows for a sql query to determine the type Typically you’ll use @DiscriminatorColumn
  • Instead of find could use em.getReference() which instantiates a proxy – no database select is needed

Hibernate, JAVA, JDBC, Synergetics India Hibernate, JAVA, JDBC, Synergetics India Presentation Transcript

  • Hibernate Omprakash Pandey [email_address] http://synergetics-india.com
  • What is Hibernate
    • Hibernate is a free, open source Java package that makes it easy to work with relational databases.
    • Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables.
    • Hibernate liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.
  • Why Hibernate?
    • Cost effective.
    • Learning is very easy compare to EJB.
    • High Performance than EJB
    • No more need for JDBC API for Result set handling.
    • Switching to other SQL database requires few changes in Hibernate configuration file
  • The Problem Two Different Worlds
    • Object-Oriented Systems
    • Represent a problem in terms of objects
    • Semantically richer, encapsulate data and behavior
    • Relational Databases
    • Efficient data storage, retrieval and integrity of the data
    • Provide a “normalized” set of data
  • The Problem Natural Divergence
    • Early on in a system’s life, both models tend to look alike
    • As the system matures two models diverge
    • They grow to do what they do best
      • Object model gets richer
      • Data model changes to accommodate operational factors
  • The Problem Object-Relational Mismatch
    • Granularity
      • Object Oriented vs. Database Types
      • User-Defined Column Types (UDT) are not portable
    • Inheritance & Polymorphism
      • Not supported in the relational model
      • No polymorphic queries
      • Columns are strictly typed
  • The Problem Object-Relational Mismatch
    • Identity Mismatch
      • Object Identity vs. Object Equality
      • Different objects can map to the same column or columns
      • Database Identity Strategies
      • Natural Keys versus Surrogate Keys
  • The Problem Object-Relational Mismatch
    • Associations
      • Object References versus Foreign Keys
      • Directionality of Associations
      • Tables associations are always one-to-many or many-to-one
      • Object associations can be many-to-many
  • The Problem Object-Relational Mismatch
    • Object Graph Navigation
      • Object-oriented applications “walk” the object graph
      • Object-oriented systems access what they need
      • With database we need a “plan” of what to retrieve
      • N+1 Problem is a common symptom
  • Object-Relational Mapping
    • Tools/techniques to store and retrieve objects from a database
    • From the code perspective it behaves like a virtual object database
    • A complete ORM solution should provide:
      • Basic CRUD functionality
      • An Object-Oriented Query Facility
      • Mapping Metadata support
      • Transactional Capability
  • Hibernate Relational Persistence For Idiomatic Java
    • Provides
      • Transparent persistence
      • Object-querying capabilities
      • Caching
    • Works with fine-grained POJO-based models
    • Supports most Databases
    • Created by Gavin King, now part of the JBoss Group
  • Hibernate Relational Persistence For Idiomatic Java
    • Declarative programming
    • Uses Runtime Reflection
    • Query Language is SQL-like
      • Leverages programmer’s knowledge
    • Mappings
      • Typically defined as XML documents
    • But you never have to write XML if you don’t want to (XDoclet, JSE 1.5 Annots)
  • Hibernate Relational Persistence For Idiomatic Java
  • Hibernate 3.0
    • Hibernate 3.0 provides three full-featured query facilities:
    • Hibernate Query Language
    • Hibernate Criteria Query API
    • Hibernate Native Query
  • Advantage of using the Hibernate
    • Database independent application
    • Avoid writing queries
    • Avoid JDBC API completely
    • Hibernate uses connection pooling technique
    • Automatic Key Generation
    • Develop the Application in short Period of time
  • Hibernate Support Different Database
    • DB2
    • MySQL
    • PostgreSQL
    • Oracle
    • Microsoft SQL Server
    • HypersonicSQL
    • Informix
    • Ingres
    • Interbase
    • Pointbase
    • Mckoi SQL
    • Progress
    • FrontBase
    • SAP DB
    • Sybase
  • Hibernate Architecture
  • Hibernate Architecture
  • Hibernate Architecture
    • Hibernate architecture has three main components:
    • Connection Management Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection.   
    • Transaction management: Transaction management service provide the ability to the user to execute more than one database statements at a time.   
    • Object relational mapping: Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
    • Hibernate is very good tool as far as object relational mapping is concern but in terms of
      • connection management and
      • transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.
  • Hibernate Core Concepts
    • Session Factory
      • is a cache of compiled mappings for a single database.
      • used to retrieve Hibernate Sessions
    • Session
      • Short lived
        • Temporary bridge between the app and the data storage
      • Provides CRUD operations on Objects
      • Wraps a JDBC Connection / J2EE Data Source
      • Serves as a first level object cache
  • Architecture
  • The Big Picture
  • Hibernate Basics
  • Hibernate Basics SessionFactory A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session. Expensive to create.
  • Hibernate Basics 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.
  • Hibernate Basics 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).
  • Hibernate Basics Transient 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.
  • Hibernate Basics
    • 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.
    • Multiple transactions per Session.
  • Hibernate Basics
      • 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
      • (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.
  • Hibernate Tools The Hibernate Mapping File Database Schema Generation net.sf.hibernate.tool.hbm2ddl.SchemaExportTask net.sf.hibernate.tool.hbm2ddl.SchemaUpdateTask Best Practices suggest having one file per entity. Java Code Generation net.sf.hibernate.tool.hbm2java.Hbm2JavaTask
  • Hibernate Tools The Hibernate Mapping File Best Practices suggest having one file per entity. Database Schema Reverse Engineering (Bottom Up development) Middlegen Object Driven Design (Top Down development) AndroMDA XMI -> *.hbm.xml XDoclet can also be used to directly embed the mapping file information in the source code.
  • HQL
  • Hibernate Query Language HQL
    • An objectified version of SQL
      • Polymorphic Queries
      • Object parameters in Queries
      • Less verbose than SQL
    • Doesn’t hide the power of SQL
      • SQL joins, Cartesian products
      • Projections
      • Aggregation (max, avg) and grouping
      • Ordering
      • Sub-queries
      • … and more
  • Hibernate Query Language HQL
    • Simplest HQL Query
      • Return all Addresses
    • session = sessionFactory .openSession();
    • // query string – ‘Address’ refers to a Class not a Table
    • String queryString = " from Address " ;
    • // create, configure and execute the query
    • List addresses = session . createQuery ( queryString ). list ();
  • Hibernate Query Language HQL
    • A more elaborate HQL Query
      • Return all Tracks in a Conference
    • Conference conference = …
    • session = sessionFactory .openSession();
    • // build a query string
    • String queryString = “from Tracks as t where t.Conference = :conf” ;
    • // create, configure and execute the query
    • List addresses = session .createQuery( queryString )
    • .setObject(“conf”, conference )
    • .list();
  • Hibernate Criteria Query API
    • The Criteria interface allows to create and execute object-oriented queries. It is powerful alternative to the HQL but has own limitations. Criteria Query is used mostly in case of multi criteria search screens, where HQL is not very effective. 
  • Hibernate Native Query
    • Native SQL is handwritten SQL for all database operations like create, update, delete and select. Hibernate Native Query also supports stored procedures. Hibernate allows you to run Native SQL Query for all the database operations, so you can use your existing handwritten sql with Hibernate, this also helps you in migrating your SQL/JDBC based application to Hibernate.
  • How to Implement Hibernate
    • Configuring Hibernate
    • Persistence Class
    • Map the Object to the Database table
    • Setting up the Database
          • Insert, Update and Delete records in the table (Hibernate automatically creates query to perform this operations)
  • 1. Configuring Hibernate
    • Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.
    • <hibernate-configuration> <session-factory>    <property name=&quot;hibernate.connection.driver_class&quot;>com.mysql.jdbc.Driver
    • </property>    <property name=&quot;hibernate.connection.url&quot;> jdbc:mysql://localhost/hibernate
    • </property>       <property name=&quot;hibernate.connection.username&quot;> root </property>       <property name=&quot;hibernate.connection.password&quot;></property>       <property name=&quot;hibernate.connection.pool_size&quot;>10</property>       <property name=&quot;dialect&quot;> org.hibernate.dialect.MySQLDialect </property>       <property name=&quot;hibernate.hbm2ddl.auto&quot;> update </property>       <!-- Mapping files -->       <mapping resource=&quot; contact.hbm.xml &quot;/> </session-factory>
    • </hibernate-configuration>
  • Hibernate Configuration hibernate.properties hibernate.dialect=net.sf.hibernate.dialect.HSQLDialect hibernate.connection.driver_class=org.hsqldb.jdbcDriver ## in Ant you can get away with a relative path ## however using this through Eclipse requires an explicit path hibernate.connection.url= jdbc:hsqldb:c:/workspace/HibernateNotebook/data/music hibernate.connection.username=sa hibernate.connection.password=
  • Hibernate Configuration Currently supported Dialects DB2390Dialect DB2400Dialect DB2Dialect FirebirdDialect FrontBaseDialect GenericDialect HSQLDialect Informix9Dialect InformixDialect IngresDialect InterbaseDialect MckoiDialect MySQLDialect NoArgSQLFunction Oracle9Dialect OracleDialect PointbaseDialect PostgreSQLDialect ProgressDialect SAPDBDialect SQLServerDialect StandardSQLFunction Sybase11_9_2Dialect SybaseAnywhereDialect SybaseDialect Or you can choose to extend the Abstract Dialect object to add support to whatever database you are using. A Dialect “Represents a dialect of SQL implemented by a particular RDBMS. Subclasses implement Hibernate compatibility with different systems.” -- Hibernate Documentation
  • 2. Persistence Class
    • Hibernate uses the Plain Old Java Objects (POJO) classes to map to the database table. We can configure the variables to map to the database column.
    • package  Example;
    • public class  Contact {    private  String firstName; private  String lastName; private  String email; private long  id;   public  String getEmail() {      return  email;   }   public  String getFirstName() {      return  firstName;   }     public  String getLastName() {      return  lastName;   }    public void  setEmail(String string) {     email = string;   }    public void  setFirstName(String string) {     firstName = string;   }    public void  setLastName(String string) {     lastName = string;   }    public long  getId() {      return  id;   }    public void  setId( long  l) {     id = l; } }
  • 3.Map the Object to the Database table
    • The file contact.hbm.xml is used to map Contact Object to the Contact table in the database.
    • <hibernate-mapping>   <class name=“Example.Contact&quot; table=&quot;CONTACT&quot;>    <id name=&quot;id&quot; type=&quot;long&quot; column=&quot;ID&quot; >    <generator class=&quot;assigned&quot;/>   </id>   <property name=&quot;firstName&quot;>      <column name=&quot;FIRSTNAME&quot; />   </property>   <property name=&quot;lastName&quot;>     <column name=&quot;LASTNAME&quot;/>   </property>   <property name=&quot;email&quot;>     <column name=&quot;EMAIL&quot;/>   </property>  </class>
    • </hibernate-mapping>
  • 4.Setting up the Database
    • package  Example;
    • import  org.hibernate.Session; import  org.hibernate.SessionFactory;
    • import  org.hibernate.cfg.Configuration;
    • public class  FirstExample {  
    •   public static void  main(String[] args) {
    •   Session session =  null ;
    •   try {
    • SessionFactory sessionFactory =  new  Configuration().configure().buildSessionFactory();        session =sessionFactory.openSession();        values in it by reading them from form object        Contact contact =  new  Contact();         contact.setId(3);         contact.setFirstName(“kumar&quot;);         contact.setLastName(“m&quot;);         contact.setEmail(“kumar.m@yahoo.com&quot;);         session.save(contact);         System.out.println(&quot;Done&quot;);     } catch (Exception e){       System.out.println(e.getMessage());     } finally {       session.flush();       session.close();
    •   }   } }
  • Architecture Choices
    • How much you use depends on your needs
      • Lightweight
        • Basic persistence
      • Fully Integrated
        • Transactions
        • Caching
        • Connection Pooling
  • O/R Mappings
    • Hibernate Mapping (.hbm.xml) Files define:
      • Column to Field Mappings
      • Primary Key mapping & generation Scheme
      • Associations
      • Collections
      • Caching Settings
      • Custom SQL
      • And many more settings…
  • HBM XML File
    • <hibernate-mapping
    • package =&quot;com.integrallis.techconf.domain&quot; >
    • <class name =&quot;Address&quot;>
    • <id name =&quot;Id&quot; column =&quot;PK_ID&quot; type =&quot;integer &quot;>
    • <generator class =&quot;identity&quot; />
    • </id>
    • <property name =&quot;StreetAddress“ />
    • <property name =&quot;AptNumber&quot; />
    • </class>
    • </hibernate-mapping>
  • O/R Mappings
    • Hibernate uses smart defaults
    • Mapping files can be generated:
      • Manually
        • Tedious, boring and error prone
        • Total control of the mapping
      • From POJOs
        • XDoclet, Annotations
      • From Database Schema
        • Middlegen, Synchronizer, Hibernate Tools
  • Configuring Hibernate
    • Hibernate Session Factory configured via hibernate.cfg.xml
    • CFG file determines which mappings to load (.hbm.xml files)
    • In your application SessionFactory is a singleton
    • You request a Session as needed to work with persistent objects
  • Working with Persistent Objects Saving an Object
    • Address address = new Address();
    • ...
    • Session session = null;
    • Transaction tx = null;
    • try {
    • session = factory .openSession();
    • tx = session.beginTransaction();
    • session .save( address );
    • tx .commit();
    • } finally {
    • session .close();
    • }
    • POJO is created
    • Start a Session
    • Transaction is started
    • The object is saved
    • The transaction is committed
    • The session is closed
  • Working with Persistent Objects Loading an Object
    • Address address = null;
    • Session session = null;
    • session = factory .openSession();
    • try {
    • address = (Address)
    • session .get(Address.class, id);
    • } finally {
    • session .close();
    • }
    • Start a Session
    • POJO is loaded
    • PK and Object Class are provided
    • The session is closed
  • Working with Persistent Objects Deleting an Object
    • Session session = null;
    • Transaction tx = null;
    • try {
    • session = factory .openSession();
    • tx = session .beginTransaction();
    • session .delete( address );
    • tx .commit();
    • } finally {
    • session .close();
    • }
    • Start a Session
    • Transaction is started
    • The object is deleted
    • The transaction is committed
    • The session is closed
  • Persistence Lifecycle Possible States
    • Transient
      • Not Associated with a database table
      • Non-transactional
    • Persisted
      • Object with Database Identity
      • Associates object with a Session
      • Transactional
    • Detached
      • no longer guaranteed to be in synch with the database
  • Persistence Lifecycle
  • Working with Collections
    • Can represent a parent-child/one-many relationship using most of the available Java Collections
    • Persistence by reach-ability
    • No added semantics to your collections
    • Available Collection mappings are
      • <set> , <list> , <map> , <bag> , <array> and <primitive-array>
    • In the database mappings are defined by a foreign key to the owning/parent entity
  • Working with Collections A simple example
  • Working with Collections A simple example
    • public class Conference implements Serializable {
    • ...
    • // Tracks belonging to this Conference
    • private Set tracks ;
    • public Set getTracks () { return tracks ; }
    • public void setTracks (Set tracks) { this . tracks = tracks; }
    • // maintain bi-directional association
    • public void addTrack(Track track ) {
    • if (null == tracks ) tracks = new HashSet();
    • track .setConference(this);
    • tracks .add( track );
    • }
  • Working with Collections A simple example
    • <hibernate-mapping package =&quot; com.integrallis.tcms.domain &quot; >
    • <class name =&quot; Conference &quot;>
    • <id column =&quot; PK_ID &quot; name =&quot; Id “
    • type =&quot;integer&quot;>
    • <generator class =&quot;identity&quot; />
    • </id>
    • ...
    • <set name =&quot; Tracks &quot; inverse =&quot;true&quot;
    • cascade =&quot;all&quot; lazy =&quot;false&quot;>
    • <one-to-many class =&quot; Track &quot; />
    • <key column =&quot; FK_CONFERENCE_ID &quot; />
    • Class/Table
    • How to generate PK
    • Other field mappings
    • Java Set for the Tracks
    • Class on the many side
    • Foreign Key on the many side
  • Association Mappings Supported Associations
    • One-to-one
      • Maintained with Foreign Keys in Database
    • One-to-many / Many-to-one
      • Object on the ‘one’ side
      • Collection on the many ‘side’
    • Many-to-Many
      • Use a ‘mapping’ table in the database
  • Association Mappings Some Details
    • Inverse attribute used for bi-directional associations
    • Lazy Loading
      • Configured per relationship
      • Uses dynamic proxies at Runtime
    • Cascading Styles
      • “ none” no operations are cascaded
      • “ all” all operations are cascaded
      • Every operation in Hibernate has a corresponding cascade style
  • Lazy initialization
    • A Proxy is used
    • Getters are overridden, e.g. Event.getName();
    • The Proxy is a subclass of your persistent class, e.g extends Event
    • Requires build-time bytecode instrumentation
    • Beware of explicit comparison of runtime class, passing of class objects etc.
    v 6, 2006-09-28 Mats Strandberg
  • Hibernate Cachings
  • Caching v 6, 2006-09-28 Mats Strandberg First-level Cache Session Second-level Cache Query Cache Cache Concurrency Strategy Cache Provider
  • Caching in Hibernate
    • 1 st Level
      • Transaction scoped cache provided by the Session.
      • Always available
    • 2 nd Level
      • Process scoped cache
      • Shared by all Sessions
      • Optional
      • Pluggable implementation, can be clustered
    • Query
      • Use with care, profile first
  • Caching in Hibernate
  • Caching in Hibernate
    • Caching setting in HBM for Read Only
    • <class name =“ReferenceData”
    • table =“REFDATA” >
    • <cache usage =“read-only” />
    • ..
    • </class>
  • Caching in Hibernate
    • Caching setting in HBM for Read/Write
    • Profile the application before applying
    • <class name =“ReadMostly”
    • table =“READMOSTLY”>
    • <cache usage =“nonstrict-read-write” />
    • ..
    • </class>
  • Caching in Hibernate
    • Query Caching, most difficult to get right
    • Analyze/Profile First. Let usage determine which queries to cache
    • String queryString = “ from ... ”;
    • List hits = session
    • .createQuery( queryString )
    • .setObject(“user”, user)
    • .setCacheable(true)
    • .list();
  • Caching Demo
  • Other Hibernate Features
    • Multiple Strategies for supporting Inheritance
    • Scalar Query Results
    • Projections
    • Custom SQL for Loading, Updating and Deleting
    • J2EE/JTA Friendly
    • Spring Integration
  • Hibernate Annotations
  • What is Annotation ?
    • Annotation is a specific construction in java 5 for adding additional information to Java source code
    • Annotations are embedded in class files generated by compiler & can be used by other frameworks
  • Annotations Overview
    • Core
      • @Entity
      • @Table
      • @Id
      • @Basic
      • @Column
      • @Transient
      • @Enumerated
      • @Temporal
      • @Type
    • Relationships
      • @ManyToOne
      • @OneToOne
      • @OneToMany
      • @JoinColumn
    • Inheritance
      • @MappedSuperclass
      • @Inheritance
      • @DiscriminatorColumn
      • @DiscriminatorValue
  • @Entity / @Table @Entity @Table(name=“PROSPECT”) public class Prospect extends Persistent { ... public Prospect() { ... } } MAUI.PROSPECT PROSPECT_ID NUMBER(18) LAST_UPD_BY NUMBER(18) LAST_UP_TS TIMESTAMP(9) STUDENT_ID NUMBER(18) ... ...
  • Annotated Java class
    • @Entity // Declares this an entity bean
    • @Table(name = &quot;people&quot;) // Maps the bean to SQL table &quot;people&quot;
    • class Person implements Serializable{
    • @Id // Map this to the primary key column.
    • @GeneratedValue(strategy = GenerationType.AUTO) // Database will generate new primary keys
    • private Integer id;
    • @Column(length = 32) // Truncate column values to 32 characters.
    • private String name;
    • public Integer getId() {
    • return id;
    • }
    • public void setId(Integer id) {
    • this.id = id;
    • }
    • public String getName() {
    • return name;
    • }
    • public void setName(String name) {
    • this.name = name;
    • }
    • }
  • @Id
    • Every entity needs a primary key
    • ...
    • public abstract class Persistent {
    • @Id
    • Long id;
    • ...
    • }
  • @Basic / @Column
    • ...
    • public class Prospect extends Persistent {
    • @Basic
    • @Column(name = &quot;HS_SELF_REPORTED_CLASS_SIZE&quot;)
    • private Integer selfReportedClassSize;
    • @Basic
    • @Column(name = &quot;HS_ANTICIPATED_YR_GRAD&quot;)
    • private String anticipatedHighSchoolGraduationYear;
    • ...
    • }
    MAUI.PROSPECT PROSPECT_ID NUMBER(18) ... ... HS_SELF_REPORTED_CLASS_SIZE NUMBER(5) HS_ANTICIPATED_YR_GRAD CHAR(4) ... ...
  • @Transient
    • Indicates fields that should not be persisted
    • But it could be used for computed/derived data based on the persistent fields of the object
  • @Enumerated
    • public enum ProspectStatusEnum {
    • PROSPECT(&quot;Prospect&quot;),
    • PROSPECT_INACTIVE( &quot;Prospect Inactive&quot;),
    • PROSPECT_APPLIED( &quot;Prospect Applied&quot;);
    • private String label;
    • ProspectStatusEnum(String label) {
    • this.label = label;
    • }
    • public String toString() {
    • return this.label;
    • }
    • }
  • @Enumerated ... public class Prospect extends Persistent { ... @Enumerated(EnumType.STRING) @Column(name = &quot;PRSP_STATUS_EN&quot;) ProspectStatusEnum prospectStatusEnum; ... } MAUI.PROSPECT ... ... PRSP_STATUS_EN VARCHAR(25) ... ...
  • @Temporal
    • ...
    • public class Prospect extends Persistent {
    • ...
    • @Temporal(TemporalType.DATE)
    • @Column(name = &quot;PRSP_STATUS_DT&quot;)
    • private Date prospectStatusDate;
    • ...
    • }
    MAUI.PROSPECT ... ... PRSP_STATUS_DT DATE ... ...
  • @Type ... public class Prospect extends Persistent { ... @Basic @Column(name = &quot;IS_CONTACT_DESIRED&quot;) @org.hibernate.annotations.Type( type = &quot;org.hibernate.type.YesNoType&quot; ) private Boolean contactDesired; ... } MAUI.PROSPECT ... ... IS_CONTACT_DESIRED CHAR(1) ... ...
  • @ManyToOne ... public class Prospect extends Persistent { @ManyToOne() @JoinColumn(name = &quot;PURGE_SESSION_INFO_ID&quot;) private Session purgeSession; ... } @Entity @Table(name = &quot;MAUI.SESSION_INFO&quot;) public class Session extends Persistent { ... } MAUI.SESSION_INFO SESSION_INFO_ID NUMBER(18) ... ... MAUI.PROSPECT PROSPECT_ID NUMBER(18) PK ... ... PURGE_SESSION_INFO_ID NUMBER(18) FK
  • @OneToOne
    • public class Prospect extends Persistent {
    • @OneToOne()
    • @JoinColumn(name = &quot;STUDENT_ID&quot;)
    • private Student student;
    • ...
    • }
    • @Entity
    • @Table(name = &quot;MAUI.STUDENT&quot;)
    • public class Student extends Persistent { ... }
    MAUI.STUDENT STUDENT_ID NUMBER(18) PK ... ... MAUI.PROSPECT PROSPECT_ID NUMBER(18) PK ... ... STUDENT_ID NUMBER(18) FK UNIQUE NOT NULL
  • @OneToMany public class Prospect extends Persistent { ... @OneToMany(mappedBy = &quot;prospect”) private Set<ProspectComment> prospectComments; } @Entity public class ProspectComment extends Persistent { ... @ManyToOne() @JoinColumn(name = &quot;PROSPECT_ID&quot;) private Prospect prospect; } MAUI.PRSP_COMMENT PRSP_COMMENT_ID NUMBER(18) PK PROSPECT_ID NUMBER(18) FK NOT NULL ... ... MAUI.PROSPECT PROSPECT_ID NUMBER(18) PK ... ...
  • @MappedSuperclass
    • @MappedSuperclass
    • public abstract class Persistent {
    • ...
    • @Id
    • private Long id;
    • @Temporal
    • @Column(name = “LAST_UPD_TS”)
    • private Date lastUpdatedTimestamp;
    • }
  • @Inheritance
    • Three strategies
      • Single Table Per Class Hierarchy
        • SINGLE_TABLE
      • Joined Subclass
        • JOINED
      • Table Per Concrete Class
        • TABLE_PER_CLASS
  • Single Table Per Class Hierarchy
    • @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    • @DiscriminatorFormula(...)
    • public abstract class Institution {}
    • @DiscriminatorValue(“SECONDARY”)
    • public class SecondarySchool extends Institution {}
    • @DiscriminatorValue(“POST_SECONDARY”)
    • public class PostSecondarySchool
    • extends Institution {}
  • Working with Persistent Objects
    • // create a new prospect
    • // and make it persistent persistent
    • Prospect p = new Prospect();
    • EntityManager em = ...
    • em.persist(p);
    • // Hibernate will execute an SQL insert statement
  • Working with Persistent Objects
    • // find an existing Prospect by Id
    • // and delete it
    • EntityManager em = ...
    • Long id = ...
    • Prospect p = em.find(Prospect.class, id);
    • em.remove(p);
    • // Hibernate will execute an SQL delete statement
  • Working with Persistent Objects
    • // find an existing Prospect by Id
    • // and modify it
    • EntityManager em = ...
    • Long id = ...
    • Prospect p = em.find(Prospect.class, id);
    • p.setSelfReportedClassSize(400);
    • // no explicit persist() call is needed
    • // this object is already persistent
    • // Hibernate will determine that it is dirty and
    • // will execute an SQL update statement
  • Hibernate Annotations Demo