· 6 years ago · Oct 21, 2019, 05:02 AM
1# What is Hibernate?
2- Object Relational Mapping (ORM) framework which is used to map POJOs to SQL entities.
3- lightweight, open source, database independent.
4- faster (due to caching) and no SQL is required, as Hibernate generates the correct SQL syntax based on the provided Hibernate Dialect.
5- abstracts away JDBC, JPA Java persistence api, JTA java transaction api as well as SQLException (4.X and higher)
6- SQLException are abstracted into HibernateException (extends RuntimeException).
7## Why do we need ORM tools?
8- make data access more abstract and portable. ORM implementation class knows how to write vendor specific SQL so you don’t have to.
9## What does an ORM consist of?
10- API for performing basic CRUD operations
11- API to express queries referring to classes.
12- facilities to specify metadata.
13- optimization such as dirty checking and lazy association.
14
15
16## How do we write queries in Hibernate?
17- HQL → fully Object Oriented query language uses class names instead of table names and property names instead of column names.
18 - express complex queries
19- Criteria → used for retrieve queries ONLY.
20- Native SQL
21## How do I configure Hibernate?
22- hibernate.cfg.xml, located in src/main/resources.
23- Information you need to provide is URL, USERNAME, PASSWORD, DIALECT, Driver, hbm2ddl
24## HBM2ddl?
25- property in hibernate.cfg.xml that automatically validates or exports schema to the DB whenever a SessionFactory is created
26 - validate: make no changes to the db
27 - update: updates the schema
28 - create: creates the schema, destroying previous data.
29 - create-drop: creates, drops the schema whenever the SessionFactory is closed explicitly.
30## What are the Object states?
311. Transient → Object that is not associated with a Hibernate Session
322. Persistent → Object that is associated w/ a Hibernate Session.
333. Detached → object that was associated w/ a Session, but the Session has closed
34## What are the important interfaces?
35- Configuration (actually a class)
36 - used to create a SessionFactory and specify the location of the hibernate.cfg.xml file.
37 - SessionFactory → creates Sessions
38 - Session → represents a connection to the DB
39 - Transaction → associated w/ a session, a conversation between the application and the db.
40 - Query → used to create complex CRUD using HQL
41 - Criteria → retrieve only queries, allow you to use restrictions and projections
42## What is a restriction?
43- used w/ the Criteria API to restrict the retrieval of data through comparison operators from a db.
44- functions like WHERE
45- only applicable to rows
46## What is a projection?
47- are used to execute aggregate operations and to get single-column queries
48- only applied to columns.
49----------
50
51Employee.java
52Employee.hbm.xml
53
54
55## What do I need to include in the hbm.xml file?
56```xml
57 <hibernate-mapping>
58 <class name="NameOfPojo" table="desiredTableName">
59 <id name="NameOfIdField" type="int"> // used for primary key
60 <column name="entity_id"/>
61 <generator class="sequence"/> //sequence is the actual keyword
62 </id>
63 <property name="Java Field" type="string">
64 <column name="col_name"/>
65 </property>
66 </class>
67 </hibernateMapping>
68```
69
70## How do I configure an Entity with annotations?
71- `@Entity` declares the POJO as an entity
72- `@Table` define the table name w/ the `name` attr
73- `@Id` declares a field as the table’s primary key
74- `@GeneratedValue` applied to a PK field to specify generation strategies for the PK
75 - name: name of generator you use in SequenceGenerator
76 - strategy: specifies the generation Strategy
77 - AUTO: let Hibernate choose based on dialect
78 - SEQUENCE: uses a DB sequence to generate values
79 - IDENTITY: Lets the db generate a new value
80 - TABLE: rarely used anymore, simulates a sequence by updating and storing its current value in a table
81- `@SequenceGenerator` - defines a PK generator
82 - name: a unique generator name
83 - sequenceName: the name of DB sequence object to obtain PK values
84 - initialValue
85 - allocationSize: amount to increment
86- `@Column` declares a field as an entity column
87## What is DynamicInsert and DynamicUpdate?
88- both class-level annotations
89- `@DynamicInsert` ensures that the translated native SQL contains columns whose values are not null.
90- `@DynamicUpdate` ensures that the translated native SQL only includes the values which have changed.
91- Prior to Hibernate 5, you had to use the `org.hibernate.annotations.Entity` specifying the dynamic insert & dynamic update attributes.
92## What is transactional Write Behind?
93- Where Hibernate ignores FK constraints during a transaction.
94## What is automatic dirty checking?
95- mechanism that updates the DB when we modify the state of an object during a transaction
96- whenever a persistent object is loaded through Hibernate, it makes an additional copy of that persistent objects along with its property values. Hibernate auto detects incoming changes and schedules SQL UPDATE statements accordingly.
97## What is a Proxy?
98- a subclass of the object being fetched, which is created at runtime, instead of hitting the database directly.
99- proxies are a way to avoid retrieving an object until you need it
100## What are the fetching strategies?
101- fetching is the process of grabbing data from the db and making it available to the application.
102- eager → associated data is initialized when the object is being fetched
103- lazy → defer initialization of association until it’s needed
104- tuning how an application does its fetching is one of the biggest factors in determining how an application will perform
105## How do we achieve multiplicity in Hibernate?
106- `@OneToOne` → defaults to eager fetching.
107 - unidirectional → source entity has a relationship field that refers to the target entity
108 - bidirectional → each entity has a relationship field that refers to the other. Specify the mapped by attribute in the source entity, and the `@JoinColumn` in target entity
109- `@OneToMany` → defaults to lazy fetching, `@ManyToOne` → defaults to eager
110 - unidrectional → source entity has a relationship that refers to the target entity.
111 - bidirectional → each entity has a relationship field that refers to the other. Specify mappedBy in the source entity and `@JoinColumn` in the target entity
112- `@ManyToMany` → default lazy
113 - unidirectional → source entity has a relationship field that refers to the target entity
114 - `@JoinTable`, specify the `joinColumn` and `inverseJoinColumn` attributes
115 - bidirectional → each entity has a relationship field that points to the other entity
116 - source entity much have `@ManyToMany` and `@JoinTable`
117 - target entity must have mappedBy attribute defined in the `@ManyToMany`
118## What is CascadeType?
119- entities that use relationships often have to rely on the existence of the other entity of the relationship
120- CascadeType defines the cascade operations that are applied in a relationship.
121 - PERSIST: save() or persist operations cascade to related entities.
122 - MERGE: related entities are merged when the owning entity is merged
123 - REFRESH: refresh() is cascaded
124 - REMOVE: cascade delete
125 - DETACH: detach all related activities if a manual detach occurs, evict()
126 - ALL: all of the above
127## What is the difference in session.get() and session.load()?
128- load() will always return a proxy without hitting the DB
129 - if no object is found an ObjectNotFoundException is thrown
130- get() will always hit the database and return an object that row, not a proxy
131 - return null if no row is found
132## What is the difference in session.update() and session.merge()?
133- both transfer an object from the detached state to persistent state
134- when we use update(), if there is already an in the session cache containing the same object, then a NonUniqueObjectException is thrown
135- when we use merge, it forces Hibernate to copy any changes from the detached instance onto the instance you want to save, and thus merges all changes in memory before save.
136 - this may use more resources because it copies all values to a persistent instance in the Session, which will be loaded if it’s not currently loaded.
137## What is caching?
138- caching is the storing of data so that future requests for that data may be retrieved more quickly.
139- L1 → objects are cached within the Session
140 - Session Scoped.
141 - default setting
142- L2 → objects are cached across sessions
143 - must be configured.
144 - Session Factory scoped
145 - L2 Caching Providers
146 - EHCache
147 - JBossCache
148 - OSCache
149 - SwarmCache
150 - ApacheIgnite
151 - Hazelcast