Skip to main content

11 - JPA/Hibernate Interview Questions

Why Hibernate?
Answer : In Short it helps you solve some problem which indirectly comes when you are using JDBC
1. Help you to avoid lots of boilerplate code.
2. Helps you to avoid doing any Connection Management and Transaction Management explicitly.
3. Helps you DB Developer to do exciting things rather than helping the Junior or Mid Level engineer for writing native query.
4. It creates two way data binding between your table and POJO i.e. any change in POJOs's reflects in db table and any changes in db table reflects in application POJO, i.e. objectifies the data layer.
5. Future Proof : Very minimal effort needed to migrate the one database type to another.
6. When you want to do lot of business operation on your POJO's, and you want those POJO's to be handy.


When Not to use Hibernate?
Answer : Few points to be seen before introducing the Hibernate into your application
1. If you do not have Persistence Layer, there is no use of Hibernate.
2. Legacy database, if most of the rules are written in the database and there is very less what hibernate is required to do apart from directly calling those stored procedures and Function.
3. Complex Query: If you need to call very complex query all the time, and require lot of aggregate function call like MIN Max and group by manipulation all the time, even though we have native Query call support but at the end we may loose one of the advantage of having database portability.
4.When your database is not huge and complex, e.g. 8-10 tables with not much relation between them.

