Java.Hibernate.Beginner.What is better, save or persist ?

It depends on your needs — but in modern, portable code, persist() is usually the better choice. Here’s why:


🔹 Why prefer persist()
✅ Standardized (JPA) — persist() is part of the JPA specification, so it’s portable across any JPA implementation (Hibernate, EclipseLink, etc.).
✅ Safer behavior — persist() requires an active transaction, ensuring you don’t accidentally “save” something without committing (which could silently fail with save()).
✅ Consistent semantics — guarantees the entity will become managed/persistent if the transaction commits.

🔹 When might you use save()
✅ If you specifically need the generated ID immediately, because save() returns it as a Serializable.
✅ If you’re writing Hibernate-specific code, and you don’t care about JPA portability.
✅ When you don’t mind that save() works outside transactions (but be careful: this can lead to inconsistent behavior).

🔹 Key differences summarized:

Featuresave()persist()
Returns ID?Yes (Serializable)No (void)
Requires transaction?No (but recommended)Yes (throws exception if missing)
JPA-compliant?No (Hibernate-specific)Yes (standard JPA)
PortabilityHibernate-onlyWorks with any JPA provider

✅ Best practice:
Use persist() for new projects or whenever you want portable, JPA-compliant code.
Use save() only if you specifically need the returned ID and you’re OK with Hibernate-specific APIs.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is better, save or persist ?

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

To save an object in Hibernate, you need to:
1️⃣ Open a Hibernate Session.
2️⃣ Start a transaction.
3️⃣ Call session.save() or session.persist() to make the object persistent.
4️⃣ Commit the transaction to write the object to the database.
5️⃣ Close the session to release resources.


🔹 Example step-by-step:

Session session = sessionFactory.openSession();    // 1️⃣ Open session
Transaction tx = session.beginTransaction();       // 2️⃣ Start transaction

User user = new User();                            // Create new entity
user.setUsername("alice");
user.setEmail("alice@example.com");

session.save(user);                                // 3️⃣ Save object → schedules INSERT

tx.commit();                                      // 4️⃣ Commit transaction → executes SQL
session.close();                                  // 5️⃣ Close session

🔹 What happens under the hood:
✅ session.save(user) → assigns an ID and marks the object as persistent, adding it to the first-level cache.
✅ Hibernate queues the SQL INSERT statement in memory.
✅ tx.commit() → triggers a flush → executes the actual SQL insert on the database.
✅ After commit, the object’s generated ID is available, and the session’s changes are persisted.

🔹 Important notes:

  • Always save objects inside a transaction → without commit(), data won’t persist to the database.
  • Remember to close the session to avoid connection and memory leaks.

🔹 Using JPA-standard persist() instead of save():

session.persist(user);  // also makes the entity persistent, but returns void

✅ Key takeaway:
To save an object in Hibernate: open a session, start a transaction, call save() or persist(), commit the transaction, and close the session.

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

Java.Hibernate.Beginner.What happens if you don’t close a session in Hibernate?

✅ What happens if you don’t close a Hibernate session?

Answer:
If you don’t close a Session, several serious problems can occur:

🔹 1) Database connection leaks
✅ Each Hibernate Session holds a JDBC connection (from your connection pool, e.g., HikariCP).
✅ If you forget to close the session, the connection is never returned to the pool → over time, you’ll exhaust all available connections.
✅ Result: new sessions fail with Timeout waiting for connection or Connection refused errors..

🔹 2) Memory leaks
✅ Hibernate keeps a first-level cache (session cache) storing all persistent entities you loaded, saved, or updated.
✅ If the session stays open, this cache keeps growing → unused objects stay in memory → application consumes more and more RAM → potential OutOfMemoryError.

🔹 3) Locks and transactions left open
✅ An open session might leave uncommitted transactions or database locks hanging → can cause data corruption, deadlocks, or blocking of other database clients.

🔹 4) Data consistency issues
✅ If the session is not closed properly, changes might not be flushed or committed → entities modified in-memory may never persist to the database → data loss.

