Question and answer in Hibernate

Share Embed Donate


Short Description

Hibernate questions...

Description

Q: What is Hibernate?

A: Hibernate is a java-based Object/relational mapping(ORM) tool. Q: What are ORM tools? A: ORM tools provide automated solutions for the Object/relational paradigm mismatch problem, using metadata that describes the mapping between the objects and the database. Q: What is Object/relational paradigm mismatch? A: Object-Oriented paradigm is based on software engineering principles, whereas relational paradigm on mathematical principles. Object-oriented technology supports the building of applications out of networks of objects with both data and behavior. Relational technology supports the storage of data in tables and manipulation of that data using data manipulation language (DML). Because the underlying paradigms are different the two technologies do not work seamlessly, hence the name Object/relational paradigm mismatch. Q: What role does the Session interface play in Hibernate? A: The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not threadsafe. Q: What is SessionFactory interface? A: The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database Q: What is Configuration interface? A: The application uses a Configuration instance to specify the location of mapping documents and Hibernate-specific properties and then creates the SessionFactory. 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 elements in hibernate.cfg.xml in the classpath. Q: How can the mapping files be configured in Hibernate? A: 1. Mapping files can be added to Configuration in the application code or, 2. They can be configured in hibernate.cfg.xml using the elements. Q: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath? A: The settings of the XML configuration file will override the settings used in the properties.

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 to set Hibernate to log all generated SQL to the console? A: By setting the hibernate.show_sql property to true. Q: In hibernate, what interfaces/classes must the persistent classes (classes that are mapped to database tables) implement/extend? A: NONE, they can be regular POJOs. Q: Does hibernate require persistent classes to implement Serializable? A: Hibernate doesn't require that persistent classes implement Serializable. However, when objects are stored in an HttpSession or passed by value using RMI, serialization is necessary. Q: What methods must the persistent classes implement in Hibernate? A: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables. Q: How can Hibernate be configured to access a instance variable directly and not through a setter method? A: 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. Q: What is dirty checking in Hibernate? A: Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. An important note here is, Hibernate will compare objects by value, except for Collections, which are compared by identity. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates. Q: What is the root level element in a hibernate mapping file? A: Q: Is it possible to declare mappings for multiple classes in one mapping file? A: Yes, by using multiple elements. But, the recommended practice is to use one mapping file per persistent class. Q: How are the individual properties mapped to different table columns? A: By using multiple elements inside the element. Q: What are derived properties? A: The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The

expression can be defined using the formula attribute of the element. 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. Q: How can a whole class be mapped as immutable? A: By using the mutable="false" attribute in the class mapping. Q: What is the use of dynamic-insert and dynamic-update attributes in a class mapping? A: They tell hibernate whether to include unmodified properties in SQL INSERT and SQL UPDATE. Q: How do you achieve table-per-class hierarchy while mapping classes in Hibernate? A: By using several elements one for each sub-class inside the element. The class element can in turn contain other elements. Q: How do you achieve table-per-subclass while mapping classes in Hibernate? A: By using element inside the element. A element may contain other elements. Q: Does hibernate allow mixing table-per-class hierarchy and table-persubclass strategies? A: No, you cannot have a inside and vice versa. Session Interface Methods: There are number of methods provided by the Session interface but I'm going to list down few important methods only, which we will use in this tutorial. You can check Hibernate documentation for a complete list of methods associated with Session and SessionFactory. S.N.

Session Methods and Description Transaction beginTransaction()

1

Begin a unit of work and return the associated Transaction object. void cancelQuery()

2

Cancel the execution of the current query. void clear()

3

Completely clear the session.

Connection close() 4

End the session by releasing the JDBC connection and cleaning up. Criteria createCriteria(Class persistentClass)

5

Create a new Criteria instance, for the given entity class, or a superclass of an entity class. Criteria createCriteria(String entityName)

6

Create a new Criteria instance, for the given entity name. SerializablegetIdentifier(Object object)

7

Return the identifier value of the given entity as associated with this session. Query createFilter(Object collection, String queryString)

8

Create a new instance of Query for the given collection and filter string. Query createQuery(String queryString)

9

Create a new instance of Query for the given HQL query string. SQLQuerycreateSQLQuery(String queryString)

10

Create a new instance of SQLQuery for the given SQL query string. void delete(Object object)

11

Remove a persistent instance from the datastore. void delete(String entityName, Object object)

12

Remove a persistent instance from the datastore. Session get(String entityName, Serializable id)

13

Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.

SessionFactorygetSessionFactory() 14 15

Get the session factory which created this session. void refresh(Object object)

Re-read the state of the given instance from the underlying database. Transaction getTransaction() 16

Get the Transaction instance associated with this session. booleanisConnected()

17

Check if the session is currently connected. booleanisDirty()

18

