Java.Hibernate.Beginner.What does the @GeneratedValue annotation do?

The @GeneratedValue annotation in JPA/Hibernate tells the persistence provider how to automatically generate values for the primary key field when a new entity is persisted.
It works together with @Id to specify the strategy for generating unique identifiers.


🔹 What does it provide?
✅ Automates primary key generation → you don’t need to manually set IDs.
✅ Ensures IDs are unique across your entity’s table.
✅ Integrates with different strategies (e.g., database auto-increment, sequences, tables) depending on your database and performance needs.


🔹 Basic usage:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // tells Hibernate to use DB auto-increment
private Long id;

🔹 Main strategies you can specify:
✅ GenerationType.IDENTITY → database auto-increment columns.
✅ GenerationType.SEQUENCE → database sequence objects.
✅ GenerationType.TABLE → special table used for ID generation.
✅ GenerationType.AUTO → JPA provider automatically chooses the best strategy.


🔹 Why is it important?
✅ Simplifies entity persistence by removing the need to manually set unique IDs.
✅ Helps avoid bugs from duplicate or conflicting keys.
✅ Allows your application to scale without worrying about key collisions.


🔹 What happens without @GeneratedValue?
You must manually set the primary key on every new entity → error-prone and impractical in most applications.


✅ Key takeaway:
@GeneratedValue automates the generation of primary keys, ensuring each persisted entity gets a unique ID according to the chosen strategy, making your code simpler, safer, and database-friendly.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What does the @GeneratedValue annotation do?

Java.Hibernate.Beginner.What types of @GeneratedValue we have ?

The @GeneratedValue annotation lets you tell JPA/Hibernate how to automatically generate primary key values. You choose the strategy using strategy = GenerationType.XXX, where the main options are:


🔹 1️⃣ GenerationType.IDENTITY

  • Relies on the database’s auto-increment or identity columns.
  • The database generates the ID on insert.
  • Suitable for MySQL, SQL Server, PostgreSQL, etc.
  • No separate sequence or table needed.

Example:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

🔹 2️⃣ GenerationType.SEQUENCE

  • Uses a database sequence object to generate unique IDs.
  • Portable across databases that support sequences (e.g., Oracle, PostgreSQL).
  • Typically more efficient than TABLE strategy.

Example:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Long id;

🔹 3️⃣ GenerationType.TABLE

  • Uses a special table to store and increment primary key values.
  • Database-independent (works even on databases without sequences or identity columns).
  • Least efficient in high-concurrency environments → rarely used in modern projects.

Example:

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_gen")
@TableGenerator(name = "user_table_gen", table = "id_generator", pkColumnName = "gen_name",
                valueColumnName = "gen_value", pkColumnValue = "user_id", allocationSize = 1)
private Long id;

🔹 4️⃣ GenerationType.AUTO

  • The default strategy: lets the JPA provider choose the best strategy based on the database dialect.
  • Might use IDENTITY, SEQUENCE, or TABLE depending on the DB.
  • Easiest way to let Hibernate handle key generation automatically.

Example:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

🔹 Quick summary table:

StrategyHow it worksWhen to use
IDENTITYDatabase auto-incrementMySQL, SQL Server, etc.
SEQUENCEDatabase sequence objectOracle, PostgreSQL, etc.
TABLETable storing generated IDsDBs without sequences/identity
AUTOProvider picks best strategyWhen you want portability

You can choose among IDENTITY, SEQUENCE, TABLE, and AUTO in @GeneratedValue to control how Hibernate generates unique IDs — pick the one that fits your database and scalability needs.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What types of @GeneratedValue we have ?

Java.Hibernate.Beginner.What is the @Id annotation used for?

The @Id annotation marks a field or getter in a JPA entity as the primary key, meaning it uniquely identifies each entity instance and maps to the primary key column in the database table.

🔹 Why is it important?
✅ Every JPA entity must have exactly one primary key → it’s required for Hibernate or any JPA provider to:

  • Track and manage entities in the persistence context.
  • Generate correct SQL for CRUD operations.
  • Identify objects for updates, deletes, and relationships.
    ✅ Without an @Id, your entity is invalid and won’t work with JPA/Hibernate → you’ll get runtime errors.

🔹 Basic example:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // optional, for auto-increment
    private Long id;

    private String username;
}

✅ Here:

  • id is the primary key column in the users table.
  • Hibernate uses id as the unique identifier of each User instance.

🔹 Where can you put @Id?
✅ On a field (as above) → field access.
✅ On a getter method:

@Id
public Long getId() { return id; }

🔹 What about key generation?
You often combine @Id with @GeneratedValue to let Hibernate automatically generate key values:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;

🔹 For composite keys:
If your primary key spans multiple columns, use @EmbeddedId or @IdClass, but each key field still uses @Id in case of @IdClass.

✅ Key takeaway:
@Id marks the primary key field of an entity → it’s essential for Hibernate/JPA to uniquely identify, persist, and manage entity instances.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is the @Id annotation used for?

Java.Hibernate.Beginner.What does the @Table annotation do?

The @Table annotation in JPA/Hibernate is used in combination with @Entity to customize the mapping between your Java class and the database table.
It allows you to explicitly specify the table name and define additional table-level constraints like unique keys or indexes.


🔹 What happens if you omit @Table?
✅ By default, JPA maps the entity to a table with the same name as the class (e.g., class User → table User).


🔹 How to use @Table:

@Entity
@Table(name = "users") // customize table name
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
}

✅ Here:

  • Even if the Java class is named User, the entity will be stored in the users table.

🔹 Advanced features of @Table:
You can also define unique constraints or indexes:

@Entity
@Table(
    name = "users",
    uniqueConstraints = @UniqueConstraint(columnNames = {"email"}),
    indexes = @Index(name = "idx_username", columnList = "username")
)
public class User {
    @Id
    private Long id;
    private String username;
    private String email;
}

✅ Here:

  • Adds a unique constraint on email.
  • Creates an index on username.

🔹 Key options in @Table:

  • name → database table name.
  • catalog and schema → specify catalog/schema in DB (optional).
  • uniqueConstraints → declare unique constraints on one or more columns.
  • indexes → define database indexes (JPA 2.1+).

🔹 Key points:
✅ @Entity alone maps the class → @Table customizes how it maps to the physical table.
✅ Without @Table, the default table name is the class

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What does the @Table annotation do?

Java.Hibernate.Beginner.What is the purpose of the @Entity annotation?

The @Entity annotation marks a Java class as a persistent entity in JPA/Hibernate, meaning it should be mapped to a table in the database.
It tells the JPA provider (Hibernate) to manage instances of the class as rows in a relational table.

🔹 What does @Entity do?
✅ Registers the class as part of the persistence context → Hibernate will map it to a database table.
✅ Enables automatic ORM (object-relational mapping) → Hibernate translates Java objects into SQL statements for CRUD operations.
✅ Ensures the class participates in JPA features like transactions, caching, dirty checking, and queries.

🔹 Basic example:

import javax.persistence.Entity;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
}

✅ Here:

  • User is an entity → each instance of User corresponds to a row in a table (e.g., users).
  • Fields in User map to columns in the table.

🔹 Important notes:
✅ Every @Entity class must have a primary key, defined with @Id.
✅ You can specify a custom table name with @Table(name = "your_table"), but if omitted, the table defaults to the class name.

🔹 Why is it important?
Without @Entity, Hibernate/JPA ignores the class → it won’t be mapped to a table, persisted, or managed.

✅ Key takeaway:
@Entity marks a Java class as a persistent entity mapped to a database table, enabling Hibernate or any JPA provider to manage it automatically.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is the purpose of the @Entity annotation?

Java.Hibernate.Beginner.What are transient, persistent, and detached objects in Hibernate?

🔹 1️⃣ Transient objects
✅ Newly created objects that are not associated with any Hibernate session and have no representation in the database yet.
✅ Hibernate does not track them → changes are ignored unless you explicitly save them.
✅ Created with new but not yet saved or loaded.

Example:

User user = new User(); // transient
user.setUsername("alice");

🔹 2️⃣ Persistent objects
✅ Objects that are associated with an open Hibernate session → Hibernate tracks their state and automatically synchronizes any changes with the database at flush or commit.
✅ They can become persistent by:

  • Saving a transient object: session.save(user)
  • Loading from DB: session.get(User.class, 1L)
  • Reattaching a detached object: session.update(user) or session.merge(user)

Example:

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

User user = session.get(User.class, 1L); // persistent
user.setUsername("bob");                // tracked → auto-updated on commit

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

🔹 3️⃣ Detached objects
✅ Objects that were persistent but the session is now closed or the entity was evicted → they still exist in memory but are no longer tracked by Hibernate.
✅ Changes to detached objects will not be persisted until you reattach them.

Example:

Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L); // persistent
session.close();                         // user becomes detached

