Sie sind auf Seite 1von 21

 What Is Jpa And Its Key Components?

 What Is The Difference Between Persistence.xml And Hibernate.cfg.xml?

When using JPA need persistence.xml and while using Hibernate API need hibernate.cfg.xml. When
using JPA or Hibernate not needed both xmls, need the xml configuration file according to JPA or
Hibernate.

 What Is An Entitymanager?

Entity manager javax.persistence.EntityManager provides the operations from and to the database,
e.g. find objects, persists them, remove objects from the database, etc. Entities which are managed
by an EntityManager will automatically propagate these changes to the database (if this happens
within a commit statement). These objects are known as persistent object. If the Entity Manager is
closed (via close()) then the managed entities are in a detached state. These are known as the
detached objects. If you want synchronize them again with the database, the a Entity Manager
provides the merge() method. Once merged, the object(s) becomes perstent objects again.

The EntityManager is the API of the persistence context, and an EntityManager can be injected
directly in to a DAO without requiring a JPA Template. The Spring Container is capable of acting as
a JPA container and of injecting the EntityManager by honoring the @PersistenceContext (both as
field-level and a method-level annotation).

Entity manager javax.persistence.EntityManager provides the operations from and to the database,
e.g. find objects, persists them, remove objects from the database, etc. Entities which are managed
by an EntityManager will automatically propagate these changes to the database (if this happens
within a commit statement). These objects are known as persistent object. If the Entity Manager is
closed (via close()) then the managed entities are in a detached state. These are known as the
detached objects. If you want synchronize them again with the database, the a Entity Manager
provides the merge() method. Once merged, the object(s) becomes perstent objects again.

The EntityManager is the API of the persistence context, and an EntityManager can be injected
directly in to a DAO without requiring a JPA Template. The Spring Container is capable of acting as
a JPA container and of injecting the EntityManager by honoring the @PersistenceContext (both as
field-level and a method-level annotation).

 What Is An Entity?

A class which should be persisted in a database it must be annotated with javax.persistence.Entity.


Such a class is called Entity. An instances of the class will be a row in the person table. So, the
columns in the person table will be mapped to the Person java object annotated as @Entity.

While insert, update or fetch record to or from the database we use entity as mapping with relational
tables.

 Why To Use Jpa?


Using JPA does not tie you to Hibernate. JPA gives you most of the features of plain old Hibernate,
except:

No criteria queries in JPA 2.0. Criteria query is a neat feature of Hibernate that constructs query
using Java-based combinators instead of alternate query language, getting the benefit of
IntelliSense and Eclipse’s refactoring tools.

JPA doesn’t have Hibernate’s DeleteOrphan cascade type.

Delete Orphan is a useful annotation that directs Hibernate to deletes entities in a collection if the
parent is deleted, preventing orphaning.

JPA doesn’t have an equivalent to Hibernate’s ScrollableResults.

 What Is Embeddable Classes?

Entities may use persistent fields, persistent properties, or a combination of both. If the mapping
annotations are applied to the entity’s instance variables, the entity uses persistent fields. If the
mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the
entity uses persistent properties.

 What Is Persistent Fields?

If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance
variables directly. All fields not annotated javax.persistence.Transient or not marked as Java
transient will be persisted to the data store. The object/relational mapping annotations must be
applied to the instance variables.

 What Is Persistent Properties?

If the entity uses persistent properties, the entity must follow the method conventions of JavaBeans
components. JavaBeans-style properties use getter and setter methods that are typically named
after the entity class’s instance variable names. For every persistent property property of type Type
of the entity, there is a getter method getProperty and setter method setProperty. If the property is a
Boolean, you may use isProperty instead of getProperty. For example, if a Customer entity uses
persistent properties and has a private instance variable called firstName, the class defines a
getFirstName and setFirstName method for retrieving and setting the state of the firstName instance
variable.

The method signature for single-valued persistent properties are as follows:

Type getProperty()
void setProperty(Type type)

The object/relational mapping annotations for persistent properties must be applied to the getter
methods. Mapping annotations cannot be applied to fields or properties annotated @Transient or
marked transient.
 Explain Life Cycle Of A Jpa Entity.

Key states that an entity might be in:

1. New / Transient: An object is instantiated but not yet associated with an Entity Manager and

has no representation in the database.

2. Managed / Persisted.

3. Detached: Detached entity objects are objects in a special state in which they are not

