Upload
jocelin-chambers
View
214
Download
0
Tags:
Embed Size (px)
Citation preview
Quiz Results: How did you do? Did you answer “Yes” to all of the
databases? If not, this presentation is for You!
Hibernate’s Most Important Features
Object to Relational Mapping Tool. Relational databases do not map well to the real world Takes Java Objects and maps them to relational tables
Not easy! Works with any relational database
Handles Database Transactions Automatically Possible through mapping files Programmers don’t need to worry about writing SQL
FACT: Programmers are not typically proficient in SQL but still need to interact with databases on a regular basis.
Another tool to help you get things done. Because that’s what gets you hired and keeps you
employed
What Hibernate Isn’t?
The answer to all of your database problems. No amount of awesome code will substitute for good design. At the end of the day, data is stored in a relational model
Example
Suppose you have a system that needs to keep track of students and courses (easy) Students Table Courses Table
How do we express the m:n relationship for students that need to enroll in several courses? (not as easy) Enrolled Table (This does not map well to an
object) Can Hibernate help with this?
Yes!
The Anatomy of a Hibernate Project
Java Classes Student.java Course.java
Hibernate Mapping File Student.hbm.xml Course.hbm.xml
Hibernate Files hibernate.cfg.xml HibernateUtil.java StudentManager.java
main()
Regular Java Objects
Student.java
public class Student {
private long sid; private String firstName; private String lastName; private double gpa;
Student() {} //Default constructor
public Student(String firstName, String lastName, double gpa) { this.firstName = firstName; this.lastName = lastName; this.gpa = gpa; }
public void setSid(long sid) { this.sid = sid; }
public long getSid() { return this.sid; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
... ...}
Just a regular everyday Java class
Need a getter/setter for each database value
Course.javapublic class Course { long cid; String name; Set students = new HashSet();
public Course() {}
public Course(String name) { this.name = name; }
... ...
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Set getStudents() { return students; }
public void setStudents(Set students) { this.students = students; }
public void addStudent(Student student) { this.students.add(student); }}
Each course object holds a collection of the Students enrolled in it.
Student.hbm.xml
Teach Hibernate how to map objects to the database
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping> <class name="CSE7330.greiner.hibernate.Student" table="students"> <id name="sid" column="sid"> <generator class="increment" /> </id>
<property name="firstName" column="first_name" /> <property name="lastName" column="last_name" /> <property name="gpa" column="gpa" /> </class></hibernate-mapping>
Course.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping> <class name="CSE7330.greiner.hibernate.Course" table="courses"> <id name="cid" column="cid"> <generator class="increment" /> </id>
<property name="name" column="course_name" />
<set name="students" table="list" lazy="true"> <key column="cid"/> <many-to-many column="sid" class="Student"/> </set> </class></hibernate-mapping>
Hibernate.cfg.xml<!DOCTYPE hibernate-configuration SYSTEM"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.url“>jdbc:hsqldb:hsql://localhost</property> <property name="hibernate.connection.username“>sa</property> <property name="hibernate.dialect“>org.hibernate.dialect.HSQLDialect</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.timeout">300</property> <property name="hibernate.c3p0.max_statements">50</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="show_sql">false</property> <property name="format_sql">true</property> <mapping resource="CSE7330/greiner/hibernate/Student.hbm.xml" /> <mapping resource="CSE7330/greiner/hibernate/Course.hbm.xml" /> </session-factory></hibernate-configuration>
HibernateUtil.java – The Setup
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory(); private static Session session = HibernateUtil.getSessionFactory().openSession(); private static SessionFactory buildSessionFactory() { try { return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.out.println("Exception!!!!"); throw new ExceptionInInitializerError(ex); } }
public static SessionFactory getSessionFactory() { return sessionFactory; } ...
HibernateUtil.java – Insert Students/Courses
public static void insertStudents(List<Student> students) { //Inserts a list of students into the database Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction();
for (Student s : students) { Long sid = (Long) session.save(s); }
tx.commit(); session.close();}public static void insertCourses(List<Course> courses) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction();
for (Course c : courses) { Long sid = (Long) session.save(c); }
tx.commit(); session.close();}
HibernateUtil.java – Read Students/Coursesprivate static List<Student> getStudents() { List<Student> students = new ArrayList<Student>(); students = session.createCriteria(Student.class).list(); return students;}
private static List<Course> getCourses() { List<Course> courses = new ArrayList<Course>(); courses = session.createCriteria(Course.class).list(); return courses;}
HibernateUtil.java – Print Collectionspublic static void printDatabaseState() { List<Student> students = getStudents(); List<Course> courses = getCourses(); Set studentsInCourse = new HashSet(); for (Student s : students) { System.out.println(s.getSid() + " - " + s.getFirstName() + " " + s.getLastName()); } for (Course c : courses) { studentsInCourse = c.getStudents(); System.out.println(c.getName()); for (Object s : studentsInCourse) { System.out.println(" " + ((Student)s).getFirstName() + " " + ((Student)s).getLastName()); } }}
StudentManager.java
public class StudentManager { List<Student> students = new ArrayList<Student>(); List<Course> courses = new ArrayList<Course>();
public static void main(String[] args) { //Initialize and call each method } public void addStudents() { this.students.add(new Student("Albert", "Einstein", 4.0)); this.students.add(new Student("Carl", "Sagan", 2.5)); this.students.add(new Student("Alan", "Turing", 4.0)); this.students.add(new Student("Ken", "Thompson", 4.0)); this.students.add(new Student("Bill", "Gates", 0.0)); this.students.add(new Student("Steve", "Jobs", 3.5)); HibernateUtil.insertStudents(this.students); } public void addCourses() { this.courses.add(new Course("CSE7330")); this.courses.add(new Course("CSE5330")); this.courses.add(new Course("CSE7314")); this.courses.add(new Course("CSE8313"));
this.courses.get(0).addStudent(this.students.get(0)); this.courses.get(0).addStudent(this.students.get(1)); this.courses.get(0).addStudent(this.students.get(2)); this.courses.get(1).addStudent(this.students.get(3)); this.courses.get(1).addStudent(this.students.get(5)); this.courses.get(2).addStudent(this.students.get(0)); this.courses.get(2).addStudent(this.students.get(1)); this.courses.get(3).addStudent(this.students.get(2)); this.courses.get(3).addStudent(this.students.get(3)); this.courses.get(3).addStudent(this.students.get(5)); HibernateUtil.insertCourses(this.courses); }}
Results
Program Output1 - Albert Einstein2 - Carl Sagan3 - Alan Turing4 - Ken Thompson5 - Bill Gates6 - Steve Jobs
CSE7330 Alan Turing Albert Einstein Carl SaganCSE5330 Steve Jobs Ken ThompsonCSE7314 Albert Einstein Carl SaganCSE8313 Alan Turing Steve Jobs Ken Thompson
Summary
It can be difficult to express real life objects as relations
Hibernate is an Object to Relational mapping tool Example: No 3rd Enrolled object needed
Allows for a more Object Oriented approach Hibernate allows you to interact with a
database without having to know platform-specific SQL Did you see one line of SQL in this
presentation?
Future Applications
Web frameworks are moving towards ORM. Rails (Ruby) Django (Python)
Hibernate for other languages nHibernate (.NET)
The 5 W’s of Hibernate
Who: Hibernate is maintained by Red Hat What: Object to Relational Mapping Tool When: Your next project that uses a database Where: Project Homepage:
http://hibernate.org Why: Get things done!
References Harnessing Hibernate
Dr. James Elliot O'Reilly Media (April 1, 2008) Amazon Link
Java Persistence with Hibernate Christian Bauer Manning Publications; Revised edition (November 24,
2006) Amazon Link
https://www.hibernate.org/ Official Hibernate Project Site Red Hat 11/11/2009
http://www.allapplabs.com/hibernate/hibernate_tutorials.htm Hibernate Tutorials Bushan Dongare Good intro tutorial to hibernate 11/11/2009
http://stackoverflow.com/questions/tagged/hibernate Stack Overflow Tag for Hibernate Questions Great community resource for getting your questions
answered Community Authored and Licensed 2008-2009