Java.Hibernate.Beginner.Explain what means bidirectional ? What’s difference to unidirectional ?

🔹 Bidirectional relationship
A bidirectional relationship means both entities know about each other in your Java model:

  • You can navigate the relationship from either side in your code.
  • Both entities have fields referencing each other.
  • Example: User has a UserProfile field, and UserProfile has a User field.

This makes it easy to traverse in both directions:

user.getProfile();
profile.getUser();

🔹 Unidirectional relationship
A unidirectional relationship means only one entity knows about the other:

  • Only one side has a field referencing the other entity.
  • You can navigate only in one direction in your code.
  • Example: User has UserProfile, but UserProfile has no reference back to User.

This limits navigation:

user.getProfile(); // works
profile.getUser(); // not possible → no user field

🔹 Practical example:

✅ Unidirectional

@Entity
public class User {
    @OneToOne
    @JoinColumn(name = "profile_id")
    private UserProfile profile; // User → UserProfile only
}

✅ Bidirectional

@Entity
public class User {
    @OneToOne(mappedBy = "user")
    private UserProfile profile;
}

@Entity
public class UserProfile {
    @OneToOne
    @JoinColumn(name = "user_id")
    private User user; // UserProfile → User
}

🔹 Database schema
🚫 There’s no difference in the physical database: whether you use unidirectional or bidirectional mapping, you still have a foreign key enforcing the relationship.

🔹 Key differences summarized:

AspectUnidirectionalBidirectional
NavigationOne side only (A → B)Both sides (A ↔ B)
Java mappingOne entity has a referenceBoth entities have references
Use caseSimpler, less codeNeeded when you must navigate both ways

✅ Key takeaway:

  • Unidirectional → simpler, but can navigate only one way.
  • Bidirectional → more flexible; you can navigate the relationship from either entity → recommended when both sides need to interact or need business logic involving both.
Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Explain what means bidirectional ? What’s difference to unidirectional ?

Java.Hibernate.Beginner.OneToOne.Bidirectional

A User entity has exactly one UserProfile, and each UserProfile belongs to exactly one User.

🔹 Entity 1: User

import javax.persistence.*;

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

    private String username;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private UserProfile profile;

    // Getters and setters
    public Long getId() { return id; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public UserProfile getProfile() { return profile; }
    public void setProfile(UserProfile profile) { this.profile = profile; }
}

🔹 Entity 2: UserProfile

import javax.persistence.*;

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

    private String address;

    @OneToOne
    @JoinColumn(name = "user_id") // foreign key column in user_profile table
    private User user;

    // Getters and setters
    public Long getId() { return id; }
    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }
    public User getUser() { return user; }
    public void setUser(User user) { this.user = user; }
}

🔹 What happens here:
✅ The UserProfile table has a foreign key column user_id referencing users.id.
✅ UserProfile owns the relationship because it has the @JoinColumn.
✅ In User, the @OneToOne(mappedBy = "user") points back to the user field in UserProfile → this makes UserProfile the owner and User the inverse side.

🔹 How to create and persist both sides:

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

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

UserProfile profile = new UserProfile();
profile.setAddress("123 Wonderland");

// Tie both sides of the bidirectional relationship
user.setProfile(profile);
profile.setUser(user);

session.persist(user); // cascade=ALL will persist UserProfile too

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

🔹 Important:
✅ Always set both sides of the bidirectional relationship (user.setProfile(profile) and profile.setUser(user)) to keep the in-memory model consistent.
✅ With cascade = CascadeType.ALL on User.profile, saving the User also saves the UserProfile.

✅ Key takeaway:
This example shows a bidirectional one-to-one where both User and UserProfile know each other → you can navigate in both directions in your domain model, and the database enforces the relationship via the foreign key.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.OneToOne.Bidirectional

Java.Hibernate.Beginner.What is one-to-one mapping in Hibernate?

A one-to-one mapping in Hibernate represents a relationship where one entity instance is associated with exactly one instance of another entity, and vice versa. It models a real-world scenario where two tables have a one-to-one relationship (e.g., User ↔ UserProfile).


