Date post: | 29-Dec-2015 |
Category: |
Documents |
Upload: | ruth-taylor |
View: | 213 times |
Download: | 0 times |
CS 157B: Database Management Systems IIJanuary 30 Class Meeting
Department of Computer ScienceSan Jose State University
Spring 2013Instructor: Ron Mak
www.cs.sjsu.edu/~mak
Department of Computer ScienceSpring 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.
Department of Computer ScienceSpring 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 ScienceSpring 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
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
5
Student.java
@Entitypublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
6
Student.java
@Entitypublic 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; } ...}
Department of Computer ScienceSpring 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
8
Student.javapublic 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 ScienceSpring 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
10
HibernateContext.javaimport 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 ScienceSpring 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 ScienceSpring 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(); } ...}
Department of Computer ScienceSpring 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 ScienceSpring 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); } ...}
Department of Computer ScienceSpring 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); } }}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
16
Student.java@Entitypublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
17
Student.java@Entitypublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
18
Teacher.java
Similar to Student.java
@Entitypublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
19
Teacher.java
@Entitypublic 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; } ...}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
20
Teacher.java@Entitypublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
21
Teacher.java
@Entitypublic 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<Teacher>) query.list()) { teacher.print(); } session.close(); }}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
22
Teacher.java
@Entitypublic class Teacher { ... /** * Print teacher attributes. */ public void print() { System.out.printf("%d: %s %s\n", id, firstName, lastName); } ...}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
23
SchoolDemo.javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;
public class SchoolDemo { private static final String HELP_MESSAGE = "*** Commands: create, load, find <n>, 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
24
SchoolDemo.javapublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
25
SchoolDemo.javapublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
26
SchoolDemo.javapublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
27
SchoolDemo.javapublic 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 ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
28
One-to-One Association
Recall:
Id Last First Contact_id
7003 Rogers Tom 207
7008 Thompson Art 190
7012 Lane John 458
7051 Flynn Mabel 856
Id Email_address
Teacher Contact_Info
Student Contact_Info
Also:
Department of Computer ScienceSpring 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; }}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
30
Student.java (One-to-One)
@Entitypublic 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; }
...}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
31
Student.java (One-to-One)
@Entitypublic 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("[email protected]"))); session.save(new Student("Kim", "Smith", new ContactInfo("[email protected]"))); session.save(new Student("John", "Doe", new ContactInfo("[email protected]"))); session.save(new Student("Tim", "Novak", new ContactInfo("[email protected]"))); session.save(new Student("Leslie", "Klein", new ContactInfo("[email protected]"))); } tx.commit(); session.close();
System.out.println("Student table loaded."); }
...}
Department of Computer ScienceSpring 2013: January 30
CS 157B: Database Management Systems II© R. Mak
32
Student.java (One-to-One)@Entitypublic class Student { ...
private ContactInfo contactInfo; ...
public void print() { System.out.printf("%d: %s %s (%s)\n", id, firstName, lastName, contactInfo.getEmailAddress()); }
...}
Department of Computer ScienceSpring 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
Department of Computer ScienceSpring 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.
Department of Computer ScienceSpring 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;}
Department of Computer ScienceSpring 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
Department of Computer ScienceSpring 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