Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Getting Things Done with Hibernate Robert Greiner CSE7330 Southern Methodist University Introduction – A quick Quiz. How many of you are proficient in: 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! Let’s see some code 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 private private private Just a regular everyday Java class long sid; String firstName; String lastName; 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; } Need a getter/setter for each database value public void setFirstName(String firstName) { this.firstName = firstName; } ... ... } Course.java public class Course { long cid; String name; Set students = new HashSet(); public Course() {} Each course object holds a collection of the Students enrolled in it. 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); } } Student.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.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> Teach Hibernate how to map objects to the database 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 <property <property <property <property name="hibernate.c3p0.min_size">5</property> name="hibernate.c3p0.max_size">20</property> name="hibernate.c3p0.timeout">300</property> name="hibernate.c3p0.max_statements">50</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/Courses private 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 Collections public 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 Output 1 - Albert Einstein 2 - Carl Sagan 3 - Alan Turing 4 - Ken Thompson 5 - Bill Gates 6 - Steve Jobs CSE7330 Alan Turing Albert Einstein Carl Sagan CSE5330 Steve Jobs Ken Thompson CSE7314 Albert Einstein Carl Sagan CSE8313 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: Allows No 3rd Enrolled object needed 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