🔹 Example scenario:
A User entity has exactly one UserProfile entity containing extra details like address, phone, etc.


🔹 How to map one-to-one in Hibernate:
Use JPA annotations @OneToOne along with @JoinColumn (for unidirectional) or mappedBy (for bidirectional) relationships.

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

    @OneToOne
    @JoinColumn(name = "profile_id") // foreign key in 'users' table
    private UserProfile profile;
}

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

🔹 Here:

  • The users table has a foreign key column profile_id referencing user_profile.id.
  • You can fetch the profile of a user with user.getProfile().

✅ Bidirectional one-to-one example:

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

    @OneToOne(mappedBy = "user")
    private UserProfile profile;
}

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

    @OneToOne
    @JoinColumn(name = "user_id") // foreign key in 'user_profile' table
    private User user;
}

🔹 Here:

  • Both entities can reference each other.
  • mappedBy on User points to UserProfile.user → establishes ownership on UserProfile.

🔹 Fetch type:
By default, @OneToOne uses FetchType.EAGER, meaning the related entity is loaded automatically with the owning entity. You can switch to LAZY if needed:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "profile_id")
private UserProfile profile;

🔹 Key points about one-to-one mapping:
✅ Models exclusive relationships → one row on one side corresponds to exactly one row on the other.
✅ Requires a unique foreign key constraint in the database for true one-to-one enforcement.
✅ Can be unidirectional (one entity references the other) or bidirectional (both reference each other).

✅ Key takeaway:
One-to-one mapping in Hibernate models exclusive relationships between two entities and maps them via @OneToOne, typically using foreign keys with unique constraints to enforce the relationship.

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

Java.Hibernate.Beginner.How can you use native SQL queries in Hibernate?

You can execute raw SQL queries directly against the database using Hibernate’s native query API, which lets you write standard SQL (not HQL/JPQL) — useful when you need database-specific features or want maximum control.


🔹 How to create a native query:
Use Session.createNativeQuery() (Hibernate) or EntityManager.createNativeQuery() (JPA) to run a SQL statement.


🔹 Example: fetching results as entities

Session session = sessionFactory.openSession();

String sql = "SELECT * FROM users WHERE username = :username";
User user = session.createNativeQuery(sql, User.class)
                   .setParameter("username", "alice")
                   .uniqueResult();

System.out.println("User email: " + user.getEmail());

session.close();

✅ Here:

  • createNativeQuery(sql, User.class) tells Hibernate to map the SQL result rows to your User entity.

🔹 Example: fetching scalar values (plain columns)

Session session = sessionFactory.openSession();

String sql = "SELECT username, email FROM users WHERE active = true";
List<Object[]> results = session.createNativeQuery(sql).list();

for (Object[] row : results) {
    System.out.println("Username: " + row[0] + ", Email: " + row[1]);
}

session.close();

🔹 Example with JPA’s EntityManager

String sql = "SELECT * FROM users WHERE id = ?";
User user = entityManager.createNativeQuery(sql, User.class)
                         .setParameter(1, 1L)
                         .getSingleResult();

🔹 Benefits of native SQL:
✅ Full power of SQL, including vendor-specific functions or hints.
✅ Can call stored procedures.
✅ Useful for reporting queries not easily expressed in HQL/JPQL.

🔹 Drawbacks:
❌ Loses portability — ties your query to the specific database’s SQL dialect.
❌ Bypasses some Hibernate optimizations (e.g., caching or automatic dirty checking).
❌ You’re responsible for correctly mapping results.

✅ Key takeaway:
Use createNativeQuery() when you need raw SQL for advanced or vendor-specific queries — but prefer HQL/JPQL for most CRUD to keep your app database-independent.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How can you use native SQL queries in Hibernate?

Java.Hibernate.Beginner.How can i understad that i use HQL or JPQL ?

