Hibernate 3.6 Criteria API root entity alias coverage mechanism resolution

Understanding root entity alias issues in Hibernate Criteria API
When querying using the Hibernate Criteria API, we often need to specify aliases for entities to improve the readability of SQL or resolve column name conflicts. Usually, you can set the alias through the getSession().createCriteria(Entity.class, "aliasName") method. However, in certain versions such as Hibernate 3.6.10.Final, after setting a custom alias (such as temp) for the root entity (that is, the starting entity of the query), the generated SQL statement still uses the default alias (usually this_), which brings confusion to developers.
For example, when we try to set the Vehicle entity's alias to temp:
Criteria cr = getSession().createCriteria(Vehicle.class, "temp"); // ...other Criteria configuration
We expect that in the generated SQL statement, the alias of the vehicle table is temp:
/* criteria query */ select temp.vehicle_id as y0_, temp.vin as y1_, temp.initial_registration as y2_ from vehicle temp where temp.vin=?
But the actual observed SQL is:
/* criteria query */ select this_.vehicle_id as y0_, this_.vin as y1_, this_.initial_registration as y2_ from vehicle this_ where this_.vin=?
This shows that the custom alias we set has not taken effect.
Sample code
To better illustrate this problem, we use a simplified Vehicle entity and its corresponding Criteria query method:
Vehicle entity definition:
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.*;
import java.util.Date; // Import Date class import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "vehicle")
public class Vehicle {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "vehicle_id", unique = true, nullable = false)
private int vehicleId;
@Column(nullable = false, length = 17)
private String vin;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "initial_registration")
private Date initialRegistration;
}
Criteria query method:
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import java.util.ArrayList;
import java.util.List;
public class VehicleDao { // Assume this is a DAO class private Session session; // Assume the session has been obtained in some way public VehicleDao(Session session) {
this.session = session;
}
protected Session getSession() {
return session;
}
// Assume that begin() and commit() are transaction management methods protected void begin() { /* Transaction start logic*/ }
protected void commit() { /* transaction commit logic*/ }
public <t> List<t> findByProjectionCriteria() {
Criteria cr = getSession().createCriteria(Vehicle.class, "temp"); // Try to set the alias to "temp"
cr.setResultTransformer(Transformers.aliasToBean(Vehicle.class));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("vehicleId"), "vehicleId");
projectionList.add(Projections.property("vin"), "vin");
projectionList.add(Projections.property("initialRegistration"), "initialRegistration");
cr.setProjection(projectionList);
cr.add(Restrictions.eq("vin", "WVW29343249702776"));
begin(); // Transaction starts List<t> list = null;
try {
list = cr.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
commit(); // Transaction submission}
if (list == null) {
list = new ArrayList();
}
return list;
}
}</t></t></t>
Hibernate internal mechanism analysis
In order to understand why custom aliases are overridden, we need to have a deeper understanding of the internal mechanism of Hibernate 3.6 version to handle Criteria queries. When the Criteria.list() method is called, it triggers the corresponding logic in SessionImpl and creates a CriteriaLoader object. CriteriaLoader will construct a CriteriaQueryTranslator object during the initialization process, and it is this CriteriaQueryTranslator that is responsible for converting the Criteria query into an actual SQL statement and handling aliases in the process.
One of the core methods of CriteriaQueryTranslator is createCriteriaSQLAliasMap(), which is responsible for establishing the mapping between Criteria objects and SQL aliases. Let’s take a look at the simplified logic of this method:
private void createCriteriaSQLAliasMap() {
int i = 0;
// Traverse all non-root criteria (such as child criteria in a related query)
Iterator criteriaIterator = criteriaEntityNames.entrySet().iterator();
while ( criteriaIterator.hasNext() ) {
Map.Entry me = ( Map.Entry ) criteriaIterator.next();
Criteria crit = (Criteria) me.getKey();
String alias = crit.getAlias(); // Get the alias set by the user if (alias == null) {
alias = ( String ) me.getValue(); // If not set, use the entity name}
// Generate and store alias criteria for non-root criteriaSQLAliasMap.put( crit, StringHelper.generateAlias( alias, i ) );
}
// Root Criteria alias processing criteriaSQLAliasMap.put( rootCriteria, rootSQLAlias ); // Here the root Criteria alias is set to rootSQLAlias (ie "this_")
}
Problem root analysis:
Custom alias addition: When we call getSession().createCriteria(Vehicle.class, "temp"), we create a Criteria instance and set the alias temp for it. This Criteria instance will be added to the criteriaEntityNames collection (or similar structure). In the while loop in the createCriteriaSQLAliasMap() method, it iterates through these Criteria instances. At this point, our Vehicle root Criteria will be recognized, and its custom alias temp will be obtained and temporarily stored as a value in the criteriaSQLAliasMap together with the Vehicle root Criteria instance (as a key).
Default alias override: After the while loop ends, the createCriteriaSQLAliasMap() method will execute the key last line of code: criteriaSQLAliasMap.put( rootCriteria, rootSQLAlias ); The rootCriteria here is the Vehicle root Criteria instance we created, and rootSQLAlias is usually this_ by default in Hibernate 3.6. Since rootCriteria is unique as a Map key, this line of code will overwrite the custom alias temp previously stored for the same rootCriteria instance with the default this_alias.
Therefore, no matter what alias we specify for the root entity in the createCriteria() method, it will eventually be overwritten by the default rootSQLAlias (i.e. this_) inside the CriteriaQueryTranslator.
Conclusion and Notes
In Hibernate version 3.6, due to the implementation mechanism of its internal CriteriaQueryTranslator, setting a custom table alias for the root entity through getSession().createCriteria(Entity.class, "aliasName") is invalid, and the final generated SQL will still use the default this_alias.
Things to note:
- Version limitation: This behavior is a feature or limitation of specific versions of Hibernate 3.6. In subsequent Hibernate versions (such as Hibernate 5 and above), the usage and internal implementation of the Criteria API may differ, and the handling of root entity aliases may also be improved.
- Understand rather than avoid: For developers still using Hibernate 3.6, the importance of understanding this mechanism is that do not expect to change the default SQL alias of the root entity through the createCriteria() method. If you have strict custom needs for SQL aliases, you may want to consider the following alternatives:
- HQL (Hibernate Query Language): HQL allows aliases to be specified explicitly in queries, such as from Vehicle temp where temp.vin = ?.
- Native SQL: Write native SQL queries directly and have full control over every detail of the SQL statement, including table aliases.
- Upgrade considerations: If the project allows, upgrading to a higher version of Hibernate may be a more fundamental way to solve such problems, because new versions usually bring more features, optimizations, and more flexible API designs.
In short, in the Hibernate 3.6 environment, when we use the Criteria API, we should know that the table alias of the root entity will always default to this_, and adjust the development strategy accordingly.
The above is the detailed content of Hibernate 3.6 Criteria API root entity alias coverage mechanism resolution. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20516
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
The correct way to send emails in batches using JavaMail API in Java
Mar 04, 2026 am 10:33 AM
This article explains in detail how to correctly set multiple recipients (BCC/CC/TO) through javax.mail in Java, solves common misunderstandings - repeatedly calling setRecipients() causes only the first/last address to take effect, and provides a safe and reusable code implementation.
Elementary practice: How to write a simple console blog searcher in Java_String matching
Mar 04, 2026 am 10:39 AM
String.contains() is not suitable for blog search because it only supports strict substring matching and cannot handle case, spaces, punctuation, spelling errors, synonyms and fuzzy queries; preprocessing toLowerCase() indexOf() or escaped wildcard regular matching (such as .*java.*config.*) is a more practical lightweight alternative.
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-





