Slide 1

Slide 1 text

Hibernate ORM Jussi Pohjolainen

Slide 2

Slide 2 text

Overview • Hibernate ORM is an object-relational mapping framework for Java • Mapping Java classess to databatase tables • Free software • Mapping is done by using • 1) XML configuration or • 2) Java annotations • Classes must have no-argument constructor • Collections are stored in Set or List, also generics are supported • Can be used part of Java SE or EE

Slide 3

Slide 3 text

"Hello world" 1. Download needed jars from Hibernate site http://hibernate.org/orm/ 2. Take the jars from the required/ folder and put those to classpath 3. Create plain old java object (Employee.java) 4. Create Java file with main – method that stores POJOs to database (StoreData.java) 5. Optional: Create hibernate mapping xml file that has rules how to map POJO to relational database (employee.hbm.xml) 6. Create hibernate configuration xml file that defines the database you are accessing (hibernate.cfg.xml) Notice also MySQL Driver. Separate download.

Slide 4

Slide 4 text

public class Employee { private int id; private String firstName,lastName; public Employee() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }

Slide 5

Slide 5 text

import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; public class StoreData { public static void main(String[] args) { // Create configuration object Configuration cfg = new Configuration(); // Populate the data of the default configuration file which name // is hibernate.cfg.xml cfg.configure(); // Create SessionFactory that can be used to open a session SessionFactory factory = cfg.buildSessionFactory(); // Session is an interface between Java app and Database // Session is used to create, read, delete operations Session session = factory.openSession(); Transaction tx = session.beginTransaction(); // Create pojo Employee e1 = new Employee(); e1.setId(2); e1.setFirstName("Hello"); e1.setLastName("World"); // Save to database session.persist(e1); tx.commit(); // Close connection factory.close(); } }

Slide 6

Slide 6 text

hibernate.cfg.xml (mysql) update org.hibernate.dialect.MySQLDialect jdbc:mysql://localhost/test com.mysql.jdbc.Driver

Slide 7

Slide 7 text

hibernate.cfg.xml (derby) org.hibernate.dialect.DerbyDialect update jdbc:derby://localhost:1527/donaldduck;create=true APP APP org.apache.derby.jdbc.ClientDriver

Slide 8

Slide 8 text

Slide 9

Slide 9 text

Transaction Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // Create pojo Employee e1 = new Employee(); e1.setId(1152); e1.setFirstName("Hello"); e1.setLastName("World"); // Save to database session.persist(e1); tx.commit(); } catch(Exception e) { if(tx != null) { tx.rollback(); } e.printStackTrace(); } finally { factory.close(); }

Slide 10

Slide 10 text

Compile and Run • Mac or Linux • javac -cp .:required/* *.java • java -cp .:required/* StoreData • Windows • javac -cp .;required/* *.java • java -cp .;required/* StoreData

Slide 11

Slide 11 text

Compile and Run Derby • Mac or Linux • javac -cp .:required/* *.java • java -cp .:$DERBY_HOME/lib/derbyclient.jar:required/* StoreData • Windows • javac -cp .;required/* *.java • java -cp .;%DERBY_HOME%/lib/derbyclient;required/* StoreData

Slide 12

Slide 12 text

ID

Slide 13

Slide 13 text

ID Generator assigned => id is assigned in code Change to identity so that mysql will handle autoincrement. Lot of possibilities here: http://www.javatpoint. com/generator-classes

Slide 14

Slide 14 text

native

Slide 15

Slide 15 text

SQL CREATE TABLE employees ( id INT(11) NOT NULL auto_increment PRIMARY KEY, firstname VARCHAR(255), lastname VARCHAR(255) );

Slide 16

Slide 16 text

Code // Create pojo Employee e1 = new Employee(); // e1.setId(115); e1.setFirstName("Hello"); e1.setLastName("World");

Slide 17

Slide 17 text

Database mysql> select * from employees; +----+-----------+----------+ | id | firstName | lastName | +----+-----------+----------+ | 1 | Hello | World | | 2 | Hello | World | +----+-----------+----------+ 2 rows in set (0.00 sec)

Slide 18

Slide 18 text

Reading

Slide 19

Slide 19 text

Hibernate Query Language • Load complete set of resources • List results = session.createQuery("FROM Employee").list(); • SELECT • List results = session.createQuery("SELECT firstName FROM Employee").list(); • WHERE • List results = session.createQuery("FROM Employee WHERE ID = 10").list(); • You will get a warning: [unchecked] unchecked conversion because hibernate is not type safe by design. Solution: • @SuppressWarnings("unchecked")

Slide 20

Slide 20 text

Annotations

Slide 21

Slide 21 text

Mapping is done in code! update org.hibernate.dialect.MySQLDialect jdbc:mysql://localhost/test com.mysql.jdbc.Driver

Slide 22

Slide 22 text

Annotations @Entity @Table(name = "employees") public class Employee { // Each pojo will have a primary key which you annotate // by using @Id @Id @Column(name = "id") private int id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName;

Slide 23

Slide 23 text

Annotations @Entity @Table(name = "employees") public class Employee { // Each pojo will have a primary key which you annotate // by using @Id @Id // Define strategy how to save this to db // IDENTIFY allow auto increment on demand in MySQL @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName;

Slide 24

Slide 24 text

Configuration without XML public class StoreData { public static void main(String[] args) { // Create configuration object Configuration cfg = new Configuration(); // Populate the data of the configuration file cfg.configure(); cfg.addAnnotatedClass(Employee.class); // Create session object SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession();