Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.

Similar presentations


Presentation on theme: "CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak."— Presentation transcript:

1 CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak

2 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 email address of each team member If necessary, I will arbitrarily form teams by randomly assigning students.

3 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!

4 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: http://www.cs.sjsu.edu/~mak/CS157B/projects/ 1/Hibernate.pdf http://www.cs.sjsu.edu/~mak/CS157B/projects/ 1/Hibernate.pdf

5 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 5 Student.java @Entity 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; }... }

6 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 6 Student.java @Entity public class Student {... @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name="first_name") public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } @Column(name="last_name") public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; }... }

7 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();... }

8 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

9 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.

10 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(); } }... }

11 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(); } }... }

12 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. * @return a session. */ public static Session getSession() { setFactory(); return factory.openSession(); }... }

13 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); }... }

14 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. * @param klass the class object. */ public static void addClass(Class klass) { setConfiguration(); config.addAnnotatedClass(klass); }... }

15 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. * @param klasses the list of class objects. */ public static void addClasses(Class klasses[]) { for (Class klass : klasses) { addClass(klass); } } }

16 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 16 Student.java @Entity 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)

17 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 17 Student.java @Entity 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; }... }

18 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 18 Teacher.java  Similar to Student.java @Entity 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; }... }

19 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 19 Teacher.java @Entity public class Teacher {... @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name="first_name") public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } @Column(name="last_name") public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; }... }

20 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 20 Teacher.java @Entity 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."); }... }

21 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 21 Teacher.java @Entity 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(); } }

22 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 22 Teacher.java @Entity public class Teacher {... /** * Print teacher attributes. */ public void print() { System.out.printf("%d: %s %s\n", id, firstName, lastName); }... }

23 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);... } }

24 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")); } }

25 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")); } }

26 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")); } }

27 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

28 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 28 One-to-One Association  Recall: IdLastFirstContact_id 7003RogersTom207 7008ThompsonArt190 7012LaneJohn458 7051FlynnMabel856 IdEmail_address 458jlane@sjsu.edu 856mflynn@sjsu.edu 207trogers@sjsu.edu 190athompson@sjsu.edu TeacherContact_InfoStudentContact_Info  Also:

29 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 29 ContactInfo.java @Entity @Table(name="Contact_Info") public class ContactInfo { private long id; private String emailAddress; public ContactInfo() {} public ContactInfo(String address) { this.emailAddress = address; } @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name="email_address") public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String address) { this.emailAddress = address; } }

30 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 30 Student.java (One-to-One) @Entity public class Student {... private ContactInfo contactInfo; @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY) @JoinColumn(name="contact_id") public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo info) { this.contactInfo = info; }... }

31 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 31 Student.java (One-to-One) @Entity 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 ContactInfo("mjane@sjsu.edu"))); session.save(new Student("Kim", "Smith", new ContactInfo("ksmith@sjsu.edu"))); session.save(new Student("John", "Doe", new ContactInfo("jdoe@sjsu.edu"))); session.save(new Student("Tim", "Novak", new ContactInfo("tnovak@sjsu.edu"))); session.save(new Student("Leslie", "Klein", new ContactInfo("lklein@sjsu.edu"))); } tx.commit(); session.close(); System.out.println("Student table loaded."); }... }

32 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 32 Student.java (One-to-One) @Entity public class Student {... private ContactInfo contactInfo;... public void print() { System.out.printf("%d: %s %s (%s)\n", id, firstName, lastName, contactInfo.getEmailAddress()); }... }

33 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 contactInfo;... @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY) @JoinColumn(name="contact_id") public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo info) { this.contactInfo = info; } SchoolDemo3

34 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 emailAddress 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.

35 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 emailAddress 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; }

36 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 contactInfo;... @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name="contact_id") public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo info) { this.contactInfo = info; } SchoolDemo3

37 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


Download ppt "CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak."

Similar presentations


Ads by Google