managed by any EntityManager but still represent objects in the database. Detached objects

are often returned from a persistence tier to the web layer where they can be displayed to

the end-user in some form. Changes can be made to a detached dobject, but these changes

won't be persisted to the database until the entity is reassociated with a persistence context

(the entity is merged back to an EntityManager to become managed again).

4. Removed.

o The merge method's major task is to transfer the state from an unmanaged entity (passed as the

argument) to its managed counterpart within the persistence context.

o merge deals with both new and detached entities. Merge causes either INSERT or UPDATE

operation according to the sub-scenario (on the one hand it is more robust, on the other hand this

robustness needn't be required.)

o persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the

entity has already been inserted and thus the primary key violation happens.)

 What Is Jpql?

JPQL (Java Persistence Query Language) offers an object-oriented syntax for expressing query that
is very similar to SQL. The language is interpreted at runtime, which means you cannot use the
compiler to verify the correctness and integrity of a query. To adress this limitation, Hibernate
includes a Criteria API, which allows queries to be expressed programmatically.

 Example Of An Entity With Embedded Class.

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "categoryparticipant")
@NamedQueries({
@NamedQuery(name = "Categoryparticipant.getCategoriesOfParticipant", query = "SELECT
cp.category from Categoryparticipant cp where cp.participant.participantid= :participantid")
})
public class Categoryparticipant implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected CategoryparticipantPK categoryparticipantPK;
@Basic(optional = false)
@Column(name = "CreationDate")
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@JoinColumn(name = "ParticipantId", referencedColumnName = "ParticipantId", insertable = false,
updatable = false)
@ManyToOne(optional = false)
private Participant participant;
@JoinColumn(name = "CategoryId", referencedColumnName = "CategoryId", insertable = false,
updatable = false)
@ManyToOne(optional = false)
private Category category;
public Categoryparticipant() {
}
public Categoryparticipant(CategoryparticipantPK categoryparticipantPK) {
this.categoryparticipantPK = categoryparticipantPK;
}
public Categoryparticipant(CategoryparticipantPK categoryparticipantPK, Date creationDate) {
this.categoryparticipantPK = categoryparticipantPK;
this.creationDate = creationDate;
}
public Categoryparticipant(int categoryId, int participantId) {
this.categoryparticipantPK = new CategoryparticipantPK(categoryId, participantId);
}
public CategoryparticipantPK getCategoryparticipantPK() {
return categoryparticipantPK;
}
public void setCategoryparticipantPK(CategoryparticipantPK categoryparticipantPK) {
this.categoryparticipantPK = categoryparticipantPK;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Participant getParticipant() {
return participant;
}
public void setParticipant(Participant participant) {
this.participant = participant;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Override
public int hashCode() {
int hash = 0;
hash += (categoryparticipantPK != null ? categoryparticipantPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Categoryparticipant)) {
return false;
}
Categoryparticipant other = (Categoryparticipant) object;
if ((this.categoryparticipantPK == null && other.categoryparticipantPK != null) ||
(this.categoryparticipantPK != null &&
!this.categoryparticipantPK.equals(other.categoryparticipantPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.xchanging.entity.jpa.Categoryparticipant[categoryparticipantPK=" +
categoryparticipantPK + "]";
}
}

 Give An Example Of Embeddable Class For Previous Question Categoryparticipant


Entity.

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class CategoryparticipantPK implements Serializable {
@Basic(optional = false)
@Column(name = "CategoryId")
private int categoryId;
@Basic(optional = false)
@Column(name = "ParticipantId")
private int participantId;
public CategoryparticipantPK() {
}
public CategoryparticipantPK(int categoryId, int participantId) {
this.categoryId = categoryId;
this.participantId = participantId;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public int getParticipantId() {
return participantId;
}
public void setParticipantId(int participantId) {
this.participantId = participantId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) categoryId;
hash += (int) participantId;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CategoryparticipantPK)) {
return false;
}
CategoryparticipantPK other = (CategoryparticipantPK) object;

if (this.categoryId != other.categoryId) {
return false;
}
if (this.participantId != other.participantId) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.xchanging.entity.jpa.CategoryparticipantPK[categoryId=" + categoryId + ",
participantId=" + participantId + "]";
}
}

 Insert A Record Mechanism Using Jpa.

@Override
@Transactional
public void create(Category entity) throws MeetingAppDAOException {
try {
logger.info("Enter - create()");
super.create(entity);
logger.info("Exit - create()");
} catch (PersistenceException exception) {
logger.error("create()::REASON OF EXCEPTION=" + exception.getMessage(), e);
}
}

 How To Fetch A Record Using Namedquery?


public Category findByCategoryId(Long categoryId) {
try {
logger.info("Enter - findByCategoryId()");
Query lQuery = (Query) em.createNamedQuery("Category.findByCategoryId");
Integer intValue = categoryId.intValue();
lQuery.setParameter("categoryId", intValue);
Category category = (Category) lQuery.getSingleResult();
logger.info("Exit - findByCategoryId");
return category;
} catch (PersistenceException exception) {
logger.debug(exception.getCause().getStackTrace());
logger.error("CategoryDaoImpl::maxCategoryId()::REASON OF EXCEPTION=" +
exception.getMessage() + exception.getCause());
} finally {
closeEntityManager();
}
}

 Why Have You Introduced The New Java Persistence Api As Part Of The Java Ee 5
Platform?

We introduced the Java Persistence API to the Java platform for two reasons. First, this new API
simplifies the development of Java EE and Java SE applications using data persistence. Second, we
wanted to get the entire Java community behind a single, standard persistence API.

 What Are The Advantages Of The Java Persistence Api?

The Java Persistence API draws upon the best ideas from persistence technologies such as
Hibernate, TopLink, and JDO. Customers now no longer face the choice between incompatible non-
standard persistence models for object/relational mapping. In addition, the Java Persistence API is
usable both within Java SE environments as well as within Java EE, allowing many more developers
to take advantage of a standard persistence API.

 What Are Some Of The Main Features Of The Java Persistence Api?

The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full
object/relational mapping specification supporting the use of Java language metadata annotations
and/or XML descriptors to define the mapping between Java objects and a relational database. It
supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both
static and dynamic queries. It also supports the use of pluggable persistence providers.

 Why Was The Java Persistence Api Developed As Part Of Jsr-220 (ejb 3.0)?

The Java Persistence API originated as part of the work of the JSR 220 Expert Group to simplify
EJB CMP entity beans. It soon became clear to the expert group, however, that a simplification of
EJB CMP was not enough, and that what was needed was a POJO persistence framework in line
with other O/R mapping technologies available in the industry. Once an Earlier Draft of the EJB 3.0
specification including the Java Persistence API was released, the JSR-220 Expert Group received
many requests from the community that this work be made available beyond just the scope of EJB.

 Why Didn't You Split Off The Java Persistence Api Work Into A Separate Jsr?

We believed that leveraging the work in the context of JSR-220 would minimize risk and deliver a
high quality result more quickly. Further, it was important that this API integrate smoothly and
consistently with the rest of the simplifications to the EJB 3.0 APIs. It therefore seemed best to
extend this ongoing project, and draw additional experts into the JSR-220 group as appropriate as
the work expanded.

 Why Didn't You Adopt Hibernate Or Jdo As The Persistence Api?

We chose to combine the best ideas from many sources in the new persistence API and create a
practical, easy to use API to meet the needs of a majority of Java EE and Java SE community
members. The Java Persistence API is not based on any single existing persistence framework but
incorporates--and improves upon--ideas contributed by many popular frameworks, including
Hibernate, TopLink, JDO, and others.

 What If I Want To Use The Java Persistence Api Outside Of The Java Ee Platform?

The specification, RI, and TCK insure that the Java Persistence API works with Java SE as well as
with Java EE. Passing the TCK for the Java SE portion allows vendors to be compliant with the Java
Persistence API without having a Java EE certification.

 What Will Happen To Other Data Persistence Apis Now That The Java Persistence Api
Is Available?

The Java Persistence API is now the standard API for persistence and object/relational mapping for
the Java EE platform. Earlier APIs of course will not go away, but we expect that they will become
less interesting once this new standard API is available.

 How Will The Java Persistence Api Evolve Now That Jsr 220 Has Been Completed?

We expect to spin off the Java Persistence API into its own new JSR for future evolution. This
means subsequent versions of the Java Persistence API will not be tied to future EJB JSRs. We
expect to continue to draw expertise from a diversity of sources, quite likely including many of the
members of the JSR 220 Expert Group who helped define the Java Persistence API.

 Will The Java Persistence Api Become Part Of Java Se?

There are no current plans to include the Java Persistence API in Java SE. As the Java Persistence
API evolves, however, it is likely that this issue will be considered by the Java SE expert group in a
future Java SE release.
 Are Changes Needed To Existing Ejb Cmp Applications?

Existing EJB CMP applications continue to work unchanged, and EJB CMP technology will continue
to be supported. There is no need to migrate existing applications to the Java Persistence API.
Further, it is possible within the same application to combine continue usage of EJB CMP entity
beans with new EJB components that make use of the Java Persistence API.

 How Can I Obtain An Implementation Of The Java Persistence Api?

We expect many vendors to offer products that include implementations of the Java Persistence API
that can be used with Java SE or Java EE. You can obtain the open source GlassFish project
implementation of the Java Persistence API.

JPA is just a specification which needs concrete implementation. The default implementation
provided by oracle is "Eclipselink" now. Toplink is donated by Oracle to Eclipse foundation to
merge with eclipselink.

Using Eclipselink, one can be sure that the code is portable to any implementation if need arises.
Hibernate is also a full JPA implementation + MORE. Hibernate is super set of JPA with some extra
Hibernate specific functionality. So application developed in Hibernate may not be compatible
when switched to other implementation. Still hibernate is choice of majority of developers as JPA
implementation and widely used.

Another JPA implementation is OpenJPA, which is an extension of Kodo implementation.

Any enterprise application performs database operations by storing and


retrieving vast amounts of data. Despite all the available technologies for
storage management, application developers normally struggle to perform
database operations efficiently.

Generally, Java developers use lots of code, or use the proprietary framework
to interact with the database, whereas using JPA, the burden of interacting
with the database reduces significantly. It forms a bridge between object
models (Java program) and relational models (database program).

Mismatches between relational and object


models
Relational objects are represented in a tabular format, while object models
are represented in an interconnected graph of object format. While storing
and retrieving an object model from a relational database, some mismatch
occurs due to the following reasons:

 Granularity : Object model has more granularity than relational model.

 Subtypes : Subtypes (means inheritance) are not supported by all types of


relational databases.

 Identity : Like object model, relational model does not expose identity while
writing equality.

 Associations : Relational models cannot determine multiple relationships while


looking into an object domain model.

 Data navigation : Data navigation between objects in an object network is


different in both models.

What is JPA?
Java Persistence API is a collection of classes and methods to persistently
store the vast amounts of data into a database which is provided by the
Oracle Corporation.

Where to use JPA?


To reduce the burden of writing codes for relational object management, a
programmer follows the ‘JPA Provider’ framework, which allows easy
interaction with database instance. Here the required framework is taken
over by JPA.

1. What’s Hibernate?

Hibernate is a popular framework of Java which allows an efficient Object Relational


mapping using configuration files in XML format. After java objects mapping to database
tables, database is used and handled using Java objects without writing complex database
queries.

2. What is ORM?
ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework
which maps database tables with Java Objects and then provides various API’s to perform
different types of operations on the data tables.
3. How properties of a class are mapped to the columns of a database table in Hibernate?

Mappings between class properties and table columns are specified in XML file as in the
below example:

4. What’s the usage of Configuration Interface in hibernate?

Configuration interface of hibernate framework is used to configure hibernate. It’s also used
to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

5. How can we use new custom interfaces to enhance functionality of built-in interfaces of
hibernate?

We can use extension interfaces in order to add any required functionality which isn’t
supported by built-in interfaces.

6. Should all the mapping files of hibernate have .hbm.xml extension to work properly?

No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping
file names. We can have any extension for these mapping files.

7. How do we create session factory in hibernate?

To create a session factory in hibernate, an object of configuration is created first which


refers to the path of configuration file and then for that configuration, session factory is
created as given in the example below:

1 Configuration config = new Configuration();


2 config.addResource("myinstance/configuration.hbm.xml");
3 config.setProperties( System.getProperties() );
4 SessionFactory sessions = config.buildSessionFactory();
8. What are POJOs and what’s their significance?

POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for
each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed
code.

9. What’s HQL?
HQL is the query language used in Hibernate which is an extension of SQL. HQL is very
efficient, simple and flexible query language to do various type of operations on relational
database without writing complex database queries.
10. How can we invoke stored procedures in hibernate?
In hibernate we can execute stored procedures using code as below:
[xml]

<sql-query name=”getStudents” callable=”true”>


<return alias=”st” class=”Student”>
<return-property name=”std_id” column=”STD_ID”/>
<return-property name=”s_name” column=”STD_NAME”/>
<return-property name=”s_dept” column=”STD_DEPARTMENT”/>
{ ? = call selectStudents() }
</return>
</sql-query>

[/xml]

11. What is criteria API?

Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through
criteria object composition.

12. What are the benefits of using Hibernate template?


Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.
13. How can we see hibernate generated SQL on console?
We need to add following in hibernate configuration file to enable viewing SQL on the
console for debugging purposes:

[xml]

<property name=”show_sql”>true</property>

[/xml]

14. What are the two types of collections in hibernate?


Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection
15. What’s the difference between session.save() and session.saveOrUpdate() methods in
hibernate?
Sessionsave() method saves a record only if it’s unique with respect to its primary key and
will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an
existing record if primary key exists in the table already.
16. What the benefits are of hibernate over JDBC?
a. Hibernate can be used seamlessly with any type of database as its database
independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as
HQL simplifies query writing process while in case of JDBC, its job of developer to write and
tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all
connection handling automatically while in case of JDBC, connection pools need to be
created.
17. How can we get hibernate statistics?
We can get hibernate statistics using getStatistics() method of SessionFactory class as
shown below:
SessionFactory.getStatistics()
18. What is transient instance state in Hibernate?
If an instance is not associated with any persistent context and also, it has never been
associated with any persistent context, then it’s said to be in transient state.
19. How can we reduce database write action times in Hibernate?
Hibernate provides dirty checking feature which can be used to reduce database write
times. Dirty checking feature of hibernate updates only those fields which require a change
while keeps others unchanged.
20. What’s the usage of callback interfaces in hibernate?
Callback interfaces of hibernate are useful in receiving event notifications from objects. For
example, when an object is loaded or deleted, an event is generated and notification is sent
using callback interfaces.
21. When an instance goes in detached state in hibernate?
When an instance was earlier associated with some persistent context (e.g. a table) and is
no longer associated, it’s called to be in detached state.
22. What the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping
23. What’s transaction management in hibernate? How it works?
Transaction management is the process of managing a set of statements or commands. In
hibernate; transaction management is done by transaction interface as shown in below
code:

[java]
Session s = null;
Transaction tr = null;
try {
s = sessionFactory.openSession();
tr = s.beginTransaction();
doTheAction(s);
tr.commit();
} catch (RuntimeException exc) {
tr.rollback();
} finally {
s.close();
}

[/java]

24. What the two methods are of hibernate configuration?


We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)
25. What is the default cache service of hibernate?
Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and
TreeCache and default cache service of hibernate is EHCache.
26. What are the two mapping associations used in hibernate?
In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association
27. What’s the usage of Hibernate QBC API?
Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria
objects at runtime.
28. In how many ways, objects can be fetched from database in hibernate?
Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL
29. How primary key is created by using hibernate?
Database primary key is specified in the configuration file hbm.xml. Generator can also be
used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:

[xml]
<id name=”deptId” type=”string” >
<column name=”columnId” length=”30″/>
<generator/>
</id>
[/xml]

30. How can we reattach any detached objects in Hibernate?


Objects which have been detached and are no longer associated with any persistent
entities can be reattached by calling session.merge() method of session class.
31. What are different ways to disable hibernate second level cache?

Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider

32. What is ORM metadata?


All the mapping between classes and tables, properties and columns, Java types and SQL
types etc is defined in ORM metadata.
33. Which one is the default transaction factory in hibernate?
With hibernate 3.2, default transaction factory is JDBCTransactionFactory.
34. What’s the role of JMX in hibernate?
Java Applications and components are managed in hibernate by a standard API called JMX
API. JMX provides tools for development of efficient and robust distributed, web based
solutions.
35. How can we bind hibernate session factory to JNDI ?
Hibernate session factory can be bound to JNDI by making configuration changes in
hibernate.cfg file.

36. In how many ways objects can be identified in Hibernate?


Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent
same row.
37. What different fetching strategies are of hibernate?
Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching
38. How mapping of java objects is done with database tables?
To map java objects with database tables, we need to have Java beans properties names
same as column names of a database table. Then mapping is provided in hbm.xml file as
given below:

[xml]
<hibernate-mapping>
<class name=”Student” table=”tbl_student”>
<property column=”studentname” length=”255″
name=”studentName” not-null=”true” type=”java.lang.String”/>
<property column=”studentDisciplne” length=”255″
name=”studentDiscipline” not-null=”true” type=”java.lang.String”/>
</class>
</hibernate-mapping>
[/xml]

39. What are derived properties in hibernate?


Derived properties are those properties which are not mapped to any columns of a
database table. Such properties are calculated at runtime by evaluation of any expressions.
40. What is meant by a Named SQL Query in hibernate and how it’s used?
Named SQL queries are those queries which are defined in mapping file and are called as
required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:

[xml]

<sql-query name = “studentdetails”>


<return alias=”std”/>
SELECT std.STUDENT_ID AS {std.STUDENT_ID},
std.STUDENT_DISCIPLINE AS {std.discipline},

FROM Student std WHERE std.NAME LIKE :name


</sql-query>
[/xml]

Then this query can be called as follows:

[java]

List students = session.getNamedQuery(&amp;quot;studentdetails&amp;quot;)


.setString(&amp;quot;TomBrady&amp;quot;, name)
.setMaxResults(50)
.list();

[/java]

41. What’s the difference between load() and get() method in hibernate?
Load() methods results in an exception if the required records isn’t found in the database
while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records
against an id.
42. What’s the use of version property in hibernate?
Version property is used in hibernate to know whether an object is in transient state or in
detached state.
43. What is attribute oriented programming?
In Attribute oriented programming, a developer can add Meta data (attributes) in the java
source code to add more significance in the code. For Java (hibernate), attribute oriented
programming is enabled by an engine called XDoclet.
44. What’s the use of session.lock() in hibernate?
session.lock() method of session class is used to reattach an object which has been
detached earlier. This method of reattaching doesn’t check for any data synchronization in
database while reattaching the object and hence may lead to lack of synchronization in
data.
45. Does hibernate support polymorphism?
Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism
associations are supported in all mapping strategies of hibernate.
46. What the three inheritance models are of hibernate?
Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class
47. How can we map the classes as immutable?
If we don’t want an application to update or delete objects of a class in hibernate, we can
make the class as immutable by setting mutable=false
48. What’s general hibernate flow using RDBMS?
General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.
49. What is Light Object Mapping?
Light Object Mapping is one of the levels of ORM quality in which all entities are
represented as classes and they are mapped manually.
50. What’s difference between managed associations and hibernate associations?
Managed associations relate to container management persistence and are bi-directional
while hibernate associations are unidirectional.

Ques 1. What is JPA and its key components?


Ans. Mapping between database tables and java objects called ORM (Object Relational
Mapping). JPA (Java Persistence API) provides and ORM facility for managing relational tables
in Java applications. It is a specification and few implementations are like Hibernate, JDO, EJB,
Toplink. By using JPA can be fetched data, insert, update etc.

Is it helpful? Yes No Add Comment View Comments


 Questions and answers
 Download Android
 Exams
 Free Downloads
 Download
 Downloading
 Detached
 Play
 Application
 Annotation
 Questions and answers
 Download Android
 Exams
Ques 2. What is the difference between persistence.xml and hibernate.cfg.xml?
Ans. When using JPA need persistence.xml and while using Hibernate API need
hibernate.cfg.xml. When using JPA or Hibernate not needed both xmls, need the xml
configuration file according to JPA or Hibernate.

Is it helpful? Yes No Add Comment View Comments


Ques 3. What is an EntityManager?
Ans. Entity manager javax.persistence.EntityManager provides the operations from and to the
database, e.g. find objects, persists them, remove objects from the database, etc. Entities which
are managed by an EntityManager will automatically propagate these changes to the
database (if this happens within a commit statement). These objects are known as persistent
object. If the Entity Manager is closed (via close()) then the managed entities are in a detached
state. These are known as the detached objects. If you want synchronize them again with the
database, the a Entity Manager provides the merge() method. Once merged, the object(s)
becomes perstent objects again.

The EntityManager is the API of the persistence context, and an EntityManager can be injected
directly in to a DAO without requiring a JPA Template. The Spring Container is capable of acting
as a JPA container and of injecting the EntityManager by honoring the @PersistenceContext
(both as field-level and a method-level annotation).

Is it helpful? Yes No Add Comment View Comments


Ques 4. What is an Entity?
Ans. A class which should be persisted in a database it must be annotated with
javax.persistence.Entity. Such a class is called Entity. An instances of the class will be a row in the
person table. So, the columns in the person table will be mapped to the Person java object
annotated as @Entity.
While insert, update or fetch record to or from the database we use entity as mapping with
relational tables.

Is it helpful? Yes No Add Comment View Comments


Ques 5. Why to use JPA?
Ans. JPA is the standard, and standards are good!
Using JPA does not tie you to Hibernate.
JPA gives you most of the features of plain old Hibernate, except:
No criteria queries in JPA 2.0. Criteria query is a neat feature of Hibernate that constructs query
using Java-based combinators instead of alternate query language, getting the benefit of
IntelliSense and Eclipse’s refactoring tools.
JPA doesn’t have Hibernate’s DeleteOrphan cascade type.
Delete Orphan is a useful annotation that directs Hibernate to deletes entities in a collection if
the parent is deleted, preventing orphaning.
JPA doesn’t have an equivalent to Hibernate’s ScrollableResults.

Ques 6. What is Embeddable classes?


Ans. Entities may use persistent fields, persistent properties, or a combination of both. If the
mapping annotations are applied to the entity’s instance variables, the entity uses persistent
fields. If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style
properties, the entity uses persistent properties.

Is it helpful? Yes No Add Comment View Comments


 Questions and answers
 Download Android
 Exams
 Free Downloads
 Download
 Downloading
 Detached
 Play
 Annotation
 Compiler
 Questions and answers
 Download Android
 Exams
Ques 7. What is Persistent Fields?
Ans. If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance
variables directly. All fields not annotated javax.persistence.Transient or not marked as Java
transient will be persisted to the data store. The object/relational mapping annotations must be
applied to the instance variables.

Is it helpful? Yes No Add Comment View Comments


Ques 8. What is Persistent Properties?
Ans. If the entity uses persistent properties, the entity must follow the method conventions of
JavaBeans components. JavaBeans-style properties use getter and setter methods that are
typically named after the entity class’s instance variable names. For every persistent property
property of type Type of the entity, there is a getter method getProperty and setter method
setProperty. If the property is a Boolean, you may use isProperty instead of getProperty. For
example, if a Customer entity uses persistent properties and has a private instance variable
called firstName, the class defines a getFirstName and setFirstName method for retrieving and
setting the state of the firstName instance variable.

The method signature for single-valued persistent properties are as follows:

Type getProperty()
void setProperty(Type type)

The object/relational mapping annotations for persistent properties must be applied to the
getter methods. Mapping annotations cannot be applied to fields or properties annotated
@Transient or marked transient.

Is it helpful? Yes No Add Comment View Comments


Ques 9. Explain Life Cycle of a JPA Entity.
Ans. Key states that an entity might be in:

1) New / Transient: An object is instantiated but not yet associated with an Entity Manager and
has no representation in the database.

2) Managed / Persisted.

