CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 2 Form Project Teams 3 students each. Pick a team name. Each team member will get the same score for each team project. Teams will last the entire semester. Choose your team members wisely! Someone from each team send me: Your team name Name and address of each team member If necessary, I will arbitrarily form teams by randomly assigning students.
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 3 Project #1 At this time, each team should: Find an interesting dataset to download. Or make up a dataset. Design tables with one-to-one, one-to-many, and many-to-many associations. Add new tables (and populate with sample data) as necessary. Design an application with queries that will show off your tables and their associations. Such as by printing reports. Start thinking about how to use Hibernate!
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 4 Hibernate on NetBeans and Eclipse See my write-up: 1/Hibernate.pdf 1/Hibernate.pdf
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 5 public class Student { private long id; private String firstName; private String lastName; public Student() {} public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 6 public class @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 7 Student.java Main method (for testing) public static void main(String args[]) { // Configure Hibernate and add the Student class. AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Student.class); config.configure(); // Create the database table. (new SchemaExport(config)).create(true, true); // Create a session. SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession();... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 8 Student.java public static void main(String args[]) {... // Create a session. SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); // Load the Student table in a transaction. Transaction tx = session.beginTransaction(); { session.save(new Student("Mary", "Jane")); session.save(new Student("Kim", "Smith")); session.save(new Student("John", "Doe")); session.save(new Student("Tim", "Novak")); session.save(new Student("Leslie", "Klein")); } tx.commit(); session.close(); } SchoolDemo1
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 9 HibernateContext.java Goal: Move all the Hibernate bookkeeping code into a shared class.
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 10 HibernateContext.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class HibernateContext { public static AnnotationConfiguration config = null; public static SessionFactory factory = null; /** * Set the configuration if it is null. */ private static void setConfiguration() { if (config == null) { config = new AnnotationConfiguration(); config.configure(); } }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 11 HibernateContext.java public class HibernateContext { public static AnnotationConfiguration config = null; public static SessionFactory factory = null;... /** * Set the factory if it is null. */ private static void setFactory() { if (factory == null) { setConfiguration(); factory = config.buildSessionFactory(); } }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 12 HibernateContext.java public class HibernateContext { public static AnnotationConfiguration config = null; public static SessionFactory factory = null;... /** * Open a session from the factory. a session. */ public static Session getSession() { setFactory(); return factory.openSession(); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 13 HibernateContext.java public class HibernateContext { public static AnnotationConfiguration config = null; public static SessionFactory factory = null;... /** * Create a new schema (database) from the configuration. */ public static void createSchema() { setConfiguration(); (new SchemaExport(config)).create(true, true); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 14 HibernateContext.java public class HibernateContext { public static AnnotationConfiguration config = null; public static SessionFactory factory = null;... /** * Add a new class object to the database. klass the class object. */ public static void addClass(Class klass) { setConfiguration(); config.addAnnotatedClass(klass); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 15 HibernateContext.java public class HibernateContext { public static AnnotationConfiguration config = null; public static SessionFactory factory = null;... /** * Add a list of class objects to the database. klasses the list of class objects. */ public static void addClasses(Class klasses[]) { for (Class klass : klasses) { addClass(klass); } } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 16 public class Student {... public static Student find(long id) { Session session = HibernateContext.getSession(); Query query = session.createQuery("from Student where id = :idvar"); query.setLong("idvar", id); Student student = (Student) query.uniqueResult(); session.close(); return student; }... } Hibernate Query Language (HQL)
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 17 public class Student {... public static Student find(String lastName) { Session session = HibernateContext.getSession(); Query query = session.createQuery("from Student where lastName = :name"); query.setString("name", lastName); Student student = (Student) query.uniqueResult(); session.close(); return student; }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 18 Teacher.java Similar to public class Teacher { private long id; private String firstName; private String lastName; public Teacher () {} public Teacher(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 19 public class @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 20 public class Teacher {... /** * Load the Teacher table. */ public static void load() { Session session = HibernateContext.getSession(); Transaction tx = session.beginTransaction(); { session.save(new Teacher("Tom", "Rogers")); session.save(new Teacher("Art", "Thompson")); session.save(new Teacher("John", "Lane")); session.save(new Teacher("Mabel", "Flynn")); } tx.commit(); session.close(); System.out.println("Teacher table loaded."); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 21 public class Teacher {... /** * List all the teachers. */ public static void list() { Session session = HibernateContext.getSession(); Query query = session.createQuery("from Teacher"); System.out.println("All teachers:"); for (Teacher teacher : (List ) query.list()) { teacher.print(); } session.close(); } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 22 public class Teacher {... /** * Print teacher attributes. */ public void print() { System.out.printf("%d: %s %s\n", id, firstName, lastName); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 23 SchoolDemo.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SchoolDemo { private static final String HELP_MESSAGE = "*** Commands: create, load, find, students, teachers, quit"; public static void main(String args[]) { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String command; Class klasses[] = {Student.class, Teacher.class}; HibernateContext.addClasses(klasses);... } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 24 SchoolDemo.java public class SchoolDemo {... public static void main(String args[]) {... do { System.out.print("\nCommand? "); try { command = stdin.readLine(); } catch (java.io.IOException ex) { command = "?"; } String parts[] = command.split(" ");... } while (!command.equalsIgnoreCase("quit")); } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 25 SchoolDemo.java public class SchoolDemo {... public static void main(String args[]) {... do {... if (command.equalsIgnoreCase("create")) { HibernateContext.createSchema(); } else if (command.equalsIgnoreCase("load")) { Student.load(); Teacher.load(); }... } while (!command.equalsIgnoreCase("quit")); } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 26 SchoolDemo.java public class SchoolDemo {... public static void main(String args[]) {... do {... else if (command.equalsIgnoreCase("teachers")) { Teacher.list(); } else if (command.equalsIgnoreCase("students")) { Student.list(); }... } while (!command.equalsIgnoreCase("quit")); } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 27 SchoolDemo.java public class SchoolDemo {... public static void main(String args[]) {... do {... else if (parts[0].equalsIgnoreCase("find") && (parts.length >= 2)) { long id = Long.parseLong(parts[1]); Student student = Student.find(id); if (student != null) { student.print(); } else { System.out.printf("*** No student with id %d\n", id); } }... } while (!command.equalsIgnoreCase("quit")); } } SchoolDemo2
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 28 One-to-One Association Recall: IdLastFirstContact_id 7003RogersTom ThompsonArt LaneJohn FlynnMabel856 Id _address TeacherContact_InfoStudentContact_Info Also:
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak public class ContactInfo { private long id; private String Address; public ContactInfo() {} public ContactInfo(String address) { this. Address = @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; public String get Address() { return Address; } public void set Address(String address) { this. Address = address; } }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 30 Student.java public class Student {... private ContactInfo public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo info) { this.contactInfo = info; }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 31 Student.java public class Student {... public static void load() { Session session = HibernateContext.getSession(); // Load the Student table in a transaction. Transaction tx = session.beginTransaction(); { session.save(new Student("Mary", "Jane", new session.save(new Student("Kim", "Smith", new session.save(new Student("John", "Doe", new session.save(new Student("Tim", "Novak", new session.save(new Student("Leslie", "Klein", new } tx.commit(); session.close(); System.out.println("Student table loaded."); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 32 Student.java public class Student {... private ContactInfo contactInfo;... public void print() { System.out.printf("%d: %s %s (%s)\n", id, firstName, lastName, contactInfo.get Address()); }... }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 33 Lazy Fetching Each Student object has a one-to-one association with a ContactInfo object via its contactInfo field. Whenever our Java program fetches a record from the Student table, Hibernate does not fetch the associated record from the Contact_Info table until our program references any field of the ContactInfo object. This is a Hibernate performance optimization. private ContactInfo public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo info) { this.contactInfo = info; } SchoolDemo3
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 34 Lazy Initialization Exception Hibernate throws the dreaded LazyInitializationException whenever your program attempts to access the field of an object whose corresponding table record has not yet been fetched, often due to lazy fetching. In SchoolDemo3, we attempted to print the value of field Address of a ContactInfo object. The corresponding record had not yet been fetched from the Contact_Info table. Hibernate can fetch table records only within the context of a session.
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 35 Lazy Initialization Exception Recall that after we fetched a matching record from the Student table, we closed the session. Therefore, Hibernate couldn’t fetch the associated Contact_Info record, and we got the exception when we attempted to print the Address field of the ContactInfo object. public static Student find(long id) { Session session = HibernateContext.getSession(); Query query = session.createQuery("from Student where id = :idvar"); query.setLong("idvar", id); Student student = (Student) query.uniqueResult(); session.close(); return student; }
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 36 Lazy Initialization Exception One solution: Use eager fetching. Whenever Hibernate fetches a table record, it immediately fetches records from associated tables. private ContactInfo public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo info) { this.contactInfo = info; } SchoolDemo3
Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 37 Lazy Initialization Exception However, eager fetching is not always a good idea. Don’t defeat Hibernate’s performance optimization, especially if there are many associations and you’re fetching many records! Better: Keep lazy fetching. Attach the Student object to another Hibernate session. Inside of this session, Hibernate can fetch the corresponding Context_Info record to allow you to print ContactInfo fields. public void printInSession() { Session session = HibernateContext.getSession(); session.update(this); print(); session.close(); } Student.java SchoolDemo3