Java.Hibernate.Beginner.Why use HQL ? What benefits ?

✅ Why use HQL? What are its benefits?

Answer:
HQL (Hibernate Query Language) is designed to let you write object-oriented, database-independent queries over your mapped entities. Its main benefits are:


🔹 1) Works with entities, not tables
✅ You write queries using your Java class and property names, not fragile database table or column names.
✅ This makes your code more intuitive and better aligned with your domain model.

🔹 2) Database independence
✅ Hibernate translates HQL into the appropriate SQL dialect for your configured database.
✅ This means you can switch databases (e.g., from MySQL to PostgreSQL) without rewriting your queries.

🔹 3) Type safety & maintenance
✅ Since HQL uses entity properties, your IDE can help you refactor field names across your codebase.
✅ Reduces errors caused by mismatches between database schema and your Java code.

🔹 4) Polymorphic queries
✅ HQL supports inheritance — you can query superclasses or subclasses in your entity hierarchy without writing complex SQL.

🔹 5) Powerful features
✅ Supports joins, subqueries, aggregations (COUNT(), SUM()), GROUP BY, ORDER BY, and more — all on your object model.
✅ Provides named parameters (:paramName) for safer, more readable queries.

🔹 6) Cleaner, more maintainable code
✅ Compared to SQL in code (which hardcodes database structure), HQL leads to cleaner, more maintainable Java applications.

🔹 Example benefit:
If your database column changes from username → user_name, but your Java field remains username, your HQL doesn’t need to change, because it references the entity property, not the column name.

✅ Key takeaway:
HQL lets you write portable, object-oriented, maintainable queries that align with your Java domain model and keep your codebase flexible, reducing coupling to the physical database schema.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Why use HQL ? What benefits ?

Java.Hibernate.Beginner.How do you create a basic HQL query?

🔹 Step-by-step example:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

// Basic HQL query: fetch all User entities
String hql = "FROM User";
List<User> users = session.createQuery(hql, User.class).list();

for (User user : users) {
    System.out.println("Username: " + user.getUsername());
}

tx.commit();
session.close();

🔹 Key points:
✅ FROM User is an HQL statement selecting the entire User entity — no need for SELECT if you want the whole object.
✅ session.createQuery(hql, User.class) creates a typed query returning List<User>.
✅ Always execute inside an active transaction when reading or modifying data.

🔹 Adding filtering with parameters:

String hql = "FROM User u WHERE u.username = :username";
User user = session.createQuery(hql, User.class)
                   .setParameter("username", "john")
                   .uniqueResult();

if (user != null) {
    System.out.println("Found user: " + user.getUsername());
}

🔹 What makes HQL powerful?

  • You query entities and properties → not tables or columns.
  • Hibernate translates HQL to database-specific SQL.
  • It’s portable and works across supported databases without changing your queries.

✅ Key takeaway:
To create a basic HQL query:
1️⃣ Write an HQL string (e.g., FROM Entity).
2️⃣ Pass it to session.createQuery().
3️⃣ Execute it with list(), uniqueResult(), or other query methods.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How do you create a basic HQL query?

Java.Hibernate.Beginner.Do i need write select word or not ?

No — you don’t have to use SELECT in HQL if you want to fetch entire entities. In HQL, you can simply write:

FROM User

This is equivalent to:

SELECT u FROM User u

Hibernate understands both forms — when you omit SELECT, Hibernate implicitly selects the entire entity.

🔹 Examples:

✅ Without SELECT:

String hql = "FROM User";
List<User> users = session.createQuery(hql, User.class).list();

✅ With SELECT:

String hql = "SELECT u FROM User u";
List<User> users = session.createQuery(hql, User.class).list();

🔹 When do you need SELECT?
You must use SELECT if you:
✅ Want to retrieve specific properties (projections), not entire entities:

String hql = "SELECT u.username FROM User u";
List<String> usernames = session.createQuery(hql, String.class).list();

✅ Want to use aggregate functions like COUNT(), SUM(), etc.:

String hql = "SELECT COUNT(u) FROM User u";
Long count = session.createQuery(hql, Long.class).uniqueResult();

✅ Key takeaway:
For entire entities, you can skip SELECT and just write FROM Entity.
For specific fields or aggregates, you must use SELECT.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Do i need write select word or not ?

Java.Hibernate.Beginner.What is HQL (Hibernate Query Language)?

HQL (Hibernate Query Language) is Hibernate’s object-oriented query language that lets you query your database using your Java entity and property names, rather than database table or column names.

🔹 Key points:
✅ HQL is similar to SQL in syntax but works with entities, not tables, and fields, not columns.
✅ It’s database-independent — Hibernate translates HQL to the appropriate SQL dialect for your configured database.
✅ Supports powerful features like joins, group by, subqueries, and aggregate functions.
✅ Safer and more maintainable than raw SQL because it’s tightly integrated with your Java model.

🔹 Basic example:

Session session = sessionFactory.openSession();

String hql = "FROM User WHERE username = :username";
User user = session.createQuery(hql, User.class)
                  .setParameter("username", "john")
                  .uniqueResult();

✅ Here:

  • FROM User uses the Java entity name, not the table name.
  • username is the entity’s property name.

🔹 Benefits of using HQL:
✅ Avoids hardcoding table or column names → reduces risk of mismatches when database schema changes.
✅ Lets you write database-agnostic queries — Hibernate handles translating HQL into the SQL your RDBMS understands.
✅ Supports polymorphic queries (e.g., queries across entity hierarchies).

🔹 Example with join:

String hql = "SELECT o FROM Order o JOIN o.customer c WHERE c.name = :name";
List<Order> orders = session.createQuery(hql, Order.class)
                            .setParameter("name", "Alice")
                            .list();

HQL is Hibernate’s powerful, entity-based query language, letting you write object-oriented, database-independent queries that operate on your mapped domain model.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is HQL (Hibernate Query Language)?

Java.Hibernate.Beginner.What is the difference between load() and get() methods?

🔹 1️⃣ session.get()
✅ Loads the entity immediately from the database or session cache.
✅ Returns the real object, not a proxy.
✅ Returns null if the entity with the given ID doesn’t exist — safe for optional lookups.
✅ Eager behavior → triggers a database query right away (unless already in first-level cache).

Example:

User user = session.get(User.class, 1L); // hits DB immediately
if (user == null) {
    System.out.println("User not found!");
}

🔹 2️⃣ session.load()
✅ Returns a proxy object (a lightweight placeholder) without immediately querying the database.
✅ Only queries the database when you actually access a property of the proxy (lazy initialization).
✅ Throws ObjectNotFoundException if the entity doesn’t exist when accessing properties.
✅ Useful when you know the entity must exist, or you want to delay the database hit until necessary.

Example:

User user = session.load(User.class, 1L); // returns proxy
System.out.println(user.getUsername());   // triggers DB fetch or throws exception if not found

🔹 Key differences summarized:

Featureget()load()
BehaviorEagerly fetches entity immediatelyReturns proxy; lazy fetches on property access
If not foundReturns nullThrows ObjectNotFoundException when accessed
Return typeReal entity instanceProxy object
Use caseWhen entity may or may not existWhen entity must exist or for lazy loading

🔹 Practical advice:
✅ Use get() when you’re unsure if the entity exists or need immediate data.
✅ Use load() when you know the entity must exist and want to benefit from lazy loading — but handle potential ObjectNotFoundException.

✅ Key takeaway:
get() fetches the entity right away and returns null if not found, while load() returns a proxy, delaying the query until you access a property — but throws an exception if the entity doesn’t exist.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is the difference between load() and get() methods?

Java.Hibernate.Beginner.How do you retrieve an object by its ID?

You retrieve an object by its primary key (ID) using either:
1️⃣ session.get() — recommended for most use cases, or
2️⃣ session.load() — advanced use cases.

🔹 Using session.get()

  • Loads the entity immediately from the database or session cache.
  • Returns the entity or null if no matching row is found.