🔹 1️⃣ Context of your project

  • JPQL is used if you’re working with JPA (javax.persistence / jakarta.persistence), e.g.:
    • Your project uses JPA annotations (@Entity, @Id, etc.).
    • You create queries using EntityManager.createQuery().
    • You rely on JPA-standard features like @PersistenceContext, @Transactional.

HQL is used if you’re directly working with native Hibernate API, e.g.:

  • Your code uses org.hibernate.Session.createQuery().
  • You don’t use JPA’s EntityManager.

🔹 2️⃣ How you build queries
✅ JPQL

TypedQuery<User> query = entityManager.createQuery(
    "SELECT u FROM User u WHERE u.username = :username", User.class);

Uses JPA EntityManager.

Always JPQL.

✅ HQL

List<User> users = session.createQuery(
    "FROM User u WHERE u.username = :username", User.class).list();

Uses Hibernate Session.

Always HQL.

🔹 3️⃣ Query features

  • If your queries use Hibernate-specific syntax or functions (e.g., index(), elements(), or certain proprietary operators), that’s HQL — JPQL won’t recognize them.

🔹 4️⃣ Are you using JPA-only annotations?

  • If your project uses javax.persistence.EntityManager instead of org.hibernate.Session, you’re definitely in JPQL-land.

🔹 5️⃣ Tools & providers

  • If you run your queries in Spring Data JPA repositories, your @Query strings are JPQL.
  • If you run your queries directly on Hibernate’s Session API, they’re HQL.

🔹 Bottom line:
✅ JPQL → you use JPA’s EntityManager or @Query in Spring Data JPA → fully portable.
✅ HQL → you use Hibernate’s Session API directly → Hibernate-specific.


🔹 Key takeaway:
The simplest way to know:

  • EntityManager → JPQL
  • Session → HQL
Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.How can i understad that i use HQL or JPQL ?

Java.Hibernate.Beginner.What is the difference between HQL and JPQL?

🔹 HQL (Hibernate Query Language)
✅ Hibernate’s own object-oriented query language.
✅ Introduced before the JPA standard existed.
✅ Very similar to JPQL in syntax, but includes Hibernate-specific features, like:

  • Support for querying Hibernate-specific features (e.g., some collection mappings).
  • Functions that might not exist in JPA (e.g., current_timestamp() in HQL but not JPQL).
    ✅ Not guaranteed to be portable across JPA providers (HQL-specific queries might fail on EclipseLink or OpenJPA).

🔹 JPQL (Java Persistence Query Language)
✅ The standardized object-oriented query language defined by JPA (Java Persistence API).
✅ Syntax and concepts are nearly identical to HQL → queries entities and their properties instead of tables.
✅ Designed to be portable across any JPA provider, e.g., Hibernate, EclipseLink, OpenJPA.
✅ Does not include Hibernate-specific extensions.

🔹 Key similarities:
✅ Both query entities, not tables.
✅ Both are object-oriented and support joins, subqueries, group by, aggregation, etc.
✅ Both use entity class names and field names instead of table and column names.


🔹 Key differences summarized:

FeatureHQLJPQL
Defined byHibernate-specificJPA specification
PortabilityNot guaranteedPortable across JPA providers
FeaturesHibernate-only extensionsLimited to JPA standard
SyntaxNearly identical to JPQLNearly identical to HQL

🔹 Example (same for both HQL and JPQL):

String query = "SELECT u FROM User u WHERE u.username = :username";
TypedQuery<User> typedQuery = entityManager.createQuery(query, User.class);
typedQuery.setParameter("username", "john");
List<User> users = typedQuery.getResultList();

🔹 When should you use which?
✅ In Hibernate-specific projects without JPA → HQL is fine.
✅ In JPA-based projects (e.g., Spring Data JPA) → always use JPQL for full portability.

HQL and JPQL are almost identical in syntax and purpose, but JPQL is the JPA-standard, portable query language; HQL is Hibernate-specific and may include non-portable features.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is the difference between HQL and JPQL?

Java.Hibernate.Beginner.What is the difference between HQL and SQL?