🔹 Example of forgetting to close:

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

User user = session.get(User.class, 1L);
user.setUsername("new_name");

tx.commit();
// session.close() missing! ← connection and memory leak risk

🔹 In modern Spring Boot apps:
✅ You don’t manage session closure manually when using @Transactional → Spring handles opening, flushing, committing/rolling back, and closing the session for you automatically.

✅ Key takeaway:
Failing to close a Hibernate session causes connection leaks, memory leaks, data consistency problems, and potential app crashes → always close the session when done, or use frameworks like Spring to handle it automatically.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What happens if you don’t close a session in Hibernate?

Java.Hibernate.Beginner.Explain “Can leave the entity in a transient state if there’s no transaction (e.g., changes may not actually persist)”

🔹 What happens technically:
When you call session.save(entity), Hibernate assigns an identifier (e.g., the primary key) and puts the entity into the session’s first-level cache — so it becomes persistent in the session context.

But if you haven’t started a transaction, then:

  • There’s no active database transaction to guarantee that the pending insert will be executed and committed.
  • Hibernate will still queue the SQL INSERT statement internally, but it won’t necessarily send it to the database immediately.
  • If you close the session or an error happens before a transaction is committed, the entity’s changes may never actually get flushed to the database — leaving it effectively transient outside the session.

🔹 Example showing the problem:

Session session = sessionFactory.openSession(); // but NO transaction started!

User user = new User();
user.setUsername("john");

session.save(user); // Hibernate assigns ID, but no transaction active
// No commit happens, so changes might never be sent to DB!

session.close();    // Session closes → pending SQL is discarded → user is not saved in DB

🔹 Why doesn’t persist() do this?

  • The JPA persist() method requires an active transaction — if you try to call persist() outside a transaction, it throws a TransactionRequiredException.
    ✅ This prevents you from accidentally thinking you saved something when no transaction is active.

🔹 Key takeaway:

  • save() can mislead you into thinking you’ve persisted data when you haven’t committed a transaction → resulting in lost changes.
  • Always use save() (or persist()) inside an active transaction, and prefer persist() for standard, safer behavior.
Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Explain “Can leave the entity in a transient state if there’s no transaction (e.g., changes may not actually persist)”

Java.Hibernate.Beginner.What is the difference between save() and persist() in Hibernate?

🔹 1) save()
✅ Returns the generated identifier (primary key) immediately as a Serializable value.
✅ Works both inside and outside of an active transaction.
✅ Can leave the entity in a transient state if there’s no transaction (e.g., changes may not actually persist).
✅ Hibernate-specific → not part of the standard JPA API.

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

Long id = (Long) session.save(user); // returns the generated ID immediately

session.getTransaction().commit();
session.close();

🔹 2) persist()
✅ Does not return the ID — it’s a void method.
✅ Requires an active transaction → throws TransactionRequiredException if called outside of one.
✅ Is a standard JPA method → portable across Hibernate, EclipseLink, etc.
✅ Guarantees that the entity will become managed/persistent if transaction commits.

Example:

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

session.persist(user); // returns void; user becomes managed

session.getTransaction().commit();
session.close();

🔹 Key differences summarized:

Aspectsave()persist()
Return valueReturns generated IDReturns nothing (void)
TransactionWorks without one (but not recommended)Requires active transaction
APIHibernate-specificStandard JPA
BehaviorCan leave entity transientEnsures entity becomes persistent

✅ Key takeaway:

  • Use persist() for JPA-compliant, standard behavior requiring an active transaction.
  • Use save() if you need the ID immediately, but remember it’s Hibernate-specific.
Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is the difference between save() and persist() in Hibernate?

Java.Hibernate.Beginner.How do you begin and commit a transaction in Hibernate?

You manage transactions in Hibernate using the Transaction API. You:

  • Begin a transaction with session.beginTransaction().
  • Commit it with transaction.commit().
  • Optionally roll it back with transaction.rollback() in case of errors.

🔹 Basic example of transaction management:

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

