Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 157B: Database Management Systems II February 4 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 February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak."— Presentation transcript:

1 CS 157B: Database Management Systems II February 4 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 Referential Integrity  Referential integrity is database-speak for “No dangling pointers.” In other words, a foreign key value should always be a valid reference to a record in the target table (or the key value should be null). _

3 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 3 Maintaining Referential Integrity  Recall our one-to-one table association:  The Teacher table has a foreign-key constraint. Field contact_id should always reference a valid record in the Contact_Info table, or the field should be null. _ IdLastFirstContact_id 7003RogersTom207 7008ThompsonArt190 7012LaneJohn458 7051FlynnMabel856 IdEmail_address 458jlane@sjsu.edu 856mflynn@sjsu.edu 207trogers@sjsu.edu 190athompson@sjsu.edu TeacherContact_Info

4 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 4 Maintaining Referential Integrity IdLastFirstContact_id 7003RogersTom207 7008ThompsonArt190 7012LaneJohn458 7051FlynnMabel856 IdEmail_address 458jlane@sjsu.edu 856mflynn@sjsu.edu 207trogers@sjsu.edu 190athompson@sjsu.edu CREATE TABLE `teacher` ( `Id` int(10) unsigned NOT NULL auto_increment, `Last` varchar(45) NOT NULL, `First` varchar(45) NOT NULL, `contact_id` int(10) unsigned NOT NULL, PRIMARY KEY (`Id`), KEY `FK_teacher_1` (`contact_id`), FOREIGN KEY (`contact_id`) REFERENCES `contact_info` (`id`) ) MySQL TeacherContact_Info

5 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 5 Maintaining Referential Integrity  You cannot insert a new Teacher record whose contact_id value does not match a Contact_Info.id value.  You cannot change a Teacher.contact_id value to a value that does not match a Contact_Info.id value.  You cannot change a Contact_Info.id value to a value that does not match a Teacher.contact_id value.  You cannot delete a Contact_Info record without updating the Teacher table. IdLastFirstContact_id 7003RogersTom207 7008ThompsonArt190 7012LaneJohn458 7051FlynnMabel856 IdEmail_address 458jlane@sjsu.edu 856mflynn@sjsu.edu 207trogers@sjsu.edu 190athompson@sjsu.edu TeacherContact_Info Demo

6 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 6 Maintaining Referential Integrity  Update a Contact_Info.id value  the corresponding Teacher.contact_info value is updated automatically.  Delete a Contact_Info record  the corresponding Teacher record is deleted. What happens to Contact_Info if you delete a Teacher record? CREATE TABLE `teacher` ( `Id` int(10) unsigned NOT NULL auto_increment, `Last` varchar(45) NOT NULL, `First` varchar(45) NOT NULL, `contact_id` int(10) unsigned NOT NULL, PRIMARY KEY (`Id`), KEY `FK_teacher_1` (`contact_id`), FOREIGN KEY (`contact_id`) REFERENCES `contact_info` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) cascade policy Also: ON DELETE SET NULL Demo

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

8 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 8 Hibernate Cascade Types  CascadeType.PERSIST Tell a session to save() a Teacher object, and the corresponding ContactInfo object is saved automatically.  CascadeType.REMOVE Tell a session to delete() a ContactInfo object, and the corresponding Teacher object is deleted automatically.  CascadeType.REFRESH Tell a session to refresh() a Teacher object, and the corresponding ContactInfo object is refreshed automatically.  CascadeType.MERGE Tell a session to merge() a Teacher object, and the corresponding ContactInfo object is refreshed automatically.  CascadeType.ALL Do all of the above. _

9 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 9 Hibernate Reminders  Hibernate accesses the underlying database within the context of a session.  Two common errors: Attempting to access a Java object whose corresponding database record has not yet be fetched, likely due to lazy fetching.  Attach the object to a new session to force Hibernate to fetch the record. Taking a Java object already attached to a session and attempting to attach it to another session.  Did you forget to close the first session? _

10 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 10 One-to-Many / Many-to-One Associations  The Teacher table has a one-to-many association with the Class table.  The Class table has a many-to-one association with the Teacher table. _ IdLastFirst 7003RogersTom 7008ThompsonArt 7012LaneJohn 7051FlynnMabel CodeTeacher_idSubject 9087008Data structures 9267003Java programming 9317051Compilers 9517012Software engineering 9747012Operating systems TeacherClass

11 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 11 Teacher.java @Entity public class Teacher {... private List klasses;... @OneToMany(mappedBy="teacher", targetEntity=Klass.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER) public List getKlasses() { return klasses; } public void setKlasses(List klasses) { this.klasses = klasses; }... }

12 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 12 Klass.java @Entity @Table(name="Class") public class Klass {... private Teacher teacher;... @ManyToOne @JoinColumn(name="teacher_id") public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; }... }

13 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 13 Klass.java public static void load() { Session session = HibernateContext.getSession(); Teacher rogers = Teacher.find("Rogers"); Teacher thompson = Teacher.find("Thompson"); Teacher lane = Teacher.find("Lane"); Teacher flynn = Teacher.find("Flynn"); Klass java = new Klass("Java programming"); java.setTeacher(rogers); Klass ds = new Klass("Data structures"); ds.setTeacher(thompson); Klass se = new Klass("Software engineering"); se.setTeacher(lane); Klass os = new Klass("Operating systems"); os.setTeacher(lane); Klass compilers = new Klass("Compilers"); compilers.setTeacher(flynn);... } Find each teacher. Create classes and assign teachers to them.

14 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 14 Klass.java public static void load() {... Transaction tx = session.beginTransaction(); { session.save(java); session.save(ds); session.save(se); session.save(os); session.save(compilers); } tx.commit(); session.close(); System.out.println("Class table loaded."); } Persist the objects. SchoolDemo4

15 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 15 Many-to-Many Association IdLastFirst 1001DoeJohn 1005NovakTim 1009KleinLeslie 1014JaneMary 1021SmithKim CodeTeacher_idSubject 9087008Data structures 9267003Java programming 9317051Compilers 9517012Software engineering 9747012Operating systems Student_idClass_code 1001926 1001951 1001908 1005974 1005908 1014931 1021926 1021974 1021931 Student Class Student_Class Class Student Student-Class

16 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 16 Student.java @Entity public class Student {... private List klasses = new ArrayList ();... @ManyToMany @JoinTable(name="Student_Class", joinColumns={@JoinColumn(name="student_id")}, inverseJoinColumns={@JoinColumn(name="class_code")}) public List getKlasses() { return klasses; } public void setKlasses(List klasses) { this.klasses = klasses; }... } Hibernate will automatically create and populate the Student_Class join table. Student_idClass_code 1001926 1001951... Student_Class

17 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 17 Klass.java @Entity @Table(name="Class") public class Klass {... private List students = new ArrayList ();... @ManyToMany @JoinTable(name="Student_Class", joinColumns={@JoinColumn(name="class_code")}, inverseJoinColumns={@JoinColumn(name="student_id")}) public List getStudents() { return students; } public void setStudents(List students) { this.students = students; }... } Student_idClass_code 1001926 1001951... Student_Class

18 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 18 Klass.java public static void load() {... Student doe = Student.find("Doe"); Student jane = Student.find("Jane"); Student novak = Student.find("Novak"); Student smith = Student.find("Smith"); java.getStudents().add(smith); java.getStudents().add(doe); ds.getStudents().add(doe); ds.getStudents().add(novak); se.getStudents().add(doe); os.getStudents().add(novak); os.getStudents().add(smith); compilers.getStudents().add(smith); compilers.getStudents().add(jane);... } SchoolDemo5 Find each student. Assign students to classes.

19 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 19 Hibernate Oral Presentations  Next Monday, February 11.  Four teams volunteer to each give a quick 15-minute presentation and demo of its project. What data did you use. Logical design of your database. How you used Hibernate. Demo of your application. Q & A  First four teams to send me an email. Points can be added to your project score.

20 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 20 Overcoming the Paradigm Mismatch  What is a major feature of the object-oriented data model that is not in the relational data model? inheritance  How can we model an inheritance hierarchy with relational database tables? Hibernate uses three strategies:  one table per class or subclass of the inheritance hierarchy  joined tables across the inheritance hierarchy  a single table per inheritance hierarchy _