user.setUsername("carol");               // changes not tracked

// Reattach if needed:
Session session2 = sessionFactory.openSession();
session2.beginTransaction();
session2.update(user);                   // now persistent again
session2.getTransaction().commit();
session2.close();

🔹 Summary table:

StateAssociated with Session?Tracked?Example
Transient❌ No❌ Nonew User()
Persistent✅ Yes✅ Yessession.get() or save()
Detached❌ No (was persistent)❌ NoAfter session.close()
Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What are transient, persistent, and detached objects in Hibernate?

Java.Hibernate.Beginner.What is optimistic locking in Hibernate?

Optimistic locking is a concurrency control strategy in Hibernate where multiple transactions can read and update the same data concurrently, but Hibernate checks for conflicts at commit time by comparing a version field.
If another transaction modified the data in the meantime, Hibernate detects the conflict and prevents overwriting by throwing an exception.

🔹 Why use optimistic locking?
✅ It allows high concurrency without holding database locks → best for scenarios where conflicts are rare but possible (e.g., most business systems).
✅ Eliminates blocking and deadlocks caused by pessimistic locks.

🔹 How does it work?

  • You add a @Version field in your entity (e.g., long or Timestamp).
  • Hibernate increments the version each time you update the entity.
  • When you commit, Hibernate checks the version:
    • If the version matches the one originally read → commit proceeds.
    • If the version changed (someone else modified the record) → Hibernate throws an OptimisticLockException.

🔹 Example entity with optimistic locking:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Version // enables optimistic locking
    private Long version;

    // getters and setters
}

🔹 What happens in the database:
Hibernate uses the version field in UPDATE statements:

UPDATE product
SET name = ?, version = version + 1
WHERE id = ? AND version = ?;

✅ If no rows are updated (because the version no longer matches), Hibernate throws OptimisticLockException.

🔹 Key differences from pessimistic locking:
✅ Optimistic locking → no locks are held → better performance and scalability.
✅ Pessimistic locking → locks records immediately → better for high-conflict scenarios.

🔹 When should you use optimistic locking?
✅ When your use case rarely has simultaneous updates → most web apps, CRUD systems, etc.
✅ When you need concurrency control without sacrificing performance.

🔹 Important note:
Optimistic locking cannot prevent concurrent reads, but it prevents lost updates by detecting write conflicts.

🔹 Important note:
Optimistic locking cannot prevent concurrent reads, but it prevents lost updates by detecting write conflicts.

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

Java.Hibernate.Beginner.What is pessimistic locking in Hibernate?

Pessimistic locking is a concurrency control strategy in Hibernate (and relational databases in general) where a row-level lock is acquired in the database as soon as you read or access a record, preventing other transactions from modifying it until your transaction completes.

🔹 Why use pessimistic locking?
✅ Ensures strong consistency when you need to prevent concurrent updates to the same record (e.g., financial transactions, inventory updates).
✅ Guarantees no other transaction can change or overwrite data you’re working with.

🔹 How does it work?

  • Hibernate issues SQL statements with lock hints like SELECT ... FOR UPDATE.
  • The database locks the rows until your transaction commits or rolls back.
  • Other transactions trying to acquire incompatible locks will block or fail with a timeout.

🔹 Example of using pessimistic lock in Hibernate:

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

User user = session.get(User.class, 1L, LockMode.PESSIMISTIC_WRITE); // lock user row

user.setUsername("newName");

tx.commit(); // releases the lock
session.close();

✅ Here, LockMode.PESSIMISTIC_WRITE instructs Hibernate to lock the selected row for exclusive writing → no other transaction can modify it simultaneously.

🔹 Lock modes for pessimistic locking:

  • LockMode.PESSIMISTIC_READ → acquire a shared lock to prevent other transactions from writing, but allow concurrent reads.
  • LockMode.PESSIMISTIC_WRITE → acquire an exclusive lock to prevent other reads or writes.
  • LockMode.PESSIMISTIC_FORCE_INCREMENT → lock and force a version increment for versioned entities.

🔹 SQL generated by Hibernate:
When using LockMode.PESSIMISTIC_WRITE, Hibernate typically issues:

SELECT * FROM users WHERE id = ? FOR UPDATE;

🔹 Key differences from optimistic locking:
✅ Pessimistic locking → prevents concurrent updates up front by locking data immediately.
✅ Optimistic locking → allows concurrent reads/updates but checks for conflicts when committing (e.g., using a @Version column).