try {
    tx = session.beginTransaction();   // start transaction

    User user = new User();
    user.setUsername("john");
    session.save(user);                // persist entity within transaction

    tx.commit();                       // commit transaction (flushes changes to DB)
} catch (Exception e) {
    if (tx != null) tx.rollback();     // rollback on error
    e.printStackTrace();
} finally {
    session.close();                   // always close session
}

🔹 What happens during this flow:
✅ session.beginTransaction() creates a new transaction bound to the current session and underlying database connection.
✅ All changes (INSERT, UPDATE, DELETE) are queued during the transaction.
✅ tx.commit() flushes pending changes to the database and commits the transaction atomically.
✅ If an exception occurs, tx.rollback() undoes all pending changes.

🔹 Why transactions matter:

  • Without transactions, partial updates could leave your database in an inconsistent state.
  • Transactions ensure atomicity, consistency, isolation, and durability (ACID properties).

🔹 In Spring Boot apps:
✅ You typically don’t call beginTransaction() or commit() manually → use @Transactional, and Spring manages transactions automatically.


✅ Key takeaway:
To manually manage transactions in Hibernate:
1️⃣ session.beginTransaction() to start,
2️⃣ perform your operations,
3️⃣ transaction.commit() to save, or transaction.rollback() on errors,
4️⃣ and always session.close() to clean up.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How do you begin and commit a transaction in Hibernate?

Java.Hibernate.Beginner.How do you close a Hibernate session?

You close a Hibernate Session by calling its close() method:

session.close();

🔹 What happens when you call session.close()?
✅ Releases the JDBC connection associated with the session back to the connection pool (e.g., HikariCP).
✅ Destroys the session’s first-level cache, evicting all managed entities.
✅ Cleans up other resources like prepared statements and internal caches.
✅ Marks the session as closed — trying to use it afterward will throw a org.hibernate.SessionException.

🔹 When should you close a session?

  • Always close the session after finishing a unit of work (e.g., at the end of a request or service method).
  • If you don’t close it, you can leak database connections, exhaust the connection pool, or hold unnecessary memory.

🔹 Full example with proper session closure:

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

try {
    User user = session.get(User.class, 1L);
    user.setUsername("updated_name");

    tx.commit();
} catch (Exception e) {
    if (tx != null) tx.rollback();
    e.printStackTrace();
} finally {
    session.close(); // ensures session is closed even if exceptions occur
}

🔹 In Spring Boot apps:
✅ You typically don’t call session.close() manually → Spring manages session lifecycle automatically when you use @Transactional.

Always call session.close() when done to release database resources — in modern apps, Spring or other frameworks often handle this for you, but in manual setups it’s your responsibility.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How do you close a Hibernate session?

Java.Hibernate.Beginner.In which cases entity starts to be trackable ?

An entity starts being trackable (i.e., Hibernate will dirty-check it and sync changes) when it becomes persistent — specifically, when it’s associated with an open Hibernate session.

🔹 Here are the cases when an entity becomes persistent and trackable:

✅ 1) When you call session.save(entity) or session.persist(entity)
Hibernate saves the transient entity → it becomes persistent → tracked for dirty changes.

✅ 2) When you load an entity with session.get(), session.load(), or a query

User user = session.get(User.class, 1L); // fetched entity is persistent and tracked

✅ 3) When you reattach a detached entity with session.update(entity) or session.merge(entity)

  • After reattaching, Hibernate starts tracking the entity again.

✅ 4) When an entity is associated through cascading

  • For example, if you save an Order with @OneToMany(cascade = CascadeType.PERSIST) on OrderLines, the child entities also become persistent and tracked.

🔹 When an entity is NOT tracked:
❌ If the entity is transient → newly created with new but not saved or loaded → Hibernate knows nothing about it.
❌ If the entity is detached → it was persistent, but the session is closed or the entity was evicted → Hibernate no longer tracks it.
❌ If you use a StatelessSession → entities are never tracked (no dirty checking at all).

🔹 Example of entity becoming trackable:

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

