Posts

Showing posts with the label Hibernate

Hibernate Interview Questions

 Load Vs Get load() get() Only use  load()  method if you are sure that the object exists. If you are not sure that the object exist, then use one of  get()  methods. load()  method will throw an exception if the unique id is not found in the database. get()  method will return null if the unique id is not found in the database. load()  just returns a proxy by default and database won't be hit until the proxy is first invoked. get()  will hit the database immediately.

Hibernate N+1 Problem

Image
The N+1 query problem is said to occur when an ORM, like hibernate, executes 1 query to retrieve the parent entity and N queries to retrieve the child entities. As the number of entities in the database increases, the queries being executed separately can easily affect the performance of the application. The relation between user_details and address is a one-many mapping from user_details(id) to address(user_id). That means a user can have many addresses. Public class UserDetails{   --- -.... @OneToMany(cascade = CascadeType.ALL, mappedBy = "userDetails") private List<Address> addresses; } Public class Address { --- ..... @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "user_id", referencedColumnName = "id") private UserDetails userDetails; } Now let us query for the name contains on user_details table with repository function. @Repository public interface UserDetailsRepository extends JpaRepository<UserDet...

Optimistic Vs Pessimistic Locking

 Optimistic locking The optimistic locking model, also referred to as optimistic concurrency control, is a concurrency control method used in relational databases that does not use record locking. Optimistic locking allows multiple users to attempt to update the same record without informing the users that others are also attempting to update the record. The record changes are validated only when the record is committed. If one user successfully updates the record, the other users attempting to commit their concurrent updates are informed that a conflict exists. An advantage of the optimistic locking model is that it avoids the overhead of locking a record for the duration of the action. If there are no simultaneous updates, then this model provides fast updates. Optimistic locking is a useful approach when concurrent record updates are expected to be infrequent or the locking overhead is high. In the Rational ClearQuest implementation of optimistic locking, when multiple users edi...