Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.

Similar presentations


Presentation on theme: "Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1."— Presentation transcript:

1 Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan http://www.softleader.com.tw Java Annotation Lesson 1

2 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

3 Hibernate Stacks Hibernate Core Hibernate Annotations Hibernate EntityManager Hibernate Shards Hibernate Validator Hibernate Search

4 Now.. Make Dev-Env. Download from hibernate.org –hibernate Core –hibernate annotations Build dev IDE ( with JavaSE 5.0 + ) –Eclipse (suggestion) –NetBeans Connect the Database –Hibernate supports lots of DBs. –http://squirrel-sql.sourceforge.net

5 Setup your Database Postgresql –http://www.postgresql.org/http://www.postgresql.org/ MySQL –http://www.mysql.com/http://www.mysql.com/ Oracle MS-SQL Server IBM DB2

6 Dependency Libs hibernate3.jar ehache.jar c3p0.jar hibernate-annotation.jar slf4j*, log4j.. JDBC- postgresql.jar others..

7 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 )

8 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();

9 Practice I Try to make a teacher Entity teacher columns –id bigint –name character varying(50) –subject character varying(200)

10 Annotation Driven Modify configuration for annotation –Mapping to the classes Focus on your Persistence Object –@Entity –@Table –@Id –@Column

11 Define the table @Entity @Table(name=“student”) public class Student implements Serializable { … }

12 Mapping simple properties @Transient –To specify a field or property of an entity that is not persistent @Basic (default) @Temporal –TemporalType ( DATE, TIME, TIMESTAMP ) @Enumerated –Assumes that for a property or field mapped to an enumerated constant @CollectionOfElements ( hibernate only )

13 @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

14 @Embedded Objects Main Class using @Embedded @Entity public class Student impelements Serializable { Address homeAddress; @Embedded @AttributeOverrides ( …. ) Country bornIn; } Embedded Class with @ Embeddable @Embeddable public class Address implements Serializable {..

15 No annotations ? Single type –@Basic Component –@Embeddable Serializable –@Basic Clob or Blob –@Lob

16 Composited Primary Key @Entity @IdClass(BookPK.class) public class Book { @Id public String getBookName() {…} @Id public String getAuthorName() {…} public int getPages() {…} public BookSize getSize() {…} public int getWeight() {…} …. }

17 PKClass with @Embeddable @Embeddable public class BookPK implements Serializable { public String getBookName() {..} public String getAuthorName() {..} ….. public boolean equals(Object obj) { … } public int hashCode() {… } }

18 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)

19 Mapping Inheritance –Single Table per Class Hierarchy Strategy –Table per Class Strategy –Joined Subclass Strategy @Inheritance annotation

20 Single Table create table Person ( id bigint, idno character varying(10), name character varying(50), studentcode …, teachercode …, …. ) To use @DiscriminatorColumn, @DiscriminatorValue @Inheritance(strategy=Inheritance Type.SINGLE_TABLE) @DiscriminatorValue(“PERSON”) public class Person { private long id; private String idno; private String name; } @DiscrimatorValue(“STUDENT”) public class Student extends Person { private String studentcode; }

21 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 …, …. ) @Inheritance(strategy=Inherita 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; }

22 Table per Subclass create table Person( idno character varying(10), name character varying(50), ) create table Student ( studentcode …, …. ) create table Teacher ( teachercode …, …. ) @Inheritance(strategy=Inherita 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; }

23 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 …. ) @MappedSuperclass 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; }

24 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)

25 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

26 Unidirectional One-to-One @Entity public class Person { @Id public String getIdno() { return idno; } @OneToOne(cascade=CascadeType.ALL) @PrimaryKeyJoinColumn public Heart getHeart() { return heart;} } @Entity public class Heart { @Id public Long getId(); }

27 Bidirectional One-to-One @Entity public class Person { @Id public String getIdno() { return idno; } private Passport passport; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name=“passport_id”) public Passport getPassport() { return passport;} } @Entity public class Passport { @Id public Long getId(); @OneToOne(mappedBy=“passport”) public Person getOwner(); }

28 Many-to-One @Entity public class Person implements Serializable { @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} ) @JoinColumn(name=“company_id”) public Company getCompany() { return company; } @Entity public class Company implements Serializable { … }

29 Collections Java Collection Framework –List –Set –Map Apache Jakarta Commons-Collection –Bag

30 Unidirectional One-to-Many @Entity public class Person { @OneToMany(mappedBy=“person”) @OrderBy(“name”) public List getPhones() { return phones; } @Entity public class Phone { // … no bidir }

31 Bidirectional One-to-Many @Entity public class Person { @OneToMany(mappedBy=“parent”) public List getChilds() { return childs; } @Entity public class Child { @ManyToOne public Person getParent() { return parent; }

32 Unidirectional with join table @Entity public class Teacher { @OneToMany @JoinTable( name=“student”, joinColumns = @JoinColumn(name=“teacher_id”), inverseJoinColumns = @JoinColumn(name=“student_id”) public Set getStudents() { … } @Entity public class Student { // }

33 Many-to-Many @Entity public class Person implements Serializable { @ManyToMany( targetEntity=org.ossf.course.vo.Order.class, cascade={CascadeType.PERSIST, CascadeType.MERGE} ) @JoinTable( name=“Person_Order”, joinColumns=@JoinColumn(name=“person_id”), inverseJoinColumns=@JoinColumn(name=“order_id”)) public Collection getOrders() { return orders; }

34 Many-to-Many @Entity public class Order implements Serializable { @ManyToMany ( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = “orders”, targetEntity = org.ossf.course.vo.Person.class ) public Collection getPersons() { return persons; }

35 Fetching … FetchType.EAGER FetchType.LAZY –Lazy Initialization exception ? –Hibernate.initialize(node); –Hibernate.initialize(node.getChilden());

36 Cascading ALL PERSIST MERGE REMOVE REFRESH

37 Practice IV Try to make Teacher one-to-many Students relationship Try to make Courses many-to-many Teachers relationship

38 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 !


Download ppt "Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1."

Similar presentations


Ads by Google