Escolar Documentos
Profissional Documentos
Cultura Documentos
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a
Java application to the tables in a relational database.
4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that
allows you to map plain old Java objects to relational database tables using (XML) configuration
files.Its purpose is to relieve the developer from a significant amount of relational data
persistence-related programming tasks.
• Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
• Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
• Improved maintainability
o A lot less code to write
• Improved portability
o ORM framework generates database-specific SQL for you
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)
• Session interface
• SessionFactory interface
• Configuration interface
• Transaction interface
• Query and Criteria interfaces
• Load the Hibernate configuration file and create configuration object. It will
automatically load all hbm mapping files
• Create session factory from configuration object
• Get one session from this session factory
• Create HQL Query
• Execute query to get list containing Java objects
Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true"
type="java.lang.String"/>
</class>
</hibernate-mapping>
Only use the load() method if you are sure If you are not sure that the object exists,
that the object exists. then use one of the get() methods.
load() method will throw an exception if the get() method will return null if the
unique id is not found in the database. unique id is not found in the database.
23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides
different methods for querying/retrieving data from the database. It also converts checked
HibernateExceptions into unchecked DataAccessExceptions.
26.If you want to see the Hibernate generated SQL statements on console, what should we
do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
Example:
If your collection is not large, it will be more If your collection is very large, it will be
efficient way to sort it. more efficient way to sort it .
31.What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
JDBC Hibernate
• Bag
• Set
• List
• Array
• Map
36.How can Hibernate be configured to access an instance variable directly and not
through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to
bypass the setter method and access the instance variable directly while initializing a newly
loaded object.
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class
are (not) mutable. Immutable classes, may not be updated or deleted by the application.
Provides callback support through lifecycle, Provides callback support through Entity
interceptor, and validatable interfaces Listener and Callback methods
Answer:
The configuration files hibernate.cfg.xml (or hibernate. properties) and mapping files
*.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap
hibernate) the SessionFactory, which in turn creates the Session instances. Session instances
are the primary interface for the persistence service.
• hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to
configure the hibernate sevice (connection driver class, connection URL, connection username,
connection password, dialect etc). If both files are present in the classpath then
hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.
• Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational
database. It is the best practice to store each object in an individual mapping file (i.e mapping
file per class) because storing large number of persistent classes into one mapping file can be
difficult to manage and maintain. The naming convention is to use the same name as the
persistent (POJO) class name. For example Account.class will have a mapping file named
Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent
class code instead of the *.hbm.xml files.
Answer:
Q. What is a Session? Can you share a session object between different theads?
Answer:
Session is a light weight and a non-threadsafe object (No, you cannot share it between
threads) that represents a single unit-of-work with the database. Sessions are opened by a
SessionFactory and then are closed when all work is complete. Session is the primary interface
for the persistence service. A session obtains a database connection lazily (i.e. only when
required). To avoid creating too many sessions ThreadLocal class can be used as shown below
to get the current session no matter how many times you make call to the currentSession()
method.
…
public class HibernateUtil {
…
public static final ThreadLocal local = new ThreadLocal();
It is also vital that you close your session after your unit of work completes. Note: Keep your
Hibernate Session API handy.
Answer:
Detached objects can be passed across layers all the way up to the presentation layer without
having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached
objects to another session.
Q. What are the pros and cons of detached objects?
Answer:
Pros:
• When long transactions are required due to user think-time, it is the best practice to break
the long transaction up into two or more transactions. You can use detached objects from the
first transaction to carry data all the way up to the presentation layer. These detached objects
get modified outside a transaction and later on re-attached to a new transaction via another
session.
Cons
• In general, working with detached objects is quite cumbersome, and better to not clutter up
the session with them if possible. It is better to discard them and re-fetch them on subsequent
requests. This approach is not only more portable but also more efficient because - the objects
hang around in Hibernate's cache anyway.
• Also from pure rich domain driven design perspective it is recommended to use DTOs
(DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service
and UI tiers.
Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and
detached objects?
Answer
Q. What is the difference between the session.get() method and the session.load() method?
Both the session.get(..) and session.load() methods create a persistent object by loading the required
object from the database. But if there was not such object in the database then the method
session.load(..) throws an exception whereas session.get(…) returns null.
Q. What is the difference between the session.update() method and the session.lock() method?
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The
session.lock() method simply reattaches the object to the session without checking or updating the
database on the assumption that the database in sync with the detached object. It is the best practice to
use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure
that the detached object is in sync with your detached object or if it does not matter because you will be
overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are
reatched as well.
Q. How would you reatach detached objects to a session when the same object has already
been loaded into the session?
1.You must have a default no-argument constructor for your persistent classes and there should be
getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance
variables.
2.You should implement the equals() and hashCode() methods based on your business key and it is
important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key
(i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when
saving the object.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to
migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating
proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less
verbose than *.hbm.xml files.
Would like to hear more questions and answers from the readers.....................
How can I count the number of query results without actually returning
them?
select user
from User user
left join user.messages msg
group by user
order by count(msg)
or:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
Because of the inner join, this form can't be used to return a User with zero messages, so the following form is
also useful
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0
select box
from Box box
left join box.balls ball
where ball is null
1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or <set> or <map>. This
solution does a sort in memory.
2. Specify an order-by attribute of <set>, <map> or <bag>, naming a list of table columns to sort by. This
solution works only in JDK 1.4+.
<generator class="foreign">
<param name="property">parent</param>
</generator>
Use a composite-element to model the association table. For example, given the following association table:
you could use this collection mapping (inside the mapping for class Foo):
<set name="relationship">
<key column="fk_of_foo"/>
<composite-element class="Relationship">
<property name="multiplicity" type="short" not-null="true"/>
<property name="created" type="date" not-null="true"/>
<many-to-one name="bar" class="Bar" not-null="true"/>
</composite-element>
</set>
You may also use an <idbag> with a surrogate key column for the collection table. This would allow you to have
nullable columns.
An alternative approach is to simply map the association table as a normal entity class with two bidirectional one-
to-many associations.
In an MVC application, how can we ensure that all proxies and lazy
collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view.
The session/transaction would be closed/committed after the view is rendered in, for example, a servlet filter
(another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this
approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is
often more straightforward than it sounds.
You may persist any static inner class. You should specify the class name using the standard form ie.
eg.Foo$Bar
How can I assign a default value to a property when the database column is
null?
Use a UserType.
Use a UserType.
How can I trim spaces from String data persisted to a CHAR column?
Use a UserType.
How can I convert the type of a property to/from the database column type?
Use a UserType.
How can I get access to O/R mapping information such as table and
column names at runtime?
This information is available via the Configuration object. For example, entity mappings may be obtained using
Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then
build a new SessionFactory.
If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT
statement:
Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.
This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods.
If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This
method is then treated like any other business method of the proxy, initialization is required if it is called.
How can I manipulate mappings at runtime?
You can access (and modify) the Hibernate metamodel via the Configuration object, using
getClassMapping(), getCollectionMapping(), etc.
Note that the SessionFactory is immutable and does not retain any reference to the Configuration instance,
so you must re-build it if you wish to activate the modified mappings.
How can I avoid n+1 SQL SELECT queries when running a Hibernate query?
Follow the best practices guide! Ensure that all <class> and <collection> mappings specify lazy="true" in
Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you
need to be retrieved in the initial SQL SELECT.
A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.
If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.
Enable second-level cache for the associated entity class. Don't cache collections of uncached entity types.
How can I insert XML data into Oracle using the xmltype() function?
Specify custom SQL INSERT (and UPDATE) statements using <sql-insert> and <sql-update> in Hibernate3,
or using a custom persister in Hibernate 2.1.
You will also need to write a UserType to perform binding to/from the PreparedStatement.
PreparedStatement ps = session.connection().prepareStatement(sqlString);
Or, in Hibernate3, override generated SQL using <sql-insert>, <sql-update>, <sql-delete> and
<loader> in the mapping document.
I want to call an SQL function from HQL, but the HQL parser does not
recognize it!
Q: What is Hibernate?
A: Hibernate is a java-based Object/relational mapping(ORM) tool.
Q: What is the naming convention for Hibernate XML mapping file extensions?
A: .hbm.xml
Q: What are the most common methods of configuring Hibernate?
A: 1. By placing hibernate.properties file in the classpath.
2. Including <property> elements in hibernate.cfg.xml in the classpath.
Q: Since SessionFactory instances are not lightweight, where is the single created
instance placed in J2EE environments?
A: Usually it is bound to JNDI, it will bind itself automatically if
hibernate.session_factory_name is set to the name of directory node.
Q: How can you make a property be read from the database but not modified in
anyway (make it immutable)?
A: By using the insert="false" and update="false" attributes.