🔹 When should you use pessimistic locking?
✅ When concurrent modifications must be strictly serialized.
✅ When data integrity is critical, and you can’t tolerate lost updates or write conflicts.
❌ Avoid pessimistic locks for high-throughput scenarios, as they can reduce concurrency and cause blocking.

✅ Key takeaway:
Pessimistic locking in Hibernate acquires database locks immediately to prevent concurrent modifications, ensuring strong consistency — but should be used judiciously to avoid hurting performance.

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

Java.Hibernate.Beginner.What is cascade in Hibernate?

Cascade in Hibernate specifies which operations performed on a parent entity should automatically propagate to its related child entities. It controls whether actions like save, update, delete, or refresh applied to one entity also affect its associated entities.

🔹 Why do we need cascading?
Without cascade, you’d have to manually save, update, or delete each associated entity → tedious and error-prone.
Cascading simplifies entity lifecycle management, especially in parent-child relationships.

🔹 How do you specify cascade?
Use the cascade attribute on JPA/Hibernate association annotations, like @OneToMany, @OneToOne, or @ManyToOne.

Example:

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Employee> employees;

✅ Here, any operation on Department cascades to its Employee list.

🔹 Common cascade types:

  • CascadeType.PERSIST → automatically saves new child entities when the parent is saved.
  • CascadeType.MERGE → updates child entities when the parent is merged.
  • CascadeType.REMOVE → deletes child entities when the parent is deleted.
  • CascadeType.REFRESH → refreshes child entities when the parent is refreshed.
  • CascadeType.DETACH → detaches child entities when the parent is detached.
  • CascadeType.ALL → includes all of the above.

if i want to use number of them

@OneToMany(
    mappedBy = "department",
    cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}
)
private List<Employee> employees;

🔹 Example usage:

Department department = new Department();
Employee employee1 = new Employee();
employee1.setDepartment(department);
department.getEmployees().add(employee1);

session.persist(department); // with CascadeType.PERSIST → saves employee1 too!

🔹 Important notes:
✅ Cascading only applies within the same Hibernate session — it doesn’t automatically handle changes across multiple transactions.
✅ Always use cascading carefully: CascadeType.REMOVE on many-to-many relationships, for example, can lead to unintended deletions of shared entities.

🔹 Key points about cascade:
✅ Makes entity graphs easier to persist, update, or delete.
✅ Should match your business rules: e.g., deleting an order should also delete order lines? → use CascadeType.REMOVE.

✅ Key takeaway:
Cascade in Hibernate propagates operations from a parent entity to its associated entities, simplifying persistence and maintaining consistency — but requires careful design to avoid unintended side effects.

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

Java.Hibernate.Beginner. What is eager fetching?

Eager fetching means loading an association immediately along with the parent entity, so related entities are retrieved in the same query (if possible) or with additional immediate queries.
This is the opposite of lazy loading: instead of deferring, eager fetching ensures associated data is always available as soon as you load the parent.


🔹 How does it work?

  • When you fetch an entity with eager associations, Hibernate loads the entity and its eager associations together.
  • This avoids LazyInitializationException, because the data is loaded while the session is still open.
  • But it can also load a lot of unnecessary data, hurting performance for large graphs.

🔹 How to specify eager fetching:
Use the fetch attribute on association annotations:

@OneToMany(fetch = FetchType.EAGER)
private List<Order> orders;

🔹 What happens with eager fetch:
Example entity:

@Entity
public class User {
    @OneToMany(fetch = FetchType.EAGER)
    private List<Order> orders;
}

And when you load a User:

User user = session.get(User.class, 1L); // loads User + Orders immediately

✅ Hibernate either runs:

  • A join query to load user and orders together in one SQL, or
  • A batch of additional queries immediately to load the orders.
🔹 Why use eager fetching?
✅ Ensures associated data is always available, avoiding LazyInitializationException.
✅ Useful when you always know you’ll need the associated data.

🔹 Why not always use it?
❌ Can load large object graphs unnecessarily, especially with deeply nested relationships → increases memory usage and slows performance.
❌ More prone to N+1 query problems if you don’t design queries carefully.

🔹 Comparison:

FeatureLazy FetchingEager Fetching
Load timingLoads associations when accessedLoads associations immediately
PerformanceFaster initial load if associations unusedSlower if associations unused
RiskLazyInitializationException if session closedLoads unnecessary data

✅ Key takeaway:
Eager fetching loads associated entities up front with the parent entity, ensuring availability but risking performance issues if associations aren’t always needed.

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