### Customize Example with excludeZeroes(), excludeProperty(), ignoreCase(), enableLike()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Adjusts how the Example is applied by excluding zero-valued properties, excluding a named property, ignoring case, and enabling like comparisons. Use this to customize the Example criterion.
```java
Example example = Example.create(cat)
.excludeZeroes() //exclude zero valued properties
.excludeProperty("color") //exclude the property named "color"
.ignoreCase() //perform case insensitive string comparisons
.enableLike(); //use like for string comparisons
List results = session.createCriteria(Cat.class)
.add(example)
.list();
```
--------------------------------
### hibernate.cfg.xml configuration file example
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Full hibernate.cfg.xml example that can replace hibernate.properties or override its properties when both are present. The file is expected in the root of the CLASSPATH by default. It externalizes mapping file names and is convenient for tuning the Hibernate cache.
```xml
java:/comp/env/jdbc/MyDB
org.hibernate.dialect.MySQLDialect
false
org.hibernate.transaction.JTATransactionFactory
java:comp/UserTransaction
```
--------------------------------
### Hibernate BlogMain example: configure, export tables, CRUD, and HQL query
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
A complete Hibernate example class (BlogMain) that demonstrates configuring a SessionFactory, exporting tables with SchemaExport, creating and updating Blog and BlogItem entities, and querying with HQL. It shows typical transaction handling with rollback on HibernateException and closing sessions in finally blocks.
```java
package eg;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class BlogMain {
private SessionFactory _sessions;
public void configure() throws HibernateException {
_sessions = new Configuration()
.addClass(Blog.class)
.addClass(BlogItem.class)
.buildSessionFactory();
}
public void exportTables() throws HibernateException {
Configuration cfg = new Configuration()
.addClass(Blog.class)
.addClass(BlogItem.class);
new SchemaExport(cfg).create(true, true);
}
public Blog createBlog(String name) throws HibernateException {
Blog blog = new Blog();
blog.setName(name);
blog.setItems( new ArrayList() );
Session session = _sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.persist(blog);
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
return blog;
}
public BlogItem createBlogItem(Blog blog, String title, String text)
throws HibernateException {
BlogItem item = new BlogItem();
item.setTitle(title);
item.setText(text);
item.setBlog(blog);
item.setDatetime( Calendar.getInstance() );
blog.getItems().add(item);
Session session = _sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(blog);
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
return item;
}
public BlogItem createBlogItem(Long blogid, String title, String text)
throws HibernateException {
BlogItem item = new BlogItem();
item.setTitle(title);
item.setText(text);
item.setDatetime( Calendar.getInstance() );
Session session = _sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Blog blog = (Blog) session.load(Blog.class, blogid);
item.setBlog(blog);
blog.getItems().add(item);
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
return item;
}
public void updateBlogItem(BlogItem item, String text)
throws HibernateException {
item.setText(text);
Session session = _sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(item);
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
}
public void updateBlogItem(Long itemid, String text)
throws HibernateException {
Session session = _sessions.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
BlogItem item = (BlogItem) session.load(BlogItem.class, itemid);
item.setText(text);
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
}
public List listAllBlogNamesAndItemCounts(int max)
throws HibernateException {
Session session = _sessions.openSession();
Transaction tx = null;
List result = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(
"select blog.id, blog.name, count(blogItem) " +
"from Blog as blog " +
"left outer join blog.items as blogItem " +
"group by blog.name, blog.id " +
"order by max(blogItem.datetime)"
);
q.setMaxResults(max);
```
--------------------------------
### Use Example on an associated object with createCriteria("mate")
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Uses an Example to place criteria on an associated object by creating a nested criteria on the 'mate' association. The nested criteria uses an Example created from the associated instance.
```java
List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.createCriteria("mate")
.add( Example.create( cat.getMate() ) )
.list();
```
--------------------------------
### Example classes Parent and Child
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example classes Parent and Child used in the collection examples. Parent has a Set of Child instances.
```java
public class Parent {
private long id;
private Set children;
// getter/setter
...
}
public class Child {
private long id;
private String name
// getter/setter
...
}
```
--------------------------------
### Build SessionFactory with default hibernate.cfg.xml
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Build a SessionFactory using the default hibernate.cfg.xml configuration file. This is the simplest way to start Hibernate when using the XML configuration approach.
```java
SessionFactory sf = new Configuration().configure().buildSessionFactory();
```
--------------------------------
### Full hbm.xml mapping with joined-subclass
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Complete hbm.xml mapping example showing the joined-subclass strategy with a element to declare the primary key/foreign key column. The example maps a Cat class and its DomesticCat subclass, with the subclass table DOMESTIC_CATS and key column CAT.
```xml
```
--------------------------------
### Using interface proxies with load() and iterate()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Shows how proxies for instances of Cat and DomesticCat can be returned by load() or iterate() when using interface proxies. The example loads a CatImpl and iterates over a query result, casting to the Cat interface.
```java
Cat cat = (Cat) session.load(CatImpl.class, catid);
Iterator iter = session.createQuery("from CatImpl as cat where cat.name='fritz'").iterate();
Cat fritz = (Cat) iter.next();
```
--------------------------------
### HQL fetch all properties with order by and where
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Shows how to force Hibernate to fetch lazy properties immediately using 'fetch all properties'. The first example orders by name, the second adds a where clause.
```hql
from Document fetch all properties order by name
```
```hql
from Document doc fetch all properties where lower(doc.name) like '%cats%'
```
--------------------------------
### Legacy hbm.xml mapping example
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example of a legacy hbm.xml mapping document. It defines persistent classes Cat and Dog, including id generation, discriminator, properties, many-to-one and set associations, and a subclass. The mapping is Java-centric, built around persistent class declarations.
```xml
```
--------------------------------
### Simple hbm.xml composite-id mapping for User
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
A simple hbm.xml example mapping a composite identifier for the User entity using with two elements.
```xml
```
--------------------------------
### Legacy batch fetching SQL for 24 owners
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example SQL queries generated by the legacy batch fetching algorithm when initializing 24 owners with a batch-size of 25. The queries use pre-built batch sizes [25, 12, 10, 9, 8, 7, .., 1], resulting in three queries with 12, 10, and 2 placeholders.
```sql
select * from owner where id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
select * from owner where id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
select * from owner where id in (?, ?)
```
--------------------------------
### Composite key example with Customer, Order, LineItem, Product
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Illustrates a composite key mapping with Customer, Order, LineItem, and Product classes. The Order and LineItem use composite ids, and Order has a formula for total that sums line item quantities times product prices. The mapping uses assigned generators, inverse collections, and formulas for derived properties.
```xml
( select sum(li.quantity*p.price)
from LineItem li, Product p
where li.productId = p.productId
and li.customerId = customerId
and li.orderNumber = orderNumber )
( select sum(li.quantity)
from LineItem li
where li.productId = productId )
```
--------------------------------
### Configure Hibernate Core with setNamingStrategy
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Configures Hibernate Core to delegate to a different NamingStrategy by calling Configuration.setNamingStrategy() before adding mappings. Uses the built-in ImprovedNamingStrategy.INSTANCE as an example; replace with a custom implementation class name as needed.
```java
SessionFactory sf = new Configuration()
.setNamingStrategy(ImprovedNamingStrategy.INSTANCE)
.addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml")
.buildSessionFactory();
```
--------------------------------
### Temporarily load entities read-only and initialize collections
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
This example temporarily changes the session default to load entities as read-only, executes an HQL query, explicitly initializes proxies and collections, then restores the default. It is useful when a single query cannot load and initialize all necessary entities. The setDefaultReadOnly( true ) and setDefaultReadOnly( false ) calls are shown without the Session prefix, as in the source.
```java
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
setDefaultReadOnly( true );
Contract contract =
( Contract ) session.createQuery(
"from Contract where customerName = 'Sherman'" )
.uniqueResult();
Hibernate.initialize( contract.getPlan() );
Hibernate.initialize( contract.getVariations() );
Hibernate.initialize( contract.getNotes() );
setDefaultReadOnly( false );
...
tx.commit();
session.close();
```
--------------------------------
### Hibernate mapping for Employer/Employee with Employment association
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Hibernate mapping document for the Employer/Employee example. It defines three entity classes (Employer, Employment, Employee) with sequence-based identifiers, a component for MonetaryAmount, and many-to-one associations from Employment to Employer and Employee.
```xml
employer_id_seq
employment_id_seq
employee_id_seq
```
--------------------------------
### Configure c3p0 connection pool in hibernate.properties
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example hibernate.properties file for using the c3p0 connection pool. Setting hibernate.c3p0.* properties enables Hibernate's C3P0ConnectionProvider and disables the internal pool. The internal pool is not intended for production or performance testing.
```properties
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect
```
--------------------------------
### HQL aggregate functions example
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Returns the average, sum, maximum, and count of the weight property of Cat instances. The aggregate functions avg, sum, min, max, count are supported in HQL select clauses.
```hql
select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
from Cat cat
```
--------------------------------
### EventManagerServlet doGet() with session-per-request
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Basic servlet implementing the session-per-request pattern. It opens a Hibernate Session via getCurrentSession(), starts a transaction, and commits or rolls back based on exceptions. Save as src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java.
```java
package org.hibernate.tutorial.web;
// Imports
public class EventManagerServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" );
try {
// Begin unit of work
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
// Process request and render page...
// End unit of work
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
catch (Exception ex) {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
if ( ServletException.class.isInstance( ex ) ) {
throw ( ServletException ) ex;
}
else {
throw new ServletException( ex );
}
}
}
}
```
--------------------------------
### Native SQL queries with positional and named parameters
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
This example shows both positional (?) and named (:name) parameters in native SQL queries. The first query uses setString(0, "Pus%") for the positional parameter, and the second uses setString("name", "Pus%") for the named parameter.
```java
Query query = sess.createSQLQuery("SELECT * FROM CATS WHERE NAME like ?").addEntity(Cat.class);
List pusList = query.setString(0, "Pus%").list();
query = sess.createSQLQuery("SELECT * FROM CATS WHERE NAME like :name").addEntity(Cat.class);
List pusList = query.setString("name", "Pus%").list();
```
--------------------------------
### Execute native SQL queries with createSQLQuery
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Expresses queries in native SQL using `createSQLQuery()` and lets Hibernate map result sets to objects. SQL aliases must be enclosed in braces. The first example selects all columns with `{cat.*}`; the second explicitly lists columns and aliases.
```java
List cats = session.createSQLQuery("SELECT {cat.*} FROM CAT {cat} WHERE ROWNUM<10")
.addEntity("cat", Cat.class)
.list();
```
```java
List cats = session.createSQLQuery(
"SELECT {cat}.ID AS {cat.id}, {cat}.SEX AS {cat.sex}, " +
"{cat}.MATE AS {cat.mate}, {cat}.SUBCLASS AS {cat.class}, ... " +
"FROM CAT {cat} WHERE ROWNUM<10")
.addEntity("cat", Cat.class)
.list()
```
--------------------------------
### Using classpath:// user namespace in hbm.xml
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example of using user namespacing with a classpath:// URL protocol in an hbm.xml mapping. The EntityResolver resolves entities via the current thread context classloader and the classloader that loaded Hibernate classes. The referenced types.xml is a resource in the your.domain package containing a custom typedef.
```xml
]>
...
&types;
```
--------------------------------
### Map address to separate table with in hbm.xml
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example of mapping address information for a person to a separate table using the element. The join table 'ADDRESS' is linked via a key column and contains properties for address, zip, and country. This preserves value type semantics for all properties.
```xml
...
...
```
--------------------------------
### Compile the tutorial with Maven (mvn compile)
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Run the Maven compile goal to verify the project compiles. The output shows a successful build with the compiled source file path and build statistics.
```bash
[hibernateTutorial]$ mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building First Hibernate Tutorial
[INFO] task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Compiling 1 source file to /home/steve/projects/sandbox/hibernateTutorial/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009
[INFO] Final Memory: 5M/547M
[INFO] ------------------------------------------------------------------------
```
--------------------------------
### Programmatic configuration with setProperty()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Creates a Configuration instance and sets configuration properties such as dialect, datasource, and order_updates.
```java
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
.setProperty("hibernate.order_updates", "true");
```
--------------------------------
### Get collection size with createFilter
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Uses a collection filter to get the size of a collection without initializing it. The filter executes a count query and returns the result as an Integer.
```java
( (Integer) s.createFilter( collection, "select count(*)" ).list().get(0) ).intValue()
```
--------------------------------
### Programmatic configuration with addResource()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Creates a Configuration instance by adding mapping documents from the classpath using addResource().
```java
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
```
--------------------------------
### HQL subquery examples
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
HQL subqueries must be surrounded by parentheses and can appear only in the select or where clauses. These examples show correlated subqueries, the some keyword, not exists, not in, and a scalar subquery in the select clause.
```hql
from Cat as fatcat
where fatcat.weight > (
select avg(cat.weight) from DomesticCat cat
)
```
```hql
from DomesticCat as cat
where cat.name = some (
select name.nickName from Name as name
)
```
```hql
from Cat as cat
where not exists (
from Cat as mate where mate.mate = cat
)
```
```hql
from DomesticCat as cat
where cat.name not in (
select name.nickName from Name as name
)
```
```hql
select cat.id, (select max(kit.weight) from cat.kitten kit)
from Cat as cat
```
--------------------------------
### Create HibernateUtil helper class to build SessionFactory
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Use this class to centralize Hibernate startup. It builds a global SessionFactory from hibernate.cfg.xml in a static initializer and provides a static getter. The build catches Throwable and throws ExceptionInInitializerError if creation fails. Save as src/main/java/org/hibernate/tutorial/util/HibernateUtil.java.
```java
package org.hibernate.tutorial.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
```
--------------------------------
### Cache collections with @Cache annotation
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Cache a collection property by placing the @Cache annotation on the getter method. The example caches a SortedSet with NONSTRICT_READ_WRITE strategy.
```java
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="CUST_ID")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public SortedSet getTickets() {
return tickets;
}
```
--------------------------------
### Create a query criterion with Example.create()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Constructs a query criterion from a given instance using org.hibernate.criterion.Example. Version properties, identifiers, and associations are ignored; null valued properties are excluded by default.
```java
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.list();
```
--------------------------------
### Combine cascade styles in one-to-one mapping
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Combine multiple cascade styles by separating them with commas. This example cascades persist, delete, and lock operations along the association.
```XML
```
--------------------------------
### Programmatic configuration with addClass()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Creates a Configuration instance by specifying mapped classes, letting Hibernate find the mapping documents in the classpath.
```java
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
```
--------------------------------
### Composite identifier mapping in hbm.xml
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Equivalent hbm.xml mapping for the composite identifier examples. Uses with mapped="true" for Customer and a separate for User.
```xml
```
--------------------------------
### Implementing equals() and hashCode() with business key equality
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Recommended implementation of equals() and hashCode() using business key equality. Compares only properties that form the business key, such as litterId and mother, to avoid breaking the Set contract when identifiers are generated.
```java
public class Cat {
...
public boolean equals(Object other) {
if (this == other) return true;
if ( !(other instanceof Cat) ) return false;
final Cat cat = (Cat) other;
if ( !cat.getLitterId().equals( getLitterId() ) ) return false;
if ( !cat.getMother().equals( getMother() ) ) return false;
return true;
}
public int hashCode() {
int result;
result = getMother().hashCode();
result = 29 * result + getLitterId();
return result;
}
}
```
--------------------------------
### Maven POM for Hibernate tutorial web application
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Maven POM for the first Hibernate tutorial web application. Declares dependencies on hibernate-core, servlet-api, slf4j-simple, and javassist, and sets the WAR finalName to the artifactId. Use this as the project descriptor for the tutorial's web application.
```xml
4.0.0
org.hibernate.tutorials
hibernate-tutorial
1.0.0-SNAPSHOT
First Hibernate Tutorial
${artifactId}
org.hibernate
hibernate-core
javax.servlet
servlet-api
org.slf4j
slf4j-simple
javassist
javassist
```
--------------------------------
### Configure JNDI datasource in hibernate.properties
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Example hibernate.properties file for using an application server JNDI datasource. JDBC connections obtained from a JNDI datasource automatically participate in container-managed transactions.
```properties
hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect
```
--------------------------------
### Define cache concurrency strategy with @Cache
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Use the @Cache annotation on an entity class to define its cache concurrency strategy. The example sets NONSTRICT_READ_WRITE for the Forest entity. This is recommended over a global strategy.
```java
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Forest { ... }
```
--------------------------------
### HQL group by with aggregates
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Two examples of HQL group by clauses with aggregate functions. The first groups by a property and uses sum and count; the second groups by an id and uses avg and max.
```hql
select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color
```
```hql
select foo.id, avg(name), max(name)
from Foo foo join foo.names name
group by foo.id
```
--------------------------------
### @OneToMany with orphanRemoval
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Shows a one-to-many association with cascade=CascadeType.ALL and orphanRemoval=true. Removing an Order from the Customer's orders collection marks the Order for deletion. The example also demonstrates finding entities with em.find().
```java
@Entity
public class Customer {
private Set orders;
@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
public Set getOrders() { return orders; }
public void setOrders(Set orders) { this.orders = orders; }
[...]
}
@Entity
public class Order { ... }
Customer customer = em.find(Customer.class, 1l);
Order order = em.find(Order.class, 1l);
customer.getOrders().remove(order); //order will be deleted by cascade
```
--------------------------------
### Execute HQL queries with parameter binding and eager fetching
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Shows how to create and execute HQL queries using Session.createQuery() with parameter binding methods like setDate(), setString(), and setEntity(). The final query uses left join fetch to eagerly initialize collections, and the result is deduplicated with a HashSet.
```java
List cats = session.createQuery(
"from Cat as cat where cat.birthdate < ?")
.setDate(0, date)
.list();
List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name = ?")
.setString(0, name)
.list();
List kittens = session.createQuery(
"from Cat as cat where cat.mother = ?")
.setEntity(0, pk)
.list();
Cat mother = (Cat) session.createQuery(
"select cat.mother from Cat as cat where cat = ?")
.setEntity(0, izi)
.uniqueResult();]]
Query mothersWithKittens = (Cat) session.createQuery(
"select mother from Cat as mother left join fetch mother.kittens");
Set uniqueMothers = new HashSet(mothersWithKittens.list());
```
--------------------------------
### Override foreign key constraint name with @ForeignKey
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Use @ForeignKey to override the generated foreign key constraint name. The example shows the resulting SQL DDL with the custom constraint name.
```java
@Entity
public class Child {
...
@ManyToOne
@ForeignKey(name="FK_PARENT")
public Parent getParent() { ... }
...
}
alter table Child add constraint FK_PARENT foreign key (parent_id) references Parent
```
--------------------------------
### Configure Hibernate with hibernate.cfg.xml for HSQLDB
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
XML configuration for Hibernate 4.3 tutorial using HSQLDB in server mode. Sets up the built-in connection pool (not for production), HSQLDialect, thread-bound session context, disabled second-level cache, SQL echo, and schema update. Maps the Event.hbm.xml resource.
```xml
org.hsqldb.jdbcDriver
jdbc:hsqldb:hsql://localhost
sa
1
org.hibernate.dialect.HSQLDialect
thread
org.hibernate.cache.internal.NoCacheProvider
true
update
```
--------------------------------
### Build SessionFactory with a custom XML configuration file
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Build a SessionFactory using a specific XML configuration file by passing its name to the configure method. This allows selecting a different configuration file instead of the default hibernate.cfg.xml.
```java
SessionFactory sf = new Configuration()
.configure("catdb.cfg.xml")
.buildSessionFactory();
```
--------------------------------
### Multiple id properties without identifier type (hbm.xml)
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Equivalent hbm.xml mapping for the multiple id properties without identifier type example. Uses with and elements.
```xml
```
--------------------------------
### Activate a fetch profile with Session.enableFetchProfile
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Activates the 'customer-with-orders' fetch profile on a Session instance. The profile name must match the one defined in the mapping. After enabling, the session loads the customer and their orders together, overriding the default lazy loading for that association.
```java
Session session = ...;
session.enableFetchProfile( "customer-with-orders" ); // name matches from mapping
Customer customer = (Customer) session.get( Customer.class, customerId );
```
--------------------------------
### Projection list with rowCount, avg, max, and groupProperty
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Builds a projection list with rowCount, average weight, max weight, and a grouping projection on color. Grouping projections appear in the SQL group by clause automatically.
```java
List results = session.createCriteria(Cat.class)
.setProjection( Projections.projectionList()
.add( Projections.rowCount() )
.add( Projections.avg("weight") )
.add( Projections.max("weight") )
.add( Projections.groupProperty("color") )
)
.list();
```
--------------------------------
### Basic Hibernate mapping file structure
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Shows the basic structure of a Hibernate mapping file, including the DOCTYPE declaration and the hibernate-mapping root element. The DTD is loaded from the classpath (included in hibernate-core.jar) and enables auto-completion in editors. Replace the [...] placeholder with the actual mapping elements.
```xml
[...]
```
--------------------------------
### Open a Session with sessions.openSession()
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Opens a new Session from a SessionFactory. A JDBC connection is obtained from the pool when a task requires database access.
```java
Session session = sessions.openSession(); // open a new Session
```
--------------------------------
### Criteria query with setFetchMode(FetchMode.JOIN)
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Override the fetching strategy for a particular transaction using a Criteria query with setFetchMode(FetchMode.JOIN). This is Hibernate's equivalent of a fetch plan and changes how get() or load() retrieves associations.
```java
User user = (User) session.createCriteria(User.class)
.setFetchMode("permissions", FetchMode.JOIN)
.add( Restrictions.idEq(userId) )
.uniqueResult();
```
--------------------------------
### Define auxiliary database object with explicit CREATE and DROP commands
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Explicitly list CREATE and DROP commands for an auxiliary database object in the mapping file. Any SQL command runnable via java.sql.Statement.execute() is valid.
```xml
...
CREATE TRIGGER my_trigger ...
DROP TRIGGER my_trigger
```
--------------------------------
### Add email to Person collection
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Adds an email address to a person's collection. Uses session.load to get the Person and adds to the emailAddresses collection, which may trigger a lazy load. The transaction is committed after the addition.
```java
private void addEmailToPerson(Long personId, String emailAddress) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Person aPerson = (Person) session.load(Person.class, personId);
// adding to the emailAddress collection might trigger a lazy load of the collection
aPerson.getEmailAddresses().add(emailAddress);
session.getTransaction().commit();
}
```
--------------------------------
### Create a Criteria instance with setMaxResults
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Creates a Criteria instance for the Cat class, sets the maximum number of results to 50, and executes the query. The Session is the factory for Criteria instances.
```java
Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(50);
List cats = crit.list();
```
--------------------------------
### HQL distinct and count distinct examples
Source: https://docs.hibernate.org/orm/4.3/manual/en-US/html_single
Two queries showing the distinct and all keywords in HQL select clauses. The first returns distinct cat names; the second counts distinct names and total cats. The keywords have the same semantics as in SQL.
```hql
select distinct cat.name from Cat cat
```
```hql
select count(distinct cat.name), count(cat) from Cat cat
```