Does this session contain any changes which must be synchronized with the database? booleanisOpen()

19

Check if the session is still open. Serializable save(Object object)

20

Persist the given transient instance, first assigning a generated identifier. void saveOrUpdate(Object object)

21

Either save(Object) or update(Object) the given instance. void update(Object object)

22

Update the persistent instance with the identifier of the given detached instance. void update(String entityName, Object object)

23

Update the persistent instance with the identifier of the given detached instance.

Property name

Purpose

hibernate.connection.driver_class

JDBC driver class

hibernate.connection.url

JDBC URL

hibernate.connection.username

database user

hibernate.connection.password

database user password

hibernate.connection.pool_size

maximum number of pooled connections

roperty name

Purpose

hibernate.dialect

The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular

roperty name

Purpose relational database. e.g.full.classname.of.Dialect In most cases Hibernate will actually be able to choose the correct org.hibernate.dialect.Dialect implementation based on the JDBC metadata returned by the JDBC driver. Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.

hibernate.show_sql e.g.true | false Pretty print the SQL in the log and console. hibernate.format_sql

e.g.true | false Qualify unqualified table names schema/tablespace in generated SQL.

with

the

given

hibernate.default_schema e.g.SCHEMA_NAME Qualifies unqualified table names with the given catalog in generated SQL. hibernate.default_catalog e.g.CATALOG_NAME The org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created. hibernate.session_factory_name e.g.jndi/composite/name

hibernate.max_fetch_depth

Sets a maximum "depth" for the outer join fetch tree for singleended associations (one-to-one, many-to-one). A 0 disables default outer join fetching. e.g. recommended values between 0 and 3 Sets a default size for Hibernate batch fetching of associations.

hibernate.default_batch_fetch_size

e.g. recommended values 4, 8, 16 Sets a default mode for entity representation for all sessions opened from this SessionFactory

hibernate.default_entity_mode dynamic-map, dom4j, pojo

roperty name

hibernate.order_updates

Purpose Forces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems. e.g.true | false If enabled, Hibernate will collect statistics useful for performance tuning.

hibernate.generate_statistics e.g.true | false If enabled, generated identifier properties will be reset to default values when objects are deleted. hibernate.use_identifier_rollback e.g.true | false If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false. hibernate.use_sql_comments e.g.true | false

Hibernate JDBC and Connection Properties Property name

Purpose

hibernate.jdbc.fetch_size

A non-zero value determines the JDBC fetch size (calls Statement.setFetchSize()).

hibernate.jdbc.batch_size

A non-zero value enables use of JDBC2 batch updates by Hibernate. e.g. recommended values between 5 and 30

hibernate.jdbc.batch_versioned_data

Set this property to true if your JDBC driver returns correct row counts from executeBatch(). Iit is usually safe to turn this option on. Hibernate will then use batched DML for automatically versioned data. Defaults to false. e.g.true | false

hibernate.jdbc.factory_class

Select a custom org.hibernate.jdbc.Batcher. applications will not need this configuration property.

Most

e.g.classname.of.BatcherFactory hibernate.jdbc.use_scrollable_resultset Enables use of JDBC2 scrollable resultsets by Hibernate.

Property name

Purpose This property is only necessary when using user-supplied JDBC connections. Hibernate uses connection metadata otherwise. e.g.true | false

hibernate.jdbc.use_streams_for_binary

Use streams when writing/reading binaryserializable types to/from JDBC. *system-level property* or e.g.true | false

Enables use of JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and hibernate.jdbc.use_get_generated_key JRE1.4+, set to false if your driver has problems with the s Hibernate identifier generators. By default, it tries to determine the driver capabilities using connection metadata. e.g.true|false

hibernate.connection.provider_class

The classname of a org.hibernate.connection.ConnectionProvider provides JDBC connections to Hibernate.

custom which

e.g.classname.of.ConnectionProvider

hibernate.connection.isolation

Sets the JDBC transaction isolation level. Check java.sql.Connection for meaningful values, but note that most databases do not support all isolation levels and some define additional, non-standard isolations. e.g.1, 2, 4, 8

hibernate.connection.autocommit

Enables autocommit for JDBC pooled connections (it is not recommended). e.g.true | false

hibernate.connection.release_mode

Specifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transaction. auto will choose after_statement for the JTA and CMT transaction strategies and after_transaction

Property name

Purpose for the JDBC transaction strategy. e.g.auto (default) after_statement

|

on_close

|

after_transaction

|

This setting only affects Sessions returned from SessionFactory.openSession. For Sessions obtained through SessionFactory.getCurrentSession, the CurrentSessionContext implementation configured for use controls the connection release mode for those Sessions. hibernate.connection.

Pass the JDBC property DriverManager.getConnection(). to

hibernate.jndi.

Pass the property to the JNDI InitialContextFactory.