User user = new User();           // transient, NOT tracked yet
user.setUsername("john");

session.save(user);               // becomes persistent → Hibernate starts tracking
user.setEmail("john@example.com");// will be detected and auto-updated on flush

tx.commit();                      // flush triggers SQL UPDATE if needed
session.close();

An entity becomes trackable (persistent) when it’s attached to an open session, either by saving, loading, or reattaching — from that point on, Hibernate’s dirty checking automatically synchronizes changes to the database.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.In which cases entity starts to be trackable ?

Java.Hibernate.Beginner.What is dirty checking ?

Dirty checking is Hibernate’s automatic mechanism that tracks changes to persistent entities and ensures that any updates you make to those objects are automatically synchronized to the database when the session is flushed (usually at transaction commit).

🔹 How does it work?

  • When you load or save an entity in a Hibernate Session, it becomes persistent and is stored in the first-level cache.
  • Hibernate takes a snapshot of the entity’s initial state when it’s first loaded or saved.
  • If you modify the entity’s fields while it’s still attached to the session, Hibernate compares the current state to the snapshot during flush().
  • If any differences (i.e., “dirtiness”) are detected, Hibernate generates the appropriate UPDATE SQL statement.

🔹 Example:

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

User user = session.get(User.class, 1L); // loads entity, takes initial snapshot
user.setUsername("new_username");        // modifies persistent entity

// No explicit update needed!
// Hibernate detects the change at flush/commit:
tx.commit();                             // generates UPDATE automatically
session.close();

✅ Without dirty checking, you’d have to manually issue an UPDATE or save() call — but with dirty checking, Hibernate does it for you.

🔹 Key points about dirty checking:
✅ It works only for persistent entities attached to an open session.
✅ Happens automatically when you call flush() or commit().
✅ Saves developers from writing explicit UPDATE statements → you just modify objects, and Hibernate persists changes.
✅ Dirty checking respects transactional boundaries, ensuring changes are atomic.

🔹 Limitations:

  • If the entity is detached (e.g., session closed), changes won’t be tracked or persisted automatically.
  • Using StatelessSession disables dirty checking entirely — you must manage updates manually.

✅ Key takeaway:
Dirty checking lets you focus on changing objects naturally in code, while Hibernate tracks and synchronizes those changes with the database automatically at flush time.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is dirty checking ?

Java.Hibernate.Beginner.Whats is Stateless session ?

A StatelessSession is a lighter, faster version of Session.

It does not use first-level cache, doesn’t track entity states, or support automatic flushing.

Best suited for batch processing where you just want to read or write data efficiently without overhead.

🔹 Why use it?
✅ Avoids memory overhead from tracking entities.
✅ Reduces CPU time Hibernate spends on dirty checking.
✅ Excellent for ETL, data migration, or large-scale imports.

🔹 How to obtain a StatelessSession:
You open it directly from the SessionFactory:

StatelessSession statelessSession = sessionFactory.openStatelessSession();
Transaction tx = statelessSession.beginTransaction();

🔹 Example: Bulk insert with StatelessSession

StatelessSession statelessSession = sessionFactory.openStatelessSession();
Transaction tx = statelessSession.beginTransaction();

for (int i = 0; i < 10000; i++) {
    User user = new User();
    user.setUsername("bulk_user_" + i);
    user.setEmail("bulk" + i + "@example.com");

    statelessSession.insert(user); // no caching, direct insert
}

tx.commit();
statelessSession.close();

✅ In this example:

  • Hibernate skips first-level caching and change tracking, writing data directly to the database → much faster for big batches.

🔹 Important differences vs. regular Session:

FeatureSessionStatelessSession
CachingUses first-levelNo first-level cache
Dirty checkingAutomaticNone — you must manage changes manually
AssociationsFully supportedLimited, no automatic cascading
Use caseGeneral CRUDBulk operations

✅ Key takeaway:
Use StatelessSession when you need maximum performance for batch inserts or updates, but remember: you lose convenience features like caching, automatic flush, and change tracking.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Whats is Stateless session ?