Hibernate Class Notes

August 7, 2017 | Author: SardarRaj | Category: Computing Platforms, Software Engineering, Data Management, Computer Data, Technology
Share Embed Donate


Short Description

lecture notes of hibernate framework...

Description

1. Saving Without Hibernate -> using plain DAO. a. JDBC Database configuration b. Transfer Object - Employee c. Database Design d. DAO methods to save / retrieve the Object using SQLs. Object Relational Mapping, Java Persistence API 2. With Hibernate a. b. c. d. e.

JDBC Database configuration - Hibernate Configuration. Transfer Object - Employee hibernate mapping file or annotations. database design is not needed - hibernate will create the tables. DAO using hibernate API no sqls needed.

3. Explain the hibernate.cfg.xml file. -> explain all the relevant entries. 4. Write the Employee Object 5. Write the Employee.hbm.xml file -> with out the ID generator and explain all the fields 5.1 . Annotations are used to store the metadata so that some other tool can use that info and act on. 6. Use the annotations. @Entity, @Id @Entity(name="EMP_INFO") -> uses the table name provided. we can use @Table a s well. 7. @GeneratedValue -> Uses Sequence -> Explain the basics of the sequence in Or acle. CREATE SEQUENCE "TEST_SEQUENCE" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 21 CACHE 20 NOORDER NOCYCLE ; select test_sequence.nextVal from dual; A. @GeneratedValue(strategy=GenerationType.AUTO) -> hibernate will decid e what to use based on the underlying database. B. @GeneratedValue(strategy=GenerationType.IDENTITY) -> not for oracle > but it uses a unique value with in the table. C. @GeneratedValue(strategy=GenerationType.SEQUENCE) -> hibernate use th is if we use AUTO for oracle database. -> hibernate creates a sequence "hibernate_sequence" and uses this. but if we want to use our own sequence generator then we need to use SequenceGenera tor and this can be used with auto or seq for oracle. @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "EMP_SEQ" ) @SequenceGenerator(name="EMP_SEQ" , sequenceName="test_sequence") D. @GeneratedValue(strategy=GenerationType.TABLE) -> hibernate will crea te a table with two columns, first column to store the table name and the second column to store the value. similar to sequence we can create our own table and tell hibernate to use that table.

