Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Hibernate ORM

Hibernate ORM

Hibernate ORM

Jussi Pohjolainen

November 14, 2016
Tweet

More Decks by Jussi Pohjolainen

Other Decks in Technology

Transcript

  1. 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
  2. "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.
  3. 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; } }
  4. 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(); } }
  5. hibernate.cfg.xml (mysql) <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration

    DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hbm2ddl.auto">update</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost/test</property> <property name="connection.username"></property> <property name="connection.password"></property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <mapping resource="employee.hbm.xml"/> <mapping class="Employee"/> </session-factory> </hibernate-configuration>
  6. hibernate.cfg.xml (derby) <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration

    DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.DerbyDialect</property> <property name="hbm2ddl.auto">update</property> <property name="connection.url">jdbc:derby://localhost:1527/donaldduck;create=true</property> <property name="connection.username">APP</property> <property name="connection.password">APP</property> <property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property> <mapping resource="employee.hbm.xml"/> <mapping class="Employee"/> </session-factory> </hibernate-configuration>
  7. <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="employees"> <id name="id"> <generator class="assigned"></generator> </id> <property name="firstName"></property> <property name="lastName"></property> </class> </hibernate-mapping>
  8. 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(); }
  9. Compile and Run • Mac or Linux • javac -cp

    .:required/* *.java • java -cp .:required/* StoreData • Windows • javac -cp .;required/* *.java • java -cp .;required/* StoreData
  10. 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
  11. ID

  12. ID Generator <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping

    DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="employees"> <id name="id"> <generator class="assigned"></generator> </id> <property name="firstName"></property> <property name="lastName"></property> </class> </hibernate-mapping> 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
  13. native <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD

    3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="employees"> <id name="id"> <generator class="identity"></generator> </id> <property name="firstName"></property> <property name="lastName"></property> </class> </hibernate-mapping>
  14. SQL CREATE TABLE employees ( id INT(11) NOT NULL auto_increment

    PRIMARY KEY, firstname VARCHAR(255), lastname VARCHAR(255) );
  15. Code // Create pojo Employee e1 = new Employee(); //

    e1.setId(115); e1.setFirstName("Hello"); e1.setLastName("World");
  16. Database mysql> select * from employees; +----+-----------+----------+ | id |

    firstName | lastName | +----+-----------+----------+ | 1 | Hello | World | | 2 | Hello | World | +----+-----------+----------+ 2 rows in set (0.00 sec)
  17. Hibernate Query Language • Load complete set of resources •

    List<Employee> results = session.createQuery("FROM Employee").list(); • SELECT • List<String> results = session.createQuery("SELECT firstName FROM Employee").list(); • WHERE • List<Employee> 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")
  18. Mapping is done in code! <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration

    PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hbm2ddl.auto">update</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost/test</property> <property name="connection.username"></property> <property name="connection.password"></property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!--<mapping resource="employee.hbm.xml"/> --> <!--<mapping class="Employee"/> --> </session-factory> </hibernate-configuration>
  19. 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;
  20. 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;
  21. 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();