🔹 HQL (Hibernate Query Language)
✅ Object-oriented query language → queries are written against Java entities and their properties, not database tables or columns.
✅ Portable → Hibernate translates HQL into database-specific SQL, so you can switch databases without changing your queries.
✅ Database-agnostic → doesn’t rely on vendor-specific SQL features.
✅ Supports polymorphism → you can query superclasses and retrieve subclass instances.
✅ Uses Java class names and field names (e.g., FROM User WHERE username = :username).

🔹 SQL (Structured Query Language)
✅ Traditional, vendor-specific language used directly with relational databases.
✅ Written against physical tables and columns, not entities → tightly coupled to the database schema.
✅ Portable only if you avoid vendor-specific SQL features (which is rare in practice).
✅ Doesn’t understand object-oriented concepts like inheritance or relationships in your Java model.
✅ Example: SELECT * FROM users WHERE username = ?.

🔹 Key differences summarized:

FeatureHQLSQL
Operates onEntities & fields (OOP)Tables & columns (DB)
PortabilityDatabase-independentVendor-dependent
TranslationConverted to SQL by HibernateSent directly to DB
Object conceptsSupports polymorphism, relationshipsNo awareness of OOP
Use caseWorks with Hibernate entitiesDirect DB operations, reports

🔹 Example: same query in both:

✅ HQL

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

✅ SQL

String sql = "SELECT * FROM users WHERE username = ?";
session.createNativeQuery(sql)
       .setParameter(1, "john")
       .list();

🔹 When to use which?
✅ HQL → recommended for most Hibernate-based CRUD and complex queries involving entities.
✅ SQL → useful when you need database-specific features (e.g., vendor functions, stored procedures) or reporting queries not easily mapped to your object model.

✅ Key takeaway:
HQL is object-oriented, portable, and designed for querying mapped entities, while SQL is table-based, database-specific, and works directly on the physical schema.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.What is the difference between HQL and SQL?

Java.Hibernate.Beginner.Explain how can i change criteria api in run time, what does it mean ?

Answer:
Changing Criteria API at runtime means you can build queries dynamically based on conditions only known during execution (e.g., user input, UI filters, request parameters) instead of writing fixed, hardcoded queries.

🔹 Why is this important?

  • In real apps, search screens often let users specify any combination of filters (e.g., by username, email, status).
  • You don’t want to write separate queries for every combination → you want one flexible query that adjusts based on which filters are provided at runtime.

🔹 How do you do it?
You conditionally add predicates to the Criteria query during runtime, depending on which filter values are present.


🔹 Example: runtime criteria building
Imagine a search form where the user can enter optional filters:

  • username
  • email
  • active status
public List<User> searchUsers(String username, String email, Boolean active) {
    Session session = sessionFactory.openSession();
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> root = cq.from(User.class);

    List<Predicate> predicates = new ArrayList<>();

    // Add filters dynamically depending on provided values:
    if (username != null && !username.isEmpty()) {
        predicates.add(cb.equal(root.get("username"), username));
    }
    if (email != null && !email.isEmpty()) {
        predicates.add(cb.like(root.get("email"), "%" + email + "%"));
    }
    if (active != null) {
        predicates.add(cb.equal(root.get("active"), active));
    }

    // Combine predicates using AND
    cq.select(root).where(cb.and(predicates.toArray(new Predicate[0])));

    List<User> results = session.createQuery(cq).getResultList();
    session.close();
    return results;
}

🔹 What’s happening at runtime?
✅ Only the filters actually provided by the caller are included in the final SQL query.
✅ If a user doesn’t specify email, it’s not part of the WHERE clause.
✅ This lets you handle all combinations of filters with a single Criteria-based method.


🔹 Key benefit:
You avoid:
❌ Writing dozens of HQL/SQL variants manually.
✅ Instead, you dynamically build exactly the query needed at runtime, depending on available inputs.


✅ Key takeaway:
Changing Criteria API at runtime means conditionally adding or modifying query parts on the fly, letting you handle flexible, user-driven searches or reports with a single, maintainable query builder.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Explain how can i change criteria api in run time, what does it mean ?