8. Use the annotations @Column(name="EMP_NAME", nullable=false, unique = true, l ength = 200) 9. Use the annotation @Type to specify the column type -> better no use use as h ibernate is smart enough to use the appropriate type. 10. @Transient -> if you do not want a field to go to database, we can annotate it with this. 11. @Temporal @Temporal(TemporalType.DATE) -> If there is a Date field, it stor es the timestamp. but if we just want the Date then use this annotation. 12. LOB -> if it is large string. Large Object. --------------13. @Embedded and @Embeddable -> Employee (Address) -> To override the attributes of the Embedded Object. @AttributeOverrides{ @AttributeOverride(name="city",column=@Column(name="HOME_STREET_ NAME")) // override the default column names from the embedded object @AttributeOverride(name="zipcode",column=@Column(name="HOME_CITY _NAME")) } 14. @EmbeddedId = @Embedded + @Id -> if the primary key is more than one field t hen we need to create an object with those fields then include that in the main object and annotate it with @EmbeddedId. the object itself should be annotated w ith the @Embeddable. 15. saving and reading a basic object Student student = session.get(Student.class,1); (class name, primary key) Collection: 16. @ElementCollection -> creates a sub table student_details_addresses with a f oreign key as the student.id 17. @ElementCollection with @JoinTable ( name="STUDENT_ADDRESS", //-> now it uses the STUDENT_ADDRESS ins tead of default table name. joinColumns=@JoinColumn(name="STUDENT_ID") //-> foreign key colu mn name ) Specifying the primary key for the Child Table 18. @GenericGenerator(name="hilo-gen", strategy="hilo") @CollectionId(columns = {@Column(name="ADDRESS_ID")} , generator = "hilo -gen", type = @Type(type="long")) -> if we need to add a new primary key column in the join table then we can use @CollectionId. along with the @GenericGenerato r, @ElementCollection and the @JoinTable. 19. @ElementCollection(fetch=FetchType.LAZY) (EAGER -? lazy is default) -->> Proxy Class , Eager and Lazy fetch. when we read an object that has a collection (like address), hibernate creates a proxy class which is a sub class of the original class and implements all the m ethods. but for the collection getter methods, it adds additional code to fetch the data before calling the super class get.

Database 1. One-to-one relationships 2. One-to-many relationships 3. Many-to-many relationships

20. @OneToOne @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="COLLEGE_ADDRESS_ID") 21. @OneToMany USER, VEHICLES A. (Separate Table) creates user_vehicle (user_id, vehicle_id) table to store t he one to many relations @JoinTable(name="USERVEHICLES", joinColumns=@JoinColumn(name="userid"), inverseJ oinColumns=@JoinColumn(name="vehicleid")) -> creates USERVEHICLES(userid,vehicle id) --NOTE -> need to add the seesion.close() in finally block so that it is closed in case of exceptions as well. B. (Add a new Column to the table on the many side) @OneToMany(mappedBy="user") -> Creates a new column in the Vehicles Table to store the UserId. I. Need to add a new field in the Vehicle class to store the User. and annota te it with @ManyToOne a. add a @NotFound(action=NotFoundAction.IGNORE) to ignore the error i f the Vehicle exists with out the User. II. Need to specify the mappedBy="user" in the User class. 22. @ManyToMany SYUDENT, COURSES A. Create 2 separate tables STUDENT_COURCES and COURSES_STUDENT and populate th e relationships. -> both the tables has the same set of data, so its redundant o nly one table is enough. B. Similar to One-To-Many but both the classes holds a Collection of the other class. C. if we use (mappedBy="courses") in the COURSES class, the COURSES_STUDENT tab le will not be created. Inheritance 23. @Inheritance(strategy=InheritanceType.SINGLE_TABLE) --> Single Table Per Inheritance Strategy -> single table strategy uses the pa rent class(Animal) and adds all the extra columns from all the sub classes and a dds an extra column called DTYPE (discriminator) that stores the Class Name. val ues for the unrelated fields will be null. @DiscriminatorColumn( name="ANIMAL_TYPE", --> use this column instead of DTYPE. discriminatorType=DiscriminatorType.STRING ) @DiscriminatorValue("AAA") -> Use this value for the Discriminator instead of th

e class name. 24. @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) --> Table Per Class -> creates table per each class with all the inherited prope rties. 25. @Inheritance(strategy=InheritanceType.JOINED) --> creates a table for Parent class with all the properties form the parent cla ss and creates a Table for sub class with a id of the parent table as foreign cl ass. 26. states of Entity. Transient (before saving) , Persistent (after saving -> changes to object are pe rsisted in the DB) and Detached (after session.close) 27. HQL QBE -> Query By Example 28. First Level Cache and Second Level Cache A. First Level Cache is a session cache and it available by default. B. Second Level Cache is at the sessionFactory and we need to enable it by addi ng the following properties in the config file. true org.hibernate.cache.ehcach e.SingletonEhCacheRegionFactory C. We also need to annotate the class with @Cacheable and @Cache(usage=CacheCon currencyStrategy.READ_ONLY) 29. Query Cache -> set cacheable to true for the query object then if the same query is executed again it is not queried from the database. Need to add the bel ow property to the config file along with the entries from the line 28. true 30.@Entity @org.hibernate.annotations.Entity(selectBeforeUpdate=true) -> this will execute a select query and see if any thing changed before issuing an update. 31. JOINS: select * from user_table1; select * from vehicle1; select user_name,name from user_table1, vehicle1 where USER_TABLE1.ID = VEHICLE1 .USER_ID; -- return only matching rows from both the tables. select user_name,name from user_table1 JOIN vehicle1 ON USER_TABLE1.ID = VEHICLE 1.USER_ID; -- return only matching rows from both the tables. select user_name,name from user_table1 LEFT JOIN vehicle1 ON USER_TABLE1.ID = VE HICLE1.USER_ID; -- return all matching rows from both the tables. + un matched rows from the left table. select user_name,name from user_table1 RIGHT JOIN vehicle1 ON USER_TABLE1.ID = V EHICLE1.USER_ID; -- return all matching rows from both the tables. + un matched rows from the right table. select user_name,name from user_table1 FULL JOIN vehicle1 ON USER_TABLE1.ID = VE HICLE1.USER_ID; -- return all matching rows from both the tables. + un matched

rows from both the tables. 32. @Formula("MONTHLY_SALARY*12") private float yearlySalary;

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF