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

Slides:



Advertisements
Similar presentations
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Advertisements

CS 185C/286: The History of Computing October 31 Class Meeting Department of Computer Science San Jose State University Fall 2011 Instructor: Ron Mak
Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
1 Repetition structures [cont’d] Overview l Nested Loops l Sentinel-Controlled loop l Avoiding Number Format exception.
CS 235: User Interface Design January 22 Class Meeting
Object Persistence using Hibernate
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
CS 160: Software Engineering November 10 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CS 157B: Database Management Systems II February 27 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron.
Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.
CS 157B: Database Management Systems II May 8 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak
CS 157B: Database Management Systems II April 29 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Robert Greiner CSE7330 Southern Methodist University Getting Things Done with Hibernate.
CS 46B: Introduction to Data Structures June 25 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CS1101: Programming Methodology Recitation 3 – Control Structures.
CS 174: Web Programming September 23 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Object/Relational Mapping with Hibernate Practical ORM.
CS 174: Web Programming September 21 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 157B: Database Management Systems II February 6 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 160: Software Engineering November 5 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 235: User Interface Design September 22 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CS 160: Software Engineering October 6 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
CS 174: Web Programming August 31 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 151: Object-Oriented Design September 5 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak
CS 157B: Database Management Systems II April 3 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
CS 160: Software Engineering October 22 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Hibernate Thuy, Le Huu Pentalog HAN. What is Hibernate? Hibernate is a free, open source Java package that makes it easy to work with relational databases.
Arrays and Objects CIS 362. The familiar Employee class.
CS 174: Web Programming October 14 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 152: Programming Language Paradigms March 19 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
v110912Java Persistence: EntityManager2 Overview Earlier versions of EJB Specification defined the persistence layer –javax.ejb.EntityBean Java EE 5 moved.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 174: Web Programming November 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 146: Data Structures and Algorithms June 11 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CS 157B: Database Management Systems II April 22 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Builder Pattern. What’s Builder: TO find a solution to the telescoping constructor Problem: Too many parameters Solution: To get an abstract object, a.
CS 46B: Introduction to Data Structures July 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
CS 154 Formal Languages and Computability March 8 Class Meeting Department of Computer Science San Jose State University Spring 2016 Instructor: Ron Mak.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
CS 160 and CMPE/SE 131 Software Engineering March 10 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
CS 160 and CMPE/SE 131 Software Engineering March 15 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
CS 157B: Database Management Systems II January 23 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Современные технологии баз данных Лекция 7. Объектно-реляционное отображение (ORM) Технология отображения объектов какого- либо объектно-ориентированного.
Lecture 6 Object Oriented Programming Using Java
CS 153: Concepts of Compiler Design November 28 Class Meeting
CS 153: Concepts of Compiler Design November 30 Class Meeting
CMPE 152: Compiler Design January 25 Class Meeting
Java Data Persistence Using Hibernate
Lecture 3: The J# Language
CMPE 152: Compiler Design August 21 Class Meeting
CMPE 152: Compiler Design January 24 Class Meeting
CMPE/SE 131 Software Engineering March 9 Class Meeting
CS 151: Object-Oriented Design October 8 Class Meeting
CS 240 – Advanced Programming Concepts
Presentation transcript:

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