CS 157B: Database Management Systems IIFebruary 6 Class Meeting
Department of Computer ScienceSan Jose State University
Spring 2013Instructor: Ron Mak
www.cs.sjsu.edu/~mak
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
2
Hibernate Oral Presentations
Next Monday, February 11. Four teams volunteer to each give a quick
15-minute presentation and demoof its project. What data did you use. Logical design of your database. How you used Hibernate. Demo of your application. Q & A
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
3
Hibernate Oral Presentations
Monday, February 11
Section 1 Team Cosmos Team VoidStarStar
Section 2 Team Xeon
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
4
Internet Connection Required
Recall the configuration file hibernate.cfg.xml:
The URL is for the Document Type Definition (DTD). Hibernate can’t parse the configuration file without it. Therefore, you need a working Internet connection
to execute a Hibernate program!
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory> ... </session-factory></hibernate-configuration>
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
5
No Internet Connection Required
Solution: Download that DTD and put it somewhere local,
such as in your source folder. Modify your hibernate.cfg.xml accordingly:
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "file:///G:/NetBeansProjects/SchoolDemo5/src/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory> ... </session-factory></hibernate-configuration>
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
6
Queries Without SQL
... or anything that resembles SQL.
Hibernate offers an object-oriented way to formulate and execute database queries.
Criteria API Build nested, structured query expressions in Java. Compile-time syntax checking.
Unlike embedded SQL.
Like Hibernate itself, it isn’t perfect.
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
7
Get a List of Objects of a Class
Sort them:
Session session = HibernateContext.getSession();Criteria criteria = session.createCriteria(Student.class);
List<Student> students = (List<Student>) criteria.list();
criteria.addOrder(Order.asc("lastName"));List<Student> students = criteria.list();
Paginate:
Get only the first 5 objects.
criteria.setFirstResult(0);criteria.setMaxResults(5);List<Student> students = (List<Student>) criteria.list();
Also:Order.desc()
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
8
Query by Example
Query by Example (QBE) is a simple query technique. Create a prototype object. Set one or more of the prototype object’s field values. Use the prototype object to make an example object. Use the example object in a query to fetch all the objects
whose field values match those of the example.
Student prototype = new Student();prototype.setLastName("Smith");Example example = Example.create(prototype); Session session = HibernateContext.getSession();Criteria criteria = session.createCriteria(Student.class);criteria.add(example);
Student student = (Student) criteria.uniqueResult();
QBE doesn’t seem to workwith the primary key field.
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
9
Query by Example
Ignore zero-valued fields when matching:
Example example = Example.create( ... );example.excludeZeroes();
Don’t ignore null fields. The default is to ignore null fields when matching. Also enables matching on zero-valued fields.
Example example = Example.create( ... );example.excludeNone();
Ignore a particular field:
Example example = Example.create( ... );example.excludeProperty("firstName");
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
10
Query by Example
Fuzzy matches:
Get all students whose email addresses end in .com
MatchMode ANYWHERE START END EXACT
Student prototype = new Student();prototype.setEmailAddress(".com");Example example = Example.create(prototype);example.enableLike(MatchMode.END); Session session = HibernateContext.getSession();Criteria criteria = session.createCriteria(Student.class);criteria.add(example);
List<Student> students = (Student) criteria.list();
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
11
Restrictions
Query by example has some obvious limitations. What about the query “fetch all students with GPA > 3.0”?
Use the Criteria API’s Restrictions class. This class has many static methods.
See:
Session session = HibernateContext.getSession();Criteria criteria = session.createCriteria(Student.class);criteria.add(Restrictions.gt("gpa", 3.0f));
List<Student> smarties = (List<Student>) criteria.list();
http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/criterion/Restrictions.html
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
12
Restrictions
You can “and” together multiple restrictions:Criterion crit1 = Restrictions.gt("gpa", 3.0f);Criterion crit2 = Restrictions.le("gpa", 3.5f);Criterion crit3 = Restrictions.isNotNull("emailAddress");
Student prototype = new Student();prototype.setEmailAddress(".com");
Example example = Example.create(prototype);example.enableLike(MatchMode.END);example.ignoreCase();
Session session = HibernateContext.getSession();Criteria criteria = session.createCriteria(Student.class);criteria.add(crit1);criteria.add(crit3);criteria.add(crit3);criteria.add(example);
List<Student> students = (List<Student>) criteria.list();
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
13
Restrictions
You can also “or” together multiple restrictions. Fetch all students whose GPA is less that 3.0
or greater than 3.5
Criterion crit1 = Restrictions.lt("gpa", 3.0f);Criterion crit2 = Restrictions.gt("gpa", 3.5f);Disjunction disjunction = Restrictions.disjunction();disjunction.add(crit1);disjunction.add(crit2);
Session session = HibernateContext.getSession();Criteria criteria = session.createCriteria(Student.class);criteria.add(disjunction);
List<Student> students = (List<Student>) criteria.list();
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
14
Criteria and Associations
What classes are taught by John Lane? Sorted by subject.
“Chain” criteria across associated objects. Use the reference fields.
Id Last First
7003 Rogers Tom
7008 Thompson Art
7012 Lane John
7051 Flynn Mabel
Code Teacher_id Subject
908 7008 Data structures
926 7003 Java programming
931 7051 Compilers
951 7012 Software engineering
974 7012 Operating systems
Teacher Class
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
15
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; } ...}
What classes are taught by John Lane?
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
16
Criteria and Associations
Id Last First
7003 Rogers Tom
7008 Thompson Art
7012 Lane John
7051 Flynn Mabel
Code Teacher_id Subject
908 7008 Data structures
926 7003 Java programming
931 7051 Compilers
951 7012 Software engineering
974 7012 Operating systems
Teacher Class
Session session = HibernateContext.getSession();Criteria classCriteria = session.createCriteria(Klass.class);Criteria teacherCriteria = classCriteria.createCriteria("teacher");
teacherCriteria.add(Restrictions.eq("firstName", "John")) .add(Restrictions.eq("lastName", "Lane"));
classCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);classCriteria.addOrder(Order.asc("subject"));
List<Klass> klasses = (List<Klass>) classCriteria.list();
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
17
Student.java
@Entitypublic class Student { ... private List<Klass> klasses = new ArrayList<Klass>(); ... @ManyToMany @JoinTable(name="Student_Class", joinColumns={@JoinColumn(name="student_id")}, inverseJoinColumns={@JoinColumn(name="class_code")}) public List<Klass> getKlasses() { return klasses; } public void setKlasses(List<Klass> klasses) { this.klasses = klasses; } ...}
Who are the students taught by John Lane?
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
18
Criteria and Associations
Who are the students taught by John Lane?
Session session = HibernateContext.getSession();Criteria studentCriteria = session.createCriteria(Student.class);Criteria classCriteria = studentCriteria.createCriteria("klasses");Criteria teacherCriteria = classCriteria.createCriteria("teacher");
teacherCriteria.add(Restrictions.eq("firstName", "John")) .add(Restrictions.eq("lastName", "Lane"));
studentCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);studentCriteria.addOrder(Order.asc("lastName")); List<Student> students = (List<Student>) studentCriteria.list();
SchoolDemo6
Why is this line necessary?
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
19
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.
Do queries using the Criteria API._
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
20
Hibernate Query Language (HQL)
Looks like SQL. However, queries are based on Java classes
and their fields, not database tables. Insulate your Java code from the database.
Value injection with named parameters. Example:public static Teacher find(String lastName){ Session session = HibernateContext.getSession(); Query query = session.createQuery("from Teacher where lastName = :name"); query.setString("name", lastName); Teacher teacher = (Teacher) query.uniqueResult(); session.close(); return teacher;}
Department of Computer ScienceSpring 2013: February 6
CS 157B: Database Management Systems II© R. Mak
21
Native SQL
As a last resort, Hibernate allows native SQL. Example:
The result will be an array of field values. Similar to a JDBC result set.
Session session = HibernateContext.getSession();SQLQuery query = session.createSQLQuery( "SELECT * FROM Teacher WHERE last_name = '" + lastName + "'"); Object result = query.uniqueResult();