Example:

Session session = sessionFactory.openSession();

User user = session.get(User.class, 1L); // fetch User with ID 1

if (user != null) {
    System.out.println("User: " + user.getUsername());
} else {
    System.out.println("User not found!");
}

session.close();

🔹 Using session.load()

  • Returns a proxy without hitting the database immediately (lazy load).
  • Only fetches data from DB if you actually access a property.
  • Throws ObjectNotFoundException if no matching row exists.

Example:

Session session = sessionFactory.openSession();

User user = session.load(User.class, 1L); // returns proxy

System.out.println(user.getUsername());   // triggers DB fetch

session.close();

🔹 Key differences:

MethodBehaviorNull handling
get()Eager: hits DB or cache immediatelyReturns null if not found
load()Lazy: returns proxyThrows ObjectNotFoundException if entity missing

🔹 Important note:
✅ Both methods return an object in persistent state if found.
✅ Using get() is safer and more common in CRUD apps.
✅ Using load() can be efficient for lazy loading, but be careful about exceptions if the entity doesn’t exist.

✅ Key takeaway:
Use session.get(Entity.class, id) to eagerly fetch an object by its primary key, or session.load() for lazy-loading a proxy when you know the entity must exist.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How do you retrieve an object by its ID?

Java.Hibernate.Beginner.When object becomes unattached ?

An entity becomes detached (unattached) when it was persistent in a session but is no longer associated with any open session. This happens in several common scenarios:


🔹 1) Session is closed

  • As soon as you call session.close(), all persistent entities managed by that session become detached.
    Example:
Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L); // persistent
session.close();                         // user now detached

🔹 2) Transaction is rolled back

  • If you rollback a transaction, the session may leave entities in a detached state depending on configuration or manually evict them.

🔹 3) Evicting an entity manually

  • Calling session.evict(entity) removes the entity from the session’s first-level cache → the entity becomes detached immediately.
    Example:
session.evict(user); // user is now detached

🔹 4) Clearing the session

  • Calling session.clear() evicts all managed entities, turning them all into detached objects.

🔹 5) Serialization & deserialization

  • If you serialize an entity to send it across a network or store it temporarily, when you deserialize it later, it’s detached because it’s not connected to any session anymore.

🔹 How to recognize a detached object:
✅ It still has its identifier (e.g., primary key),
✅ It exists in memory,
❌ But it’s no longer tracked by any Hibernate session, so modifying it won’t automatically trigger database updates.

🔹 Example:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = session.get(User.class, 1L); // persistent
tx.commit();
session.close();                         // user now detached

user.setUsername("newName");             // change won't persist — user is detached

An object becomes detached when it was previously persistent but is no longer associated with an open session, like after closing the session or evicting the entity → changes to detached objects won’t be tracked or saved by Hibernate.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.When object becomes unattached ?

Java.Hibernate.Beginner.How do you delete an object in Hibernate?

You delete an object in Hibernate by:
1️⃣ Loading or attaching the entity you want to delete in an active session.
2️⃣ Calling session.delete(entity) to mark it for deletion.
3️⃣ Committing the transaction to execute the SQL DELETE.

🔹 Example of deleting a persistent entity:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = session.get(User.class, 1L); // load entity to delete

if (user != null) {
    session.delete(user);               // marks entity for deletion
}

tx.commit();                            // executes DELETE
session.close();

✅ Here:

  • session.get() loads the entity → becomes persistent.
  • session.delete() schedules a SQL DELETE for the entity.
  • tx.commit() flushes the change → deletes the record in the database.

🔹 Deleting a detached entity:

  • If you have a detached object (e.g., from a previous session), you can still delete it by reattaching:
User detachedUser = new User();
detachedUser.setId(1L);                // ID of the row to delete

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

session.delete(detachedUser);          // Hibernate deletes based on ID

tx.commit();
session.close();

✅ Hibernate will issue a DELETE for the specified ID, even if the detached entity wasn’t fully loaded.