What if the @Entity is without any Name?
Answer : Then by default class name will be taken as entity name(Case Sensitive) and also the table name present in the DB should be same. E.g.
@Entity
public class Employee {

So we have to write HQL Like "from Employee" but if we write HQL like "from employee" then it will not work since entity name is case sensitive, additionally there has to be a table with the name "Employee" not case sensitive.

Note : @Entity is required otherwise the bean will not be registered for the Hibernate Container.

What is the use of @Table?
Answer : If the table name is not same as the entity name then we can use the @Table annotation

What are the option to pass the configuration file for the hibernate while creating the sessionFactory?
Answer : Below is pictorial representation.






Question : Give example of the Sequence Generator?
Answer  : Below is the example of sequence generator
@GeneratedValue(generator = "SEC_SERVICE_ID", strategy = GenerationType.SEQUENCE)
       @SequenceGenerator(name = "SEC_SERVICE_ID", sequenceName = "CLIQAPP.SERVICE_ID_SEQ",allocationSize=1)
       @Column(name="SERVICE_ID") public Long serviceId;

Question : Example of unidirectional many to one
Answer : 
@Entity(name="cliqServiceInfo")
@Table(name="CLIQ_SERVICE_INFO")
public class CliqServiceInfo {
@Id
@GeneratedValue(generator = "SEC_SERVICE_ID", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "SEC_SERVICE_ID", sequenceName = "CLIQAPP.SERVICE_ID_SEQ",allocationSize=1)
@Column(name="SERVICE_ID") public Long serviceId;

@ManyToOne
@JoinColumn(name="VENDOR_ID"public CliqVendorInfoIdName cliqVendorInfoIdName;
name :  of the foreign key column. The table in which it is found depends upon the context.
  • If the join is for a OneToOne or ManyToOne mapping using a foreign key mapping strategy, the foreign key column is in the table of the source entity or embeddable.
  • If the join is for a unidirectional OneToMany mapping using a foreign key mapping strategy, the foreign key is in the table of the target entity.
  • If the join is for a ManyToMany mapping or for a OneToOne or bidirectional ManyToOne/OneToMany mapping using a join table, the foreign key is in a join table.
  • If the join is for an element collection, the foreign key is in a collection table.
Default (only applies if a single join column is used): The concatenation of the following: the name of the referencing relationship property or field of the referencing entity or embeddable class; "_"; the name of the referenced primary key column. If there is no such referencing relationship property or field in the entity, or if the join is for an element collection, the join column name is formed as the concatenation of the following: the name of the entity; "_"; the name of the referenced primary key column.

Question : What is the mappedSuperclass and give the example
Answer :

@MappedSuperclass
public class CliqBaseVendorInfo {
       @Id
       @GeneratedValue(generator = "SEC_ODON", strategy = GenerationType.SEQUENCE)
       @SequenceGenerator(name = "SEC_ODON"
                          sequenceName = "CLIQAPP.VENDOR_ID_SEQ",allocationSize=1)
       @Column(name="VENDOR_ID")
       protected Long vendorId;

       @Column(name="NAME")
       protected String name;

       /**
        * @return the vendorId
        */
       public Long getVendorId() {
              return vendorId;
       }
Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.
A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself. When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. Mapping information may be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.


Explain diffrent key generation stretegy?
Answer :
hilo—Uses an extra table named HIBERNATE_UNIQUE_KEY with the same algorithm as the seqhilo strategy. The table has a single column and row, holding the next value of the sequence. The default maximum lo value is 32767, so you most likely want to configure it with the max_lo parameter. See the Javadoc for the class org.hibernate.id.TableHiLoGenerator for more information. We don’t recommend this legacy strategy; use enhanced-sequence instead with an optimizer.

enhanced-table—Uses an extra table named HIBERNATE_SEQUENCES, with one row by default representing the sequence, storing the next value. This value is selected and updated when an identifier value has to be generated. You can configure this generator to use multiple rows instead: one for each generator; see the Javadoc for org.hibernate.id.enhanced.TableGenerator. Equivalent
to JPA GenerationType.TABLE with the New mapping enabled. Replaces the outdated but similar org.hibernate.id.MultipleHiLoPerTableGenerator, which is the Old mapping for JPA GenerationType.TABLE.

identity—Supports IDENTITY and auto-increment columns in DB2, MySQL, MS SQL Server, and Sybase. The identifier value for the primary key column will be generated on INSERT of a row. Has no options. Unfortunately, due to a quirk in Hibernate’s code, you can not configure this strategy in @GenericGenerator. The only way to use it is with JPA GenerationType.IDENTITY and the Old or
New mapping, making it the default for GenerationType.IDENTITY.

increment—At Hibernate startup, reads the maximum (numeric) primary key column value of each entity’s table and increments the value by one each time a new row is inserted. Especially efficient if a non-clustered Hibernate application has exclusive access to the database; but don’t use it in any other scenario.

select—Hibernate won’t generate a key value or include the primary key column in an INSERT statement. Hibernate expects the DBMS to assign a (default in schema or by trigger) value to the column on insertion. Hibernate then retrieves the primary key column with a SELECT query after insertion. Required parameter is key, naming the database identifier property (such as id) for theSELECT. This strategy isn’t very efficient and should only be used with old JDBC drivers that can’t return generated keys directly.

uuid2—Produces a unique 128-bit UUID in the application layer. Useful when you need globally unique identifiers across databases (say, you merge data from several distinct production databases in batch runs every night into an archive). The UUID can be encoded either as a java.lang.String, a byte[16], or a java .util.UUID property in your entity class. Replaces the legacy uuid and uuid
.hex strategies. You configure it with an org.hibernate.id.UUIDGenerationStrategy; see the Javadoc for the class org.hibernate.id.UUIDGenerator for more details.

guid—Uses a globally unique identifier produced by the database, with an SQL function available on Oracle, Ingres, MS SQL Server, and MySQL. Hibernate calls the database function before an INSERT. Maps to a java.lang.String identifier property. If you need full control over identifier generation, configure the strategy of @GenericGenerator with the fully qualified name of a class
that implements the org.hibernate.id.IdentityGenerator interface

Question :  Can we create two class pointing to the same table?
Answer : Yes, only thing is the entity name has to be different.

What is advantage and disadvantages of namedQuery?
Answer :
Advantages
compiled and validated at app start-up time
easier to maintain than string literals embedded in your code
HQL and native SQL queries can be used and replaced without code changes (no need to re-compile your code)

Disadvantages
static
result-set mapping with native SQL queries sometimes cumbersome
So, I think you should definitely prefer named queries over string literals in your code. When you need some kind of dynamic query creation at runtime you should take a look at the Hibernate Criteria API.

What is use of subselect?
Answer : Sometimes your DBA won’t allow you to change the database schema; even adding a new view might not be possible. Let’s say you want to create a view that contains the identifier of an auction Item and the number of bids made for that item.
@Entity
@Subselect(value="select t from table t")
@Synchronize({"table"})
class Table{
      
}

Using a Hibernate annotation, you can create an application-level view, a read-only entity class mapped to an SQL SELECT:
When an instance of Table is loaded, Hibernate executes your custom SQL SELECT as a subselect:
You should list all table names referenced in your SELECT in the @org.hibernate .annotations.Synchronize annotation. (At the time of writing, Hibernate has a bug tracked under issue HHH-84301 that makes the synchronized table names case sensitive.) Hibernate will then know it has to flush modifications of Item and Bid instances before it executes a query against ItemBidSummary:

Question : How to avoid storing the field data which are not mapped to the database column?
Answer : By default everything is treated as the column, even if you have not annotated the property or field with @Column, so in hibernate or java we have two option @javax.persistence.Transient annotation or use the Java transient keyword.

Question : What are the ways to indicate a column is having not null constraint at the hibernate/jpa level?
Answer :  There are three ways to declare whether a property value is required: with the @Basic (optional = false) annotation, the @Column( nullable=false ) annotation, and also with the Bean Validation @NotNull.

What is Temporal and what is the use of it?
Answer : This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

@Temporal(DATE)
protected java.util.Date endDate;

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (ie the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date / time or both(TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that convert back and forth between time-stamp and java util date. It also convert time-stamp into time. For example, in below snippet , ?@Temporal(TemporalType.DATE)? drops the time value and only preserves the date

@Temporal(TemporalType.DATE)
@Column(name="CREATION_DATE")
private java.util.Date date;

Question : What is enumerated type?
Answer : An enumeration type is a common Java idiom where a class has a constant (small) number of immutable instances. In CaveatEmptor, for example, you can apply this to auctions:
public enum AuctionType {
HIGHEST_BID,
LOWEST_BID,
FIXED_PRICE
}

You can now set the appropriate auctionType on each Item:
@NotNull
@Enumerated(EnumType.STRING)
protected AuctionType auctionType = AuctionType.HIGHEST_BID;


Question : What is AttributeOverride?
Answer : If we want to override any attribute from the mapped super class then we can use this annotation.

@AttributeOverride(
name = "owner",
column = @Column(name = "CC_OWNER", nullable = false))
//The class extending mapped super class BillingDetails
public class CreditCard extends BillingDetails {

}

Question : What InheritanceType.TABLE_PER_CLASS inheritance stretegy?
Answer : InheritanceType.TABLE_PER_CLASS : A table per concrete entity class, i.e. each class extending will be representing a separate table.

Question : What is the difference between InheritanceType.TABLE_PER_CLASS  and @mappedSuperClass?
Answer : There can not be table directly related to the mapped super class, but there can be a concrete table corresponding to the InheritanceType.TABLE_PER_CLASS.
in case of
@MappedSuperclass
public class CliqBaseVendorInfo {
}
The id is optional and can provided at the base class level, but in case of

@Entity(name="cliqServiceInfo")
@Table(name="CLIQ_SERVICE_INFO")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class CliqServiceInfo {
}

The Id has to be present it is no longer optional.

Question : Give the example of the SINGLE Table Hierarchy and Discriminator?
Answer :
Main Class
@Entity
@Table(name="CLIQ_COMMENTS")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE
@DiscriminatorColumn(name="COMMENT_TYPE",discriminatorType=DiscriminatorType.STRING, length=1)
@DiscriminatorOptions(force=true)
@ForceDiscriminator
public class CliqComments {
       @Id
       @GeneratedValue(generator = "SEC_CLIQ_COMMENTS", strategy = GenerationType.SEQUENCE)
       @SequenceGenerator(name = "SEC_CLIQ_COMMENTS",
                          sequenceName = "CLIQAPP.COMMENT_ID_SEQ",allocationSize=1)
       @Column(name="COMMENT_ID") private Long commentId;


Child Class - 1
/**
 *
 * @author vikmishr
 *
 * See Parent class for more details, the data will go to CLIQ_COMMENTS with the        *  comment type as 2 which means the comment is for the service not the vendor
 */
@Entity 
@DiscriminatorValue("2"
public class ServiceComments extends CliqComments{}

Child Class - 2
/**
 *
 * @author vikmishr
 *
 * See Parent class for more details, the data will go to CLIQ_COMMENTS with the 
 * comment type as 1 which means the comment is for the vendor not the service
 */
@Entity 
@DiscriminatorValue("1"
public class VendorComments extends CliqComments{

}
Question : Who decides the column which will participate as the discriminator column.
Answer : The annotation @DiscriminatorColumn will decide the column in the table which will participate as the deciding column to determine the type of the data.

@DiscriminatorColumn(name="COMMENT_TYPE",discriminatorType=DiscriminatorType.STRING, length=1)

Without an explicit discriminator value, Hibernate defaults to the fully qualified class name if you use Hibernate XML files and the simple entity name if you use annotations or JPA XML files. Note that JPA doesn’t specify a default for non-string discriminator types; each persistence provider can have different defaults. Therefore, you should always specify discriminator values for your concrete classes.
Annotate every subclass with @Entity, and then map properties of a subclass to columns in the BILLINGDETAILS table. Remember that NOT NULL constraints aren’t allowed in the schema, because a BankAccount instance won’t have an expMonth property, and the EXPMONTH column must be NULL for that row. Hibernate ignores the @NotNull for schema DDL generation, but it observes it at runtime, before inserting a row. This helps you avoid programming errors; you don’t want to accidentally save credit card data without its expiration date. (Other, less well-behaved applications can of course still store incorrect data in this database.)

Question : What is the diff between @Embeddable and @mappedSuperClass?
Answer : The first is meant for composition relationship and the later one meant for the inheritance relationships.
Example of the Embaddeble.

@Embeddable 
public class EmploymentPeriod {
  @Column(name="START_DATE")
  private java.sql.Date startDate;

  @Column(name="END_DATE")
  private java.sql.Date endDate;
  ....
}


@Entity
public class Employee {
  @Id
  private long id;
  ...
  @Embedded
  private EmploymentPeriod period;
  ...
}



Question : What is the difference between using a @OneToMany and @ElementCollection annotation since both work on the one-to-many relationship?
Answer : 

Question : What is the dfault fetch type for the ManyToOne?
Answer : it's Eager.

Question : What is EmbeddedId?
Answer : applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. The embeddable class must be annotated as Embeddable. There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used. The AttributeOverride annotation may be used to override the column mappings declared within the embeddable class. The MapsId annotation may be used in conjunction with the EmbeddedId annotation to specify a derived primary key.
If the entity has a derived primary key, the AttributeOverride annotation may only be used to override those attributes of the embedded id that do not correspond to the relationship to the parent entity.
Relationship mappings defined within an embedded id class are not supported.
    Example 1:

    @EmbeddedId
    protected EmployeePK empPK;

    Example 2:

    @Embeddable
    public class DependentId {
       String name;
       EmployeeId empPK;   // corresponds to primary key type of Employee
    }

    @Entity
    public class Dependent {
       // default column name for "name" attribute is overridden
       @AttributeOverride(name="name", @Column(name="dep_name"))
       @EmbeddedId DependentId id;
       ...
       @MapsId("empPK")
       @ManyToOne Employee emp;
    }
 

Question : What is @PrimaryKeyJoinColumn?
Answer : Specifies a primary key column that is used as a foreign key to join to another table.
It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.
If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.
    Example: Customer and ValuedCustomer subclass

    @Entity
    @Table(name="CUST")
    @Inheritance(strategy=JOINED)
    @DiscriminatorValue("CUST")
    public class Customer { ... }

    @Entity
    @Table(name="VCUST")
    @DiscriminatorValue("VCUST")
    @PrimaryKeyJoinColumn(name="CUST_ID")
    public class ValuedCustomer extends Customer { ... }

Question : Give the example of the JoinTable?
Answer : 
@Entity
public class Shipment {
@OneToOne(fetch = FetchType.LAZY)
@JoinTable(
name = "ITEM_SHIPMENT",
joinColumns =
@JoinColumn(name = "SHIPMENT_ID"),
inverseJoinColumns =
@JoinColumn(name = "ITEM_ID",
nullable = false,
unique = true)
)
protected Item auction;


What are the persistent states of the entity?
Answer : Below are the details for the 

TRANSIENT STATE
Instances created with the new Java operator are transient, which means their state is lost and garbage-collected as soon as they’re no longer referenced. For example, new Item() creates a transient instance of the Item class, just like new Long() and new BigDecimal(). Hibernate doesn’t provide any rollback functionality for transient instances; if you modify the price of a transient Item, you can’t automatically undo the change.
For an entity instance to transition from transient to persistent state, to become managed, requires either a call to the EntityManager#persist() method or the creation of a reference from an already-persistent instance and enabled cascading of state for that mapped association.

PERSISTENT STATE
A persistent entity instance has a representation in the database. It’s stored in the database—or it will be stored when the unit of work completes. It’s an instance with a database identity, as defined in section 4.2; its database identifier is set to the primary key value of the database representation.
The application may have created instances and then made them persistent by calling EntityManager#persist(). There may be instances that became persistent when the application created a reference to the object from another persistent instance that the JPA provider already manages. A persistent entity instance may be an instance retrieved from the database by execution of a query, by an identifier lookup, or by navigating the object graph starting from another persistent instance. Persistent instances are always associated with a persistence context. You see more about this in a moment.

REMOVED STATE
You can delete a persistent entity instance from the database in several ways: For example, you can remove it with EntityManager#remove(). It may also become available for deletion if you remove a reference to it from a mapped collection with orphan removal enabled.
An entity instance is then in the removed state: the provider will delete it at the end of a unit of work. You should discard any references you may hold to it in the application after you finish working with it for example, after you’ve rendered the removal confirmation screen your users see.

DETACHED STATE
To understand detached entity instances, consider loading an instance. You call EntityManager#find() to retrieve an entity instance by its (known) identifier. Then you end your unit of work and close the persistence context. The application still has a handle—a reference to the instance you loaded. It’s now in the detached state, and the data is becoming stale. You could discard the reference and let the garbage collector reclaim the memory. Or, you could continue working with the data in the detached state and later call the merge() method to save your modifications in a new unit of work.

Question : How to reattach the detached entity?
Answer : call the merge method to attache the detached entity.

Question : How to delete the detached entity from the persistence context?
Answer : If you want to delete a detached instance, you have to merge it first. Then call remove() on the persistent instance returned by merge().

Question : What is lost update ?
Answer : A lost update occurs if two transactions both update a data item and then the second transaction aborts, causing both changes to be lost. This occurs in systems that don’t implement concurrency control, where concurrent transactions aren’t isolated.

Question : What is Dirty read ? 
Answer : A dirty read occurs if a transaction reads changes made by another transaction that hasn’t yet been committed. This is dangerous because the changes made by the other transaction may later be rolled back, and invalid data may be written by the first transaction;

Question : What is An unrepeatable?
Answer : An unrepeatable read occurs if a transaction reads a data item twice and reads different state each time. For example, another transaction may have written to the data item and committed between the two reads.
A special case of an unrepeatable read is the last commit wins problem. Imagine that two concurrent transactions both read a data item, as shown in figure 11.4. One writes to it and commits, and then the second writes to it and commits. The changes made by the first writer are lost. This issue is especially frustrating for users: user A’s changes are overwritten without warning, and B has potentially made a decision based on outdated information.

Question : What is Phantom read?
Answer : A phantom read is said to occur when a transaction executes a query twice, and the second result includes data that wasn’t visible in the first result or less data because something was deleted. It need not necessarily be exactly the same query. Another transaction inserting or deleting data between the executions of the two queries causes this situation,

Question : What is Read uncommitted isolation?
Answer : A system that permits dirty reads but not lost updates operates in read uncommitted isolation. One transaction may not write to a row if another uncommitted transaction has already written to it. Any transaction may read any row, however. A DBMS may implement this isolation level with exclusive write locks.

Question : What is Read committed isolation?
Answer : A system that permits unrepeatable reads but not dirty reads implements read committed isolation. A DBMS may achieve this by using shared read locks and exclusive write locks. Reading transactions don’t block other transactions from accessing a row, but an uncommitted writing transaction blocks all other transactions from accessing the row.

Question : What is Repeatable read isolation?
Answer : A system operating in repeatable read isolation mode permits neither unrepeatable reads nor dirty reads. Phantom reads may occur. Reading transactions block writing transactions but not other reading transactions, and writing transactions block all other transactions.

Question : What is Serializable isolation? 
Answer : The strictest isolation, serializable, emulates serial execution, as if transactions were executed one after another, rather than concurrently. A DBMS may not implement serializable using only row-level locks. A DBMS must instead provide some other mechanism that prevents a newly inserted row from becoming visible to a transaction that has already executed a query that would return the row. A crude mechanism is exclusively locking the entire database table after a write, so no phantom reads can occur.

Question : Explain the optimistic lock using @Version in JPA/Hibernate?
Answer : We can enable versioning with an @Version annotation on a special additional property of our entity class, as shown below.
@Entity
public class Item implements Serializable {
@Version
protected long version;
// ...
}

In this example, each entity instance carries a numeric version. It’s mapped to an additional column of the ITEM database table; as usual, the column name defaults to the property name, here VERSION. The actual name of the property and column doesn’t matter—you could rename it if VERSION is a reserved keyword in your DBMS.
You could add a getVersion() method to the class, but you shouldn’t have a setter method and the application shouldn’t modify the value. Hibernate automatically changes the version value: it increments the version number whenever an Item instance has been found dirty during flushing of the persistence context. The version is a simple counter without any useful semantic value beyond concurrency control. You can use an int, an Integer, a short, a Short, or a Long instead of a long; Hibernate wraps and starts from zero again if the version number reaches the limit of the data type
steps followed during the optimistic lock,
Retrieving an entity instance by identifier loads the current version from the database with a SELECT.
C The current version of the Item instance is 0.
D When the persistence context is flushed, Hibernate detects the dirty Item instance and increments its version to 1. SQL UPDATE now performs the version check, storing the new version in the database, but only if the database version is still 0.
in particular the UPDATE and its WHERE clause. This update will be successful only if there is a row with VERSION = 0 in the database. JDBC returns the number of updated rows to Hibernate; if that result is zero, it means the ITEM row is either gone or doesn’t have the version 0 anymore. Hibernate detects this conflict during flushing, and a javax.persistence.OptimisticLockException is thrown.




What is Propagation.REQUIRED property
Answer :  It is the default value for transactions that do not specify a propagation setting. This property supports a current transaction if one exists or creates a new one if none exists. This ensures that the Propagation.REQUIRED annotated method will always have a valid transaction available and should be used whenever the data is modified in the persistence storage. This property is usually combined with readOnly=false.

The Propagation.SUPPORTS property
This property supports a current transaction if one exists or executes non-transactionally if none exists. The Propagation.SUPPORTS property should be used if the annotated method does not modify the data (will not execute an insert, update, or delete statement against the database). This property is usually combined with readOnly=true.

The readOnly property
This just serves as a hint for the actual transaction subsystem to allow optimization of executed statements if possible. It may be possible that the transaction manager may not be able to interpret this property. For self-documenting code, however, it is a good practice to include this property.

Other transaction properties
Spring allows us to fine-tune transactional properties with additional options that are beyond the scope of this book. Browse the link that was mentioned earlier to find out more about how transactions can be managed in more complex scenarios including multiple transactional resources.

What is the difference between UniqueResult() and SingleResult()?
They are mostly equivalent, but uniqueResult throws an Exception when more than one result row is returned. singleResult just returns the first and doesn't care whether multiple rows match.


Question : What is flush?
Answer : Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:

1. before some query executions
2. when a transaction is committed
Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).




Comments

Popular posts from this blog

NodeJS

Question : Why You should use Node JS? Answer :  Following are the major factor influencing the use of the NodeJS Popularity : The popularity can be important factor, as it has more user base and hence solution  of any common problem faced by developer can found easily online, without any professional help. JavaScript at all levels of the stack :  A common language for frontend and backend offers several potential benefits: The same programming staff can work on both ends of the wire Code can be migrated between server and client more easily Common data formats (JSON) exist between server and client Common software tools exist for server and client Common testing or quality reporting tools for server and client When writing web applications, view templates can be used on both sides Leveraging Google's investment in V8 Engine. Leaner, asynchronous, event-driven model Microservice architecture Question : example of node JS code? Answer :  const fs = require('fs'); const uti

Kubernetes

What is Kubernetes? Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem.  The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes combines over 15 years of Google’s experience running production workloads at scale with best-of-breed ideas and practices from the community. Why you need Kubernetes and what it can do? Containers are a good way to bundle and run your applications. In a production environment, you need to manage the containers that run the applications and ensure that there is no downtime. For example, if a container goes down, another container needs to start. Wouldn’t it be easier if this behavior was handled by a system? That’s how Kubernetes comes to the rescue! Kubernetes provides you with a framework to run distributed systems resi

Spring Interview Question - Version 3.5

Spring Overview Question :   What is Spring? Answer : Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO based programming model.   Question : What are benefits of Spring Framework? Answer :   Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.   Inversion of control (IOC) : Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.   Aspect oriented (AOP) : Spring supports Aspect oriented programming and separates application business logic from system services.   C