Java.Hibernate.Beginner.What is the Criteria API in Hibernate?

The Criteria API in Hibernate is an object-oriented, programmatic way to build dynamic queries — instead of writing HQL or SQL strings manually, you construct queries using Java objects and method calls.

🔹 Why use Criteria API?
✅ Useful when you need to build dynamic queries at runtime, where conditions, joins, or projections depend on user input or other variables.
✅ Provides type safety — you avoid typos in HQL/SQL strings because the compiler checks your Java code.
✅ Easier to read and maintain for complex or dynamic queries.

🔹 How does it work?

  • Hibernate offers two types of Criteria APIs:
    • Legacy Criteria API (Criteria class in Hibernate 5 and earlier) — considered deprecated.
    • JPA Criteria API (CriteriaBuilder, CriteriaQuery) — standard in JPA 2.0+ and recommended today.

🔹 Basic example using JPA Criteria API:

Session session = sessionFactory.openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();

CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class);

// Add where clause: username = "alice"
cq.select(root).where(cb.equal(root.get("username"), "alice"));

User user = session.createQuery(cq).uniqueResult();

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

session.close();

✅ Here:

  • CriteriaBuilder creates a type-safe query plan.
  • CriteriaQuery represents the query.
  • Root<User> defines the entity to query.
  • cb.equal(...) builds conditions dynamically.

🔹 Benefits of Criteria API:
✅ Fully dynamic → you can add conditions, joins, orderings at runtime.
✅ Type-safe → compiler catches mistakes with field names or types.
✅ Standard JPA API → works across all JPA providers, not just Hibernate.

🔹 Use case examples:

  • Building advanced search screens with many optional filters.
  • Generating reports with different filters, sorting, and grouping options.
  • Creating reusable query builders in your data access layer.

✅ Key takeaway:
The Criteria API lets you build dynamic, type-safe queries using Java objects, making it ideal for complex or runtime-generated queries — and it avoids fragile HQL or SQL string concatenation.

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

Java.Hibernate.Beginner.Explain Polymorphic queries and give examples

Polymorphic queries in Hibernate mean you can query a superclass entity and automatically retrieve instances of all its subclasses — without explicitly mentioning each subclass.
This happens because Hibernate maps your Java inheritance hierarchy, and HQL supports it natively.

🔹 When does it matter?

  • When you have an inheritance strategy in your entity model (e.g., single-table, joined, or table-per-class), and you want to fetch all entities of a base type, including any subclasses.

🔹 Example inheritance:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Animal {
    @Id
    private Long id;
    private String name;
}

@Entity
public class Dog extends Animal {
    private String breed;
}

@Entity
public class Cat extends Animal {
    private String color;
}

🔹 Polymorphic query example:
Fetch all animals, regardless of subclass:

Session session = sessionFactory.openSession();

String hql = "FROM Animal"; // polymorphic: returns Dogs + Cats

List<Animal> animals = session.createQuery(hql, Animal.class).list();

for (Animal animal : animals) {
    System.out.println(animal.getName());
    if (animal instanceof Dog) {
        System.out.println("Dog breed: " + ((Dog) animal).getBreed());
    } else if (animal instanceof Cat) {
        System.out.println("Cat color: " + ((Cat) animal).getColor());
    }
}

session.close();

✅ Here, Hibernate executes a single HQL query on the Animal base type → but it returns a mixed list of Dog and Cat entities.

🔹 Why is this powerful?
✅ You don’t need separate queries for each subclass.
✅ Maintains object-oriented behavior → lets you work naturally with inheritance in your domain model.
✅ Database schema complexities (e.g., joined tables) are abstracted away by Hibernate.

🔹 Key point:
Polymorphic queries work automatically with all Hibernate inheritance strategies:

  • Single table
  • Joined tables
  • Table-per-class

With HQL, polymorphic queries let you query a superclass and retrieve instances of all mapped subclasses, seamlessly integrating your object-oriented design with your relational database.

Posted in Без рубрики | Comments Off on Java.Hibernate.Beginner.Explain Polymorphic queries and give examples