🔹 Important notes:

  • Always call delete() inside an active transaction.
  • If the entity is transient (never saved), calling delete() does nothing (no SQL issued).
  • Deleting entities with relationships may require proper cascade settings (e.g., CascadeType.REMOVE) to delete related records.

✅ Key takeaway:
Use session.delete(entity) inside a transaction to delete persistent or detached objects → then commit to apply the change.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How do you delete an object in Hibernate?

Java.Hibernate.Beginner.When i will get NonUniqueObjectException ? Give example

You get a NonUniqueObjectException if you try to reattach a detached entity using update(), but the session already has another persistent instance with the same identifier (primary key).


🔹 Why does it happen?

  • Hibernate ensures that within a single session, there can be only one managed (persistent) object representing a given database row (primary key).
  • If you try to update() a detached object with the same ID while another object with that ID is already loaded in the session → Hibernate throws NonUniqueObjectException.

🔹 Example showing how it happens:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

// 1) Load entity → becomes persistent
User persistentUser = session.get(User.class, 1L); 

// 2) Later, you try to update a detached instance with same ID
User detachedUser = new User();
detachedUser.setId(1L); // same primary key as persistentUser
detachedUser.setUsername("new_username");

session.update(detachedUser); // 💥 Boom! NonUniqueObjectException

tx.commit();
session.close();

✅ Why? Because:

  • The session already manages persistentUser with ID=1.
  • You try to update() another object (detachedUser) with the same ID.
  • Hibernate sees two objects representing the same row in one session → throws org.hibernate.NonUniqueObjectException.

🔹 How to avoid it?
✅ Instead of update(), use session.merge(detachedUser):

User managedUser = (User) session.merge(detachedUser); // merges state into existing persistentUser

merge() copies the detached object’s state into the persistent one → no duplicate, no exception.

✅ Key takeaway:
You get NonUniqueObjectException if you call update() with a detached object whose ID matches an already-managed entity in the same session.
Use merge() instead when you can’t guarantee there’s no persistent instance with the same ID.

Would you like a full example comparing update() and merge() behavior side by side?

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.When i will get NonUniqueObjectException ? Give example

Java.Hibernate.Beginner.How do you update an object in Hibernate?

There are two main ways to update an object in Hibernate, depending on whether the object is still persistent or has become detached:

🔹 1) Updating a persistent object (easiest case)

  • If the entity is still attached to an open session (persistent), simply modify its fields — Hibernate’s dirty checking will detect the changes and automatically generate the SQL UPDATE on flush() or commit().

Example:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = session.get(User.class, 1L); // user is now persistent
user.setEmail("newemail@example.com");   // modify persistent object

tx.commit();                            // flushes changes → SQL UPDATE
session.close();

✅ Here you don’t need to call update() — Hibernate tracks changes automatically!

🔹 2) Updating a detached object

  • If the entity was loaded in a previous session but is now detached (e.g., session was closed), you must reattach it to a new session using either:
    • session.update(entity) → reattaches the entity → Hibernate will update its state in the database.
    • session.merge(entity) → copies the state of the detached object into a managed persistent instance, and returns it.

Example with update():

// Detached object (e.g., loaded before, session closed)
User detachedUser = new User();
detachedUser.setId(1L);
detachedUser.setEmail("updatedemail@example.com");

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

session.update(detachedUser);           // reattaches → schedules UPDATE

tx.commit();
session.close();

Example with merge():

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User managedUser = (User) session.merge(detachedUser); // returns persistent copy

tx.commit();
session.close();

🔹 Which to use — update vs. merge?
✅ update() → works only if there’s no persistent instance with the same ID already in the session (else throws NonUniqueObjectException).
✅ merge() → safer in complex scenarios because it copies the state and returns a new managed object → avoids duplicate issues.

✅ Key takeaway:

  • Persistent object? Modify fields directly → Hibernate auto-updates.
  • Detached object? Reattach with update() or merge() → then commit the transaction.
Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How do you update an object in Hibernate?