3) Detached: Detached entity objects are objects in a special state in which they are not
managed by any EntityManager but still represent objects in the database. Detached objects
are often returned from a persistence tier to the web layer where they can be displayed to the
end-user in some form. Changes can be made to a detached dobject, but these changes
won\'t be persisted to the database until the entity is reassociated with a persistence context
(the entity is merged back to an EntityManager to become managed again).

4) Removed.

- The merge method\'s major task is to transfer the state from an unmanaged entity (passed as
the argument) to its managed counterpart within the persistence context.
- merge deals with both new and detached entities. Merge causes either INSERT or UPDATE
operation according to the sub-scenario (on the one hand it is more robust, on the other hand
this robustness needn\'t be required.)
- persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the
entity has already been inserted and thus the primary key violation happens.)
Is it helpful? Yes No Add Comment View Comments
Ques 10. What is JPQL?
Ans. JPQL (Java Persistence Query Language) offers an object-oriented syntax for expressing
query that is very similar to SQL. The language is interpreted at runtime, which means you cannot
use the compiler to verify the correctness and integrity of a query. To adress this limitation,
Hibernate includes a Criteria API, which allows queries to be expressed programmatically.

Is it helpful? Yes No Add Comment View Comments

 1

 2

 3

Most helpful rated by users:

 What is JPA and its key components?


 What is an EntityManager?
 What is the difference between persistence.xml and hibernate.cfg.xml?
 What is an Entity?
 Why to use JPA?

Das könnte Ihnen auch gefallen