250 likes | 417 Views
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!.
E N D
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!
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 publicclass Student { privatelongsid; privateString firstName; privateString lastName; privatedoublegpa; Student() {} //Default constructor publicStudent(String firstName, String lastName, doublegpa) { this.firstName= firstName; this.lastName= lastName; this.gpa= gpa; } publicvoidsetSid(longsid) { this.sid= sid; } publiclonggetSid() { returnthis.sid; } publicString getFirstName() { returnfirstName; } publicvoidsetFirstName(String firstName) { this.firstName= firstName; } ... ... } Just a regular everyday Java class Need a getter/setter for each database value
Course.java publicclass Course { longcid; String name; Set students = newHashSet(); publicCourse() {} publicCourse(String name) { this.name= name; } ... ... publicString getName() { returnname; } publicvoidsetName(String name) { this.name= name; } publicSet getStudents() { returnstudents; } publicvoidsetStudents(Set students) { this.students = students; } publicvoidaddStudent(Student student) { this.students.add(student); } } Each course object holds a collection of the Students enrolled in it.
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 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 publicclassHibernateUtil { privatestaticfinalSessionFactorysessionFactory = buildSessionFactory(); privatestatic Session session = HibernateUtil.getSessionFactory().openSession(); privatestaticSessionFactorybuildSessionFactory() { try { returnnew Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.out.println("Exception!!!!"); thrownewExceptionInInitializerError(ex); } } publicstaticSessionFactorygetSessionFactory() { returnsessionFactory; } ...
HibernateUtil.java – Insert Students/Courses publicstaticvoidinsertStudents(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(); } publicstaticvoidinsertCourses(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 privatestatic List<Student> getStudents() { List<Student> students = newArrayList<Student>(); students = session.createCriteria(Student.class).list(); return students; } privatestaticList<Course> getCourses() { List<Course> courses = newArrayList<Course>(); courses = session.createCriteria(Course.class).list(); return courses; }
HibernateUtil.java – Print Collections publicstaticvoidprintDatabaseState() { List<Student> students = getStudents(); List<Course> courses = getCourses(); Set studentsInCourse = newHashSet(); 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 publicclassStudentManager{ List<Student> students = newArrayList<Student>(); List<Course> courses = newArrayList<Course>(); publicstaticvoid main(String[] args) { //Initialize and call each method } publicvoidaddStudents() { this.students.add(newStudent("Albert", "Einstein", 4.0)); this.students.add(newStudent("Carl", "Sagan", 2.5)); this.students.add(newStudent("Alan", "Turing", 4.0)); this.students.add(newStudent("Ken", "Thompson", 4.0)); this.students.add(newStudent("Bill", "Gates", 0.0)); this.students.add(newStudent("Steve", "Jobs", 3.5)); HibernateUtil.insertStudents(this.students); } publicvoidaddCourses() { this.courses.add(newCourse("CSE7330")); this.courses.add(newCourse("CSE5330")); this.courses.add(newCourse("CSE7314")); this.courses.add(newCourse("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: 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 • BushanDongare • 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