Hibernate Cache Properties Property name

Purpose The classname of a custom CacheProvider.

hibernate.cache.provider_class

hibernate.cache.use_minimal_puts

e.g.classname.of.CacheProvider Optimizes second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate3, is enabled by default for clustered cache implementations. e.g.true|false

hibernate.cache.use_query_cache

Enables the query cache. Individual queries still have to be set cachable. e.g.true|false

Can be used to completely disable the second level cache, which is enabled by default for classes which hibernate.cache.use_second_level_cach specify a mapping. e e.g.true|false

hibernate.cache.query_cache_factory

The classname of a custom QueryCacheStandardQueryCache. interface, defaults to the built-in e.g.classname.of.QueryCache

Property name

Purpose A prefix to use for second-level cache region names.

hibernate.cache.region_prefix

hibernate.cache.use_structured_entries

e.g.prefix Forces Hibernate to store data in the second-level cache in a more human-friendly format. e.g.true|false

Hibernate Transaction Properties Property name

Purpose

hibernate.transaction.factory_class

The classname of a TransactionFactory to use with Hibernate Transaction API (defaults to JDBCTransactionFactory). e.g.classname.of.TransactionFactory

jta.UserTransaction

A JNDI name used by JTATransactionFactory to obtain the JTA UserTransaction from the application server. e.g.jndi/composite/name

The classname of a TransactionManagerLookup. It is required when JVM-level caching is enabled or when hibernate.transaction.manager_lookup_class using hilo generator in a JTA environment. e.g.classname.of.TransactionManagerLookup If enabled, the session will be automatically flushed during the before completion phase of the transaction. hibernate.transaction.flush_before_completio Built-in and automatic session context management is n preferred. e.g.true | false

hibernate.transaction.auto_close_session

If enabled, the session will be automatically closed during the after completion phase of the transaction. Built-in and automatic session context management is preferred. e.g.true | false

Miscellaneous Properties Property name

Purpose

Supply a custom strategy for the scoping of the "current" Session. See Section 2.5, “Contextual sessions” for more hibernate.current_session_context_clas information about the built-in strategies. s e.g.jta | thread | managed | custom.Class Chooses the HQL parser implementation. hibernate.query.factory_class

hibernate.query.substitutions

e.g.org.hibernate.hql.ast.ASTQueryTranslatorFactory or org.hibernate.hql.classic.ClassicQueryTranslatorFactory Is used to map from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example). e.g.hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

hibernate.hbm2ddl.auto

Automatically validates or exports schema DDL to the database when the SessionFactory is created. With createdrop, the database schema will be dropped when the SessionFactory is closed explicitly. e.g.validate | update | create | create-drop

Enables the use of CGLIB instead of runtime reflection (System-level property). Reflection can sometimes be useful when troubleshooting. Hibernate always requires hibernate.cglib.use_reflection_optimizer CGLIB even if you turn off the optimizer. You cannot set this property in hibernate.cfg.xml. e.g.true | false

SQL Dialects Always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database. If you specify a dialect, Hibernate will use sensible defaults for some of the other properties listed above. This means that you will not have to specify them manually.

Hibernate SQL Dialects (hibernate.dialect) RDBMS

Dialect

DB2

org.hibernate.dialect.DB2Dialect

DB2 AS/400

org.hibernate.dialect.DB2400Dialect

DB2 OS390

org.hibernate.dialect.DB2390Dialect

PostgreSQL

org.hibernate.dialect.PostgreSQLDialect

MySQL

org.hibernate.dialect.MySQLDialect

MySQL with InnoDB

org.hibernate.dialect.MySQLInnoDBDialect

MySQL with MyISAM

org.hibernate.dialect.MySQLMyISAMDialect

Oracle (any version)

org.hibernate.dialect.OracleDialect

Oracle 9i

org.hibernate.dialect.Oracle9iDialect

Oracle 10g

org.hibernate.dialect.Oracle10gDialect

Sybase

org.hibernate.dialect.SybaseDialect

Sybase Anywhere

org.hibernate.dialect.SybaseAnywhereDialect

Microsoft SQL Server

org.hibernate.dialect.SQLServerDialect

SAP DB

org.hibernate.dialect.SAPDBDialect

Informix

org.hibernate.dialect.InformixDialect

HypersonicSQL

org.hibernate.dialect.HSQLDialect

Ingres

org.hibernate.dialect.IngresDialect

Progress

org.hibernate.dialect.ProgressDialect

Mckoi SQL

org.hibernate.dialect.MckoiDialect

Interbase

org.hibernate.dialect.InterbaseDialect

Pointbase

org.hibernate.dialect.PointbaseDialect

FrontBase

org.hibernate.dialect.FrontbaseDialect

Firebird

org.hibernate.dialect.FirebirdDialect

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF