HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015
L18 Object Relational Mapping
Reading
▪ Hibernate (Wikipedia)
▪ ORMHate
▪ Introduction to NoSQL
Agenda
▪ Object Relational Mapping – ORM
▪ NoSQL
▪ Hibernate
Object Relational Mapping – ORM
Object Relational Mapping (ORM)
▪ Use a mapping layer to map between objects and tables
– Mapping a data representation from an object model to a
relational data model with a SQL-based schema
▪ Mapping requires 

metadata
– XML
▪ Authoring and 

maintaining 

metadata is less work than maintaining SQL
Advantages of ORM
▪ Can radically reduce the amount of code you need to write
– 30% compared to JDBC for server side application
▪ More Productivity
▪ Applications are easier to maintain
▪ Fosters thinking about an OO domain model
Disadvantages of ORM
▪ Some loss of control over the persistence process
▪ May be more difficult to tune queries
▪ Performance characteristics of the tool may affect your application’s
performance
When to use ORM?
▪ Well-suited to ORM
– Read-modify-write lifecycle
– Little requirement for stored procedures
▪ Poorly suited to ORM
– “Window on data” application
– Significant use of stored procedures
– Write centric apps, where data is seldom read
When to use ORM?
▪ Typical server-side applications are fairly well suited for ORM
– 90%-95% of applications
– But there are always some special cases
– Mix and match as needed
Hibernate
Hibernate
▪ Object/relational mapping tool
– A persistence service that stores Java objects in relational
databases
– Provides an object oriented view of existing relational data
▪ Uses reflection and XML mapping files to persist POJOs
– No changes to business domain objects
– The goal is to relieve the developer from a significant amount of
common data persistence-related programming tasks
Architecture
▪ High-level architecture
Properties
file define
data access
Mapping
definition
maps classes
to tables
Architecture
Database Properties
▪ File
– hibernate.properties
▪ Contains information to access the database
– Username and password
– URL
– Database driver
▪ Hibernate will automatically read the file from the classpath
hibernate.connection.username=andri
hibernate.connection.password=abc123
hibernate.connection.url=jdbc:jtds:sqlserver://honn.ru.is:1433
hibernate.connection.driver_class=net.sourceforge.jtds.jdbc.Driver
Mapping File
▪ File
– hibernate-mapping
– In the same package as Nemandi class
<hibernate-mapping>
<class name="org.ru.honn.domain.Nemandi" table="NEMENDUR">
<id name="kennitala" column="kennitala" type="string">
</id>
<property name="nafn" column="nafn" type="string"
length="64" not-null="false"/>
<property name="netfang" column="netfang" type="string"
length="64" not-null="false"/>
<property name="hopur" column="hopur" type="string"
length="32" not-null="false" />
</class>
</hibernate-mapping>
Using Hibernate
▪ Usually an application will
– Create a single Configuration
– Build a single instance of SessionFactory
– Then instantiate Session objects
Configuration cfg = new Configuration();
cfg.addClass(theClass);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Using Hibernate
▪ Configuration
– Allows the application to specify properties and mapping
documents to be used when creating a SessionFactor
▪ SessionFactory
– Factory class to create Session objects
▪ Session
– Interface that represents a transaction
– The main function is to offer create, read and delete operations for
instances of mapped entity classes
Example
▪ NemandiGateway
public interface NemandiGateway
{
public Nemandi findNemandi(String kennitala);
public Collection getNemendur();
public void addNemandi(Nemandi nemandi);
}
Example
▪ NemandiData
– Constructor creates the configuration and the factory
– Variable factory is used when a Session is needed
public class NemandiData implements NemandiGateway
{
SessionFactory factory = null;
public NemandiData()
{
Configuration cfg = new Configuration();
cfg.addClass(Nemandi.class);
factory = cfg.buildSessionFactory();
}
Example
▪ NemandiData
– findNemandi
public Nemandi findNemandi(String kennitala)
{
Session session = factory.openSession();
Nemandi nem = (Nemandi)session.get(Nemandi.class, kennitala);
session.close();
return nem;
}
Example
▪ NemandiData
– getNemendur
– Uses the Hibernate Query Language, HQL
public Collection getNemendur()
{
Session session = factory.openSession();
List l = session.createQuery(
"SELECT n FROM is.ru.honn.domain.Nemandi AS n").list();
session.close();
return l;
}
Example
▪ NemandiData
– addNemandi
public void addNemandi(Nemandi nemandi)
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
session.save(nemandi);
tx.commit();
session.close();
}
NoSQL Databases
Matin Fowler on NoSQL
Data Model
Key-Value
▪ Basically Map<String, Object>
▪ They are also referred to as "schema on read" as one entry may be a
String, another a Date, a third PNG image
▪ Key-Value stores offer no indexes, and no querying capabilities
▪ Examples:
– Property files, Dynamo, Riak, Redis, Aerospike, Voldemort
Document Store
▪ Mesh of documents
– Documents can have any structure – “no schema” or implicit
schema
– Json is popular
▪ Examples
– MongoDB, MarkLogic, CouchDB, RavenDB,
Tablestyle Database
▪ The value stored is sort of a transposed table in it self
– Sort of like Map<String, Map<String, Object>>
– Such structures are extremely useful to store sparse data in
▪ Examples:
– Cassandra, Hadoop/HBase, Apache Fink, Monet
Graph Databases
▪ Graph or network structure of data: Entities and facts about these in
the relations on them
– Graph Databases resembles Prolog in their use to infer new insights
based upon facts and rules
▪ Really good at relation magic, e.g. if you have a "friends" relation on
"user" entities
▪ Examples:
– Neo4J, GraphBase, Trinity
Summary
▪ Object Relational Mapping – ORM
– Useful tools that work in most cases
– Still controversial
▪ Hibernate
– An example of a mapping tool
– One of the possible options
▪ NoSQL
– New bread of 21. century web databases

L18 Object Relational Mapping

  • 1.
    HÖNNUN OG SMÍÐIHUGBÚNAÐAR 2015 L18 Object Relational Mapping
  • 2.
    Reading ▪ Hibernate (Wikipedia) ▪ORMHate ▪ Introduction to NoSQL
  • 3.
    Agenda ▪ Object RelationalMapping – ORM ▪ NoSQL ▪ Hibernate
  • 4.
  • 5.
    Object Relational Mapping(ORM) ▪ Use a mapping layer to map between objects and tables – Mapping a data representation from an object model to a relational data model with a SQL-based schema ▪ Mapping requires 
 metadata – XML ▪ Authoring and 
 maintaining 
 metadata is less work than maintaining SQL
  • 6.
    Advantages of ORM ▪Can radically reduce the amount of code you need to write – 30% compared to JDBC for server side application ▪ More Productivity ▪ Applications are easier to maintain ▪ Fosters thinking about an OO domain model
  • 7.
    Disadvantages of ORM ▪Some loss of control over the persistence process ▪ May be more difficult to tune queries ▪ Performance characteristics of the tool may affect your application’s performance
  • 8.
    When to useORM? ▪ Well-suited to ORM – Read-modify-write lifecycle – Little requirement for stored procedures ▪ Poorly suited to ORM – “Window on data” application – Significant use of stored procedures – Write centric apps, where data is seldom read
  • 9.
    When to useORM? ▪ Typical server-side applications are fairly well suited for ORM – 90%-95% of applications – But there are always some special cases – Mix and match as needed
  • 10.
  • 11.
    Hibernate ▪ Object/relational mappingtool – A persistence service that stores Java objects in relational databases – Provides an object oriented view of existing relational data ▪ Uses reflection and XML mapping files to persist POJOs – No changes to business domain objects – The goal is to relieve the developer from a significant amount of common data persistence-related programming tasks
  • 12.
    Architecture ▪ High-level architecture Properties filedefine data access Mapping definition maps classes to tables
  • 13.
  • 14.
    Database Properties ▪ File –hibernate.properties ▪ Contains information to access the database – Username and password – URL – Database driver ▪ Hibernate will automatically read the file from the classpath hibernate.connection.username=andri hibernate.connection.password=abc123 hibernate.connection.url=jdbc:jtds:sqlserver://honn.ru.is:1433 hibernate.connection.driver_class=net.sourceforge.jtds.jdbc.Driver
  • 15.
    Mapping File ▪ File –hibernate-mapping – In the same package as Nemandi class <hibernate-mapping> <class name="org.ru.honn.domain.Nemandi" table="NEMENDUR"> <id name="kennitala" column="kennitala" type="string"> </id> <property name="nafn" column="nafn" type="string" length="64" not-null="false"/> <property name="netfang" column="netfang" type="string" length="64" not-null="false"/> <property name="hopur" column="hopur" type="string" length="32" not-null="false" /> </class> </hibernate-mapping>
  • 16.
    Using Hibernate ▪ Usuallyan application will – Create a single Configuration – Build a single instance of SessionFactory – Then instantiate Session objects Configuration cfg = new Configuration(); cfg.addClass(theClass); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession();
  • 17.
    Using Hibernate ▪ Configuration –Allows the application to specify properties and mapping documents to be used when creating a SessionFactor ▪ SessionFactory – Factory class to create Session objects ▪ Session – Interface that represents a transaction – The main function is to offer create, read and delete operations for instances of mapped entity classes
  • 18.
    Example ▪ NemandiGateway public interfaceNemandiGateway { public Nemandi findNemandi(String kennitala); public Collection getNemendur(); public void addNemandi(Nemandi nemandi); }
  • 19.
    Example ▪ NemandiData – Constructorcreates the configuration and the factory – Variable factory is used when a Session is needed public class NemandiData implements NemandiGateway { SessionFactory factory = null; public NemandiData() { Configuration cfg = new Configuration(); cfg.addClass(Nemandi.class); factory = cfg.buildSessionFactory(); }
  • 20.
    Example ▪ NemandiData – findNemandi publicNemandi findNemandi(String kennitala) { Session session = factory.openSession(); Nemandi nem = (Nemandi)session.get(Nemandi.class, kennitala); session.close(); return nem; }
  • 21.
    Example ▪ NemandiData – getNemendur –Uses the Hibernate Query Language, HQL public Collection getNemendur() { Session session = factory.openSession(); List l = session.createQuery( "SELECT n FROM is.ru.honn.domain.Nemandi AS n").list(); session.close(); return l; }
  • 22.
    Example ▪ NemandiData – addNemandi publicvoid addNemandi(Nemandi nemandi) { Session session = factory.openSession(); Transaction tx = session.beginTransaction(); session.save(nemandi); tx.commit(); session.close(); }
  • 23.
  • 24.
  • 26.
  • 27.
    Key-Value ▪ Basically Map<String,Object> ▪ They are also referred to as "schema on read" as one entry may be a String, another a Date, a third PNG image ▪ Key-Value stores offer no indexes, and no querying capabilities ▪ Examples: – Property files, Dynamo, Riak, Redis, Aerospike, Voldemort
  • 28.
    Document Store ▪ Meshof documents – Documents can have any structure – “no schema” or implicit schema – Json is popular ▪ Examples – MongoDB, MarkLogic, CouchDB, RavenDB,
  • 29.
    Tablestyle Database ▪ Thevalue stored is sort of a transposed table in it self – Sort of like Map<String, Map<String, Object>> – Such structures are extremely useful to store sparse data in ▪ Examples: – Cassandra, Hadoop/HBase, Apache Fink, Monet
  • 30.
    Graph Databases ▪ Graphor network structure of data: Entities and facts about these in the relations on them – Graph Databases resembles Prolog in their use to infer new insights based upon facts and rules ▪ Really good at relation magic, e.g. if you have a "friends" relation on "user" entities ▪ Examples: – Neo4J, GraphBase, Trinity
  • 31.
    Summary ▪ Object RelationalMapping – ORM – Useful tools that work in most cases – Still controversial ▪ Hibernate – An example of a mapping tool – One of the possible options ▪ NoSQL – New bread of 21. century web databases