0
# Database & ORM Layer
1
2
Comprehensive Hibernate ORM integration providing custom types, property accessors, database dialects, dynamic query building, and multi-database support for the Liferay portal framework.
3
4
## Capabilities
5
6
### Session Management
7
8
Core Hibernate session management with portal-specific enhancements and optimizations.
9
10
```java { .api }
11
/**
12
* Hibernate SessionFactory wrapper with portal enhancements
13
*/
14
public class SessionFactoryImpl implements SessionFactory {
15
16
/**
17
* Opens a new Hibernate session
18
* @return new Session instance
19
*/
20
public Session openSession();
21
22
/**
23
* Gets the current session bound to the thread
24
* @return current Session instance
25
*/
26
public Session getCurrentSession();
27
28
/**
29
* Closes the SessionFactory and releases resources
30
*/
31
public void close();
32
}
33
34
/**
35
* Hibernate Session wrapper with portal-specific enhancements
36
*/
37
public class SessionImpl implements Session {
38
39
/**
40
* Creates a new Query for HQL execution
41
* @param queryString the HQL query string
42
* @return Query instance
43
*/
44
public Query createQuery(String queryString);
45
46
/**
47
* Creates a new SQLQuery for native SQL execution
48
* @param queryString the native SQL query string
49
* @return SQLQuery instance
50
*/
51
public SQLQuery createSQLQuery(String queryString);
52
53
/**
54
* Begins a new transaction
55
* @return Transaction instance
56
*/
57
public Transaction beginTransaction();
58
59
/**
60
* Saves or updates the given entity
61
* @param entity the entity to save or update
62
*/
63
public void saveOrUpdate(Object entity);
64
65
/**
66
* Deletes the given entity
67
* @param entity the entity to delete
68
*/
69
public void delete(Object entity);
70
}
71
```
72
73
### Dynamic Query Framework
74
75
Flexible query building system enabling type-safe dynamic query construction at runtime.
76
77
```java { .api }
78
/**
79
* Factory for creating dynamic queries
80
*/
81
public class DynamicQueryFactoryImpl implements DynamicQueryFactory {
82
83
/**
84
* Creates a dynamic query for the specified class
85
* @param clazz the entity class
86
* @return DynamicQuery instance
87
*/
88
public DynamicQuery forClass(Class<?> clazz);
89
90
/**
91
* Creates a dynamic query for the specified class with custom ClassLoader
92
* @param clazz the entity class
93
* @param classLoader the ClassLoader to use
94
* @return DynamicQuery instance
95
*/
96
public DynamicQuery forClass(Class<?> clazz, ClassLoader classLoader);
97
}
98
99
/**
100
* Dynamic query builder implementation
101
*/
102
public class DynamicQueryImpl implements DynamicQuery {
103
104
/**
105
* Adds a criterion to the query
106
* @param criterion the query criterion
107
* @return this DynamicQuery for method chaining
108
*/
109
public DynamicQuery add(Criterion criterion);
110
111
/**
112
* Adds an ordering to the query
113
* @param order the ordering specification
114
* @return this DynamicQuery for method chaining
115
*/
116
public DynamicQuery addOrder(Order order);
117
118
/**
119
* Sets the maximum number of results
120
* @param maxResults maximum results to return
121
* @return this DynamicQuery for method chaining
122
*/
123
public DynamicQuery setLimit(int start, int end);
124
125
/**
126
* Executes the query and returns results as a list
127
* @return List of query results
128
*/
129
public List<Object> list();
130
131
/**
132
* Executes the query and returns a single result
133
* @return single query result or null
134
*/
135
public Object uniqueResult();
136
}
137
```
138
139
### Query Criteria and Restrictions
140
141
Query building components for constructing complex database queries with type safety.
142
143
```java { .api }
144
/**
145
* Query criterion implementation for building WHERE clauses
146
*/
147
public class CriterionImpl implements Criterion {
148
// Implementation for individual query criteria
149
}
150
151
/**
152
* Conjunction (AND) criteria combination
153
*/
154
public class ConjunctionImpl implements Criterion {
155
156
/**
157
* Adds a criterion to the AND conjunction
158
* @param criterion the criterion to add
159
* @return this Conjunction for method chaining
160
*/
161
public Conjunction add(Criterion criterion);
162
}
163
164
/**
165
* Disjunction (OR) criteria combination
166
*/
167
public class DisjunctionImpl implements Criterion {
168
169
/**
170
* Adds a criterion to the OR disjunction
171
* @param criterion the criterion to add
172
* @return this Disjunction for method chaining
173
*/
174
public Disjunction add(Criterion criterion);
175
}
176
177
/**
178
* Factory for creating query ordering
179
*/
180
public class OrderFactoryImpl implements OrderFactory {
181
182
/**
183
* Creates ascending order for property
184
* @param propertyName the property name
185
* @return Order instance for ascending sort
186
*/
187
public Order asc(String propertyName);
188
189
/**
190
* Creates descending order for property
191
* @param propertyName the property name
192
* @return Order instance for descending sort
193
*/
194
public Order desc(String propertyName);
195
}
196
197
/**
198
* Factory for creating query projections
199
*/
200
public class ProjectionFactoryImpl implements ProjectionFactory {
201
202
/**
203
* Creates count projection
204
* @param propertyName the property to count
205
* @return Projection for count operation
206
*/
207
public Projection count(String propertyName);
208
209
/**
210
* Creates sum projection
211
* @param propertyName the property to sum
212
* @return Projection for sum operation
213
*/
214
public Projection sum(String propertyName);
215
216
/**
217
* Creates property projection
218
* @param propertyName the property to project
219
* @return Projection for property selection
220
*/
221
public Projection property(String propertyName);
222
}
223
224
/**
225
* Factory for creating query restrictions
226
*/
227
public class RestrictionsFactoryImpl implements RestrictionsFactory {
228
229
/**
230
* Creates equality restriction
231
* @param propertyName the property name
232
* @param value the value to match
233
* @return Criterion for equality check
234
*/
235
public Criterion eq(String propertyName, Object value);
236
237
/**
238
* Creates inequality restriction
239
* @param propertyName the property name
240
* @param value the value to compare against
241
* @return Criterion for inequality check
242
*/
243
public Criterion ne(String propertyName, Object value);
244
245
/**
246
* Creates LIKE restriction for pattern matching
247
* @param propertyName the property name
248
* @param value the pattern to match
249
* @return Criterion for LIKE operation
250
*/
251
public Criterion like(String propertyName, String value);
252
253
/**
254
* Creates IN restriction for multiple values
255
* @param propertyName the property name
256
* @param values the collection of values
257
* @return Criterion for IN operation
258
*/
259
public Criterion in(String propertyName, Collection<?> values);
260
}
261
```
262
263
### Database Dialect Support
264
265
Multi-database support through custom Hibernate dialects optimized for each database platform.
266
267
```java { .api }
268
/**
269
* IBM DB2 database dialect with enterprise optimizations
270
*/
271
public class DB2Dialect extends Dialect {
272
// DB2-specific SQL generation and optimizations
273
}
274
275
/**
276
* HSQL Database dialect for embedded database support
277
*/
278
public class HSQLDialect extends Dialect {
279
// HSQL-specific SQL generation and in-memory optimizations
280
}
281
282
/**
283
* MariaDB/MySQL dialect with MariaDB-specific optimizations
284
*/
285
public class MariaDBDialect extends Dialect {
286
// MariaDB-specific SQL generation and performance optimizations
287
}
288
289
/**
290
* Oracle 10g+ dialect with Oracle-specific features
291
*/
292
public class Oracle10gDialect extends Dialect {
293
// Oracle-specific SQL generation and advanced features
294
}
295
296
/**
297
* SQL Server 2005 dialect
298
*/
299
public class SQLServer2005Dialect extends Dialect {
300
// SQL Server 2005-specific SQL generation
301
}
302
303
/**
304
* SQL Server 2008+ dialect with enhanced features
305
*/
306
public class SQLServer2008Dialect extends Dialect {
307
// SQL Server 2008+ specific SQL generation and features
308
}
309
```
310
311
### Custom Hibernate Types
312
313
Portal-specific Hibernate type handlers for enhanced data type support and serialization.
314
315
```java { .api }
316
/**
317
* Boolean type handler with portal-specific logic
318
*/
319
public class BooleanType implements UserType {
320
public int[] sqlTypes();
321
public Class<?> returnedClass();
322
public Object nullSafeGet(ResultSet rs, String[] names, Object owner);
323
public void nullSafeSet(PreparedStatement st, Object value, int index);
324
}
325
326
/**
327
* String type handler with portal enhancements
328
*/
329
public class StringType implements UserType {
330
public int[] sqlTypes();
331
public Class<?> returnedClass();
332
public Object nullSafeGet(ResultSet rs, String[] names, Object owner);
333
public void nullSafeSet(PreparedStatement st, Object value, int index);
334
}
335
336
/**
337
* String CLOB type handler for large text fields
338
*/
339
public class StringClobType implements UserType {
340
public int[] sqlTypes();
341
public Class<?> returnedClass();
342
public Object nullSafeGet(ResultSet rs, String[] names, Object owner);
343
public void nullSafeSet(PreparedStatement st, Object value, int index);
344
}
345
346
/**
347
* Map type handler for serialized Map storage
348
*/
349
public class MapType implements UserType {
350
public int[] sqlTypes();
351
public Class<?> returnedClass();
352
public Object nullSafeGet(ResultSet rs, String[] names, Object owner);
353
public void nullSafeSet(PreparedStatement st, Object value, int index);
354
}
355
```
356
357
### Property Access Strategies
358
359
Flexible property access mechanisms supporting various field and method access patterns.
360
361
```java { .api }
362
/**
363
* Base property accessor strategy for Liferay entities
364
*/
365
public class LiferayPropertyAccessor implements PropertyAccessor {
366
367
/**
368
* Gets property value from entity
369
* @param entity the target entity
370
* @param propertyName the property name
371
* @return property value
372
*/
373
public Object get(Object entity, String propertyName);
374
375
/**
376
* Sets property value on entity
377
* @param entity the target entity
378
* @param propertyName the property name
379
* @param value the value to set
380
*/
381
public void set(Object entity, String propertyName, Object value);
382
}
383
384
/**
385
* Camel case property accessor
386
*/
387
public class CamelCasePropertyAccessor extends LiferayPropertyAccessor {
388
// Camel case property name handling
389
}
390
391
/**
392
* Method-based property accessor using getter/setter methods
393
*/
394
public class MethodPropertyAccessor extends LiferayPropertyAccessor {
395
// Method-based property access
396
}
397
398
/**
399
* Private field property accessor using reflection
400
*/
401
public class PrivateFieldPropertyAccessor extends LiferayPropertyAccessor {
402
// Direct private field access
403
}
404
405
/**
406
* Public field property accessor
407
*/
408
public class PublicFieldPropertyAccessor extends LiferayPropertyAccessor {
409
// Direct public field access
410
}
411
```
412
413
## Usage Examples
414
415
**Basic Session Operations:**
416
417
```java
418
SessionFactoryImpl sessionFactory = new SessionFactoryImpl();
419
SessionImpl session = (SessionImpl) sessionFactory.openSession();
420
421
try {
422
Transaction tx = session.beginTransaction();
423
424
// Save entity
425
User user = new User();
426
user.setName("John Doe");
427
session.saveOrUpdate(user);
428
429
// Query entities
430
Query query = session.createQuery("FROM User WHERE active = :active");
431
query.setParameter("active", true);
432
List<User> users = query.list();
433
434
tx.commit();
435
} finally {
436
session.close();
437
}
438
```
439
440
**Dynamic Query Building:**
441
442
```java
443
DynamicQueryFactoryImpl queryFactory = new DynamicQueryFactoryImpl();
444
RestrictionsFactoryImpl restrictions = new RestrictionsFactoryImpl();
445
OrderFactoryImpl orderFactory = new OrderFactoryImpl();
446
447
DynamicQuery query = queryFactory.forClass(User.class)
448
.add(restrictions.eq("active", true))
449
.add(restrictions.like("name", "John%"))
450
.addOrder(orderFactory.asc("name"))
451
.setLimit(0, 10);
452
453
List<Object> results = query.list();
454
```
455
456
**Custom Type Usage:**
457
458
```java
459
// Custom types are automatically used by Hibernate when configured
460
// in mapping files or annotations
461
@Type(type = "com.liferay.portal.dao.orm.hibernate.StringClobType")
462
private String description;
463
464
@Type(type = "com.liferay.portal.dao.orm.hibernate.MapType")
465
private Map<String, Object> attributes;
466
```
467
468
## Integration with Portal Framework
469
470
The database and ORM layer provides foundational data access for the entire portal:
471
472
- **Entity Management** - All portal entities use this ORM layer
473
- **Service Layer Integration** - Portal services build on these database capabilities
474
- **Transaction Management** - Comprehensive transaction support for portal operations
475
- **Multi-tenant Support** - Database isolation and partitioning capabilities
476
- **Performance Optimization** - Database-specific optimizations and caching
477
- **Migration Support** - Schema evolution and upgrade capabilities
478
479
## Supported Databases
480
481
- **IBM DB2** - Enterprise database with advanced features and optimizations
482
- **HSQL Database** - Embedded database for development, testing, and simple deployments
483
- **MariaDB/MySQL** - Open source databases with MariaDB-specific enhancements
484
- **Oracle 10g+** - Enterprise Oracle database with version-specific features
485
- **Microsoft SQL Server 2005/2008+** - Microsoft database platforms with version compatibility
486
487
## Error Handling
488
489
Common database-related exceptions and error scenarios:
490
491
- **HibernateException** - General Hibernate ORM exceptions
492
- **DataAccessException** - Data access layer exceptions
493
- **ConstraintViolationException** - Database constraint violations
494
- **OptimisticLockingFailureException** - Concurrent modification conflicts
495
- **ConnectionException** - Database connectivity issues
496
497
Best practices include proper transaction management, connection pooling configuration, and comprehensive error logging for database operations.