21 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 21 Example Inheritance Hierarchy firstName : String lastName : String Person sjsuId : String SjsuPerson gpa : float SjsuStudent

22 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 22 Person.java @Entity public class Person { private long id; private String firstName; private String lastName; public Person() {} @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; }... } firstName : String lastName : String Person sjsuId : String SjsuPerson gpa : float SjsuStudent

23 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 23 SjsuPerson.java @Entity public class SjsuPerson extends Person { private String sjsuId; public SjsuPerson() {} @Column(name="sjsu_id") public String getSjsuId() { return sjsuId; } public void setSjsuId(String id) { this.sjsuId = id; } } firstName : String lastName : String Person sjsuId : String SjsuPerson gpa : float SjsuStudent

24 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 24 SjsuStudent.java @Entity public class SjsuStudent extends SjsuPerson { private float gpa; public SjsuStudent() {} @Column(name="gpa") public float getGpa() { return gpa; } public void setGpa(float gpa) { this.gpa = gpa; } } firstName : String lastName : String Person sjsuId : String SjsuPerson gpa : float SjsuStudent

25 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 25 InheritanceDemo.java public class InheritanceDemo { public static void main(String[] args) { Class klasses[] = {Person.class, SjsuPerson.class, SjsuStudent.class}; HibernateContext.addClasses(klasses); HibernateContext.createSchema();... } }

26 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 26 InheritanceDemo.java public class InheritanceDemo { public static void main(String[] args) {... Person person = new Person(); person.setFirstName("John"); person.setLastName("Doe"); SjsuPerson sjsuPerson = new SjsuPerson(); sjsuPerson.setFirstName("Mary"); sjsuPerson.setLastName("Jane"); sjsuPerson.setSjsuId("001234567"); SjsuStudent sjsuStudent = new SjsuStudent(); sjsuStudent.setFirstName("Leslie"); sjsuStudent.setLastName("Smith"); sjsuStudent.setSjsuId("007654321"); sjsuStudent.setGpa(3.71f);... } } firstName : String lastName : String Person sjsuId : String SjsuPerson gpa : float SjsuStudent

27 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 27 InheritanceDemo.java public class InheritanceDemo { public static void main(String[] args) {... Session session = HibernateContext.getSession(); Transaction tx = session.beginTransaction(); { session.save(person); session.save(sjsuPerson); session.save(sjsuStudent); } tx.commit(); session.close(); } }

28 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 28 Inheritance Strategy: One Table per Class @Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public class Person { private long id; private String firstName; private String lastName; public Person() {} @Id @GeneratedValue(strategy = GenerationType.TABLE) @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; }... } InheritanceDemo1 Top of the inheritance hierarchy

29 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 29 Inheritance Strategy: One Table per Class  Disadvantages of one table per class strategy: Duplicated fields in the subclass tables. Changes to a superclass field value will require multiple table updates.

30 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 30 Inheritance Strategy: Joined Tables @Entity @Inheritance(strategy=InheritanceType.JOINED) public class Person { private long id; private String firstName; private String lastName; public Person() {} @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; }... } InheritanceDemo2

31 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 31 Inheritance Strategy: Joined Tables  Disadvantages of the joined table strategy: Table joins are inefficient. Poor performance with deep class hierarchies.

32 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 32 Inheritance Strategy: Single Table @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) public class Person { private long id; private String firstName; private String lastName; public Person() {} @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; }... } InheritanceDemo3

33 Department of Computer Science Spring 2013: January 30 CS 157B: Database Management Systems II © R. Mak 33 Project #1  Now you should be able to use Hibernate to: Map Java classes to relational database tables. Specify one-to-one, one-to-many, and many-to-many associations, and handle class hierarchies. Create and populate your database tables.  Use sample datasets downloaded from the Internet, or make up your own data.  You should not need to download and install Hibernate. NetBeans: Hibernate is built in. Eclipse: Use my zipped jar files. Command line: Put the jar files in your class path.  Why are you using the command line instead of an IDE? _


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

Similar presentations


Ads by Google