Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1
Hibernate Introduction Opensources –LGPL ( you can use in commercial ) Object / Relational mappings Object-oriented Query Language Transparent persistence Automatic primary key generation Cache architecture High Performance
Hibernate Stacks Hibernate Core Hibernate Annotations Hibernate EntityManager Hibernate Shards Hibernate Validator Hibernate Search
Now.. Make Dev-Env. Download from hibernate.org –hibernate Core –hibernate annotations Build dev IDE ( with JavaSE ) –Eclipse (suggestion) –NetBeans Connect the Database –Hibernate supports lots of DBs. –
Setup your Database Postgresql – MySQL – Oracle MS-SQL Server IBM DB2
Dependency Libs hibernate3.jar ehache.jar c3p0.jar hibernate-annotation.jar slf4j*, log4j.. JDBC- postgresql.jar others..
Create the Test Database Open pgAdminIII and Login it Create new database “testdb” Create a SEQ ‘seq_student’ Create new Table Create table student ( id bigint PRIMARY KEY DEFAULT NEXTVAL('seq_student'), sno character varying(10), name character varying(10), sex character(1), regdate timestamp )
Build a Hello World Connect DB by Hibernate –hibernate.cfg.xml Write a Student Persistence Object –Student.java Write a Student hibernate mapping def. –Student.hbm.xml Call DAO by JUnit for printing “Hello ”+student.getName();
Practice I Try to make a teacher Entity teacher columns –id bigint –name character varying(50) –subject character varying(200)
Annotation Driven Modify configuration for annotation –Mapping to the classes Focus on your Persistence Object
Define public class Student implements Serializable { … }
Mapping simple –To specify a field or property of an entity that is not –TemporalType ( DATE, TIME, TIMESTAMP –Assumes that for a property or field mapped to an enumerated ( hibernate only )
@Column ( name=“columnName”, boolean unique() default false; boolean nullable() default true; boolean insertable() default true; boolean updatable() default true; String columnDefinition() default “”; String table() default “”; int length() default 255; int precision() default 0; // decimal precision int scale() default 0; ) // to generate create-table sql
@Embedded Objects Main public class Student impelements Serializable { ( …. ) Country bornIn; } Embedded Class public class Address implements Serializable {..
No annotations ? Single type Component Serializable Clob or Blob
Composited public class Book public String getBookName() public String getAuthorName() {…} public int getPages() {…} public BookSize getSize() {…} public int getWeight() {…} …. }
public class BookPK implements Serializable { public String getBookName() {..} public String getAuthorName() {..} ….. public boolean equals(Object obj) { … } public int hashCode() {… } }
Practice II Try to make teacher and student into annotation style ! Try to add a course Entity course columns –id bigint –subject character varying(10) –name character varying(50)
Mapping Inheritance –Single Table per Class Hierarchy Strategy –Table per Class Strategy –Joined Subclass annotation
Single Table create table Person ( id bigint, idno character varying(10), name character varying(50), studentcode …, teachercode …, …. ) @Inheritance(strategy=Inheritance public class Person { private long id; private String idno; private String name; public class Student extends Person { private String studentcode; }
Table per Class Strategy create table Person( idno character varying(10), name character varying(50), ) create table Student ( idno character varying(10), name character varying(50), studentcode …, …. ) create table Teacher ( idno character varying(10), name character varying(50), teachercode …, …. nceType.TABLE_PER_CLA SS) public class Person { private String idno; private String name; } public class Student extends Person { private String studentcode; } public class Teacher extends Person { private String teachercode; }
Table per Subclass create table Person( idno character varying(10), name character varying(50), ) create table Student ( studentcode …, …. ) create table Teacher ( teachercode …, …. nceType.JOINED) public class Person { private String idno; private String name; } public class Student extends Person { private String studentcode; } public class Teacher extends Person { private String teachercode; }
No specific table for the entity create table Student ( idno character varying(10), name character varying(50), studentcode …, …. updatetime …. ) create table Teacher ( idno character varying(10), name character varying(50), teachercode …, …. updatetime …. public class Person { private String idno; private String name; private Timestamp updatetime; } public class Student extends Person { private String studentcode; } public class Teacher extends Person { private String teachercode; }
Practice III Try to add a Person Entity Try to use JOINED strategy Person columns –id bigint –idno character varying(10) –name character varying(50)
Entity Relationships Unidirectional one-to-one –ex. Person 1--->1 Heart Bidirectional one-to-one –ex. Person 1 1 Passport Unidirectional one-to-many –ex. Person 1 --->* Phones Bidirectional one-to-many –aka. Bidirectional many-to-one –ex. Person 1 * Childs Unidirectional many-to-one –ex. Person *--->1 Company Unidirectional many-to-many –ex. Person *--->* Address Bidirectional many-to-many –ex. Person * * Orders
Unidirectional public class Person public String getIdno() { return public Heart getHeart() { return heart;} public class Heart public Long getId(); }
Bidirectional public class Person public String getIdno() { return idno; } private public Passport getPassport() { return passport;} public class Passport public Long public Person getOwner(); }
public class Person implements Serializable cascade = {CascadeType.PERSIST, CascadeType.MERGE} public Company getCompany() { return company; public class Company implements Serializable { … }
Collections Java Collection Framework –List –Set –Map Apache Jakarta Commons-Collection –Bag
Unidirectional public class public List getPhones() { return phones; public class Phone { // … no bidir }
Bidirectional public class Person public List getChilds() { return childs; public class Child public Person getParent() { return parent; }
Unidirectional with join public class name=“student”, joinColumns inverseJoinColumns public Set getStudents() { … public class Student { // }
public class Person implements Serializable targetEntity=org.ossf.course.vo.Order.class, cascade={CascadeType.PERSIST, CascadeType.MERGE} name=“Person_Order”, public Collection getOrders() { return orders; }
public class Order implements Serializable ( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = “orders”, targetEntity = org.ossf.course.vo.Person.class ) public Collection getPersons() { return persons; }
Fetching … FetchType.EAGER FetchType.LAZY –Lazy Initialization exception ? –Hibernate.initialize(node); –Hibernate.initialize(node.getChilden());
Cascading ALL PERSIST MERGE REMOVE REFRESH
Practice IV Try to make Teacher one-to-many Students relationship Try to make Courses many-to-many Teachers relationship
Summary Hibernate is easy and the leader of ORM Annotations can let you leave XML-hell We learned how to create an Entity We learned how to use Inheritance We learned how to generate relationship Well, everything should be simple Of course, java is simple and powerful !