• No results found

Question and answer in Hibernate

N/A
N/A
Protected

Academic year: 2021

Share "Question and answer in Hibernate"

Copied!
12
0
0

Loading.... (view fulltext now)

Full text

(1)

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 <property> 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 <mapping> 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.

(2)

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: <hibernate-mapping>

Q: Is it possible to declare mappings for multiple classes in one mapping file?

A: Yes, by using multiple <class> 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 <property> elements inside the <class> element. Q: What are derived properties?

A: The properties that are not mapped to a column, but calculated at

(3)

expression can be defined using the formula attribute of the <property> 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 <subclass> elements one for each sub-class inside the <class> element. The <subclass> class element can in turn contain other <subclass> elements.

Q: How do you achieve table-per-subclass while mapping classes in Hibernate?

A: By using <joined-subclass> element inside the <class> element. A <joined-subclass> element may contain other <joined-subclass> elements. Q: Does hibernate allow mixing class hierarchy and table-per-subclass strategies?

A: No, you cannot have a <joined-subclass> inside <subclass> 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

1

Transaction beginTransaction()

Begin a unit of work and return the associated Transaction object.

2

void cancelQuery()

Cancel the execution of the current query.

3

void clear()

(4)

4

Connection close()

End the session by releasing the JDBC connection and cleaning up.

5

Criteria createCriteria(Class persistentClass)

Create a new Criteria instance, for the given entity class, or a superclass of an entity class.

6

Criteria createCriteria(String entityName)

Create a new Criteria instance, for the given entity name.

7

SerializablegetIdentifier(Object object)

Return the identifier value of the given entity as associated with this session.

8

Query createFilter(Object collection, String queryString)

Create a new instance of Query for the given collection and filter string.

9

Query createQuery(String queryString)

Create a new instance of Query for the given HQL query string.

10

SQLQuerycreateSQLQuery(String queryString)

Create a new instance of SQLQuery for the given SQL query string.

11

void delete(Object object)

Remove a persistent instance from the datastore.

12

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

13

Session get(String entityName, Serializable id)

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

14

SessionFactorygetSessionFactory()

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

(5)

Re-read the state of the given instance from the underlying database.

16

Transaction getTransaction()

Get the Transaction instance associated with this session.

17

booleanisConnected()

Check if the session is currently connected.

18

booleanisDirty()

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

19

booleanisOpen()

Check if the session is still open.

20

Serializable save(Object object)

Persist the given transient instance, first assigning a generated identifier.

21

void saveOrUpdate(Object object)

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

22

void update(Object object)

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

23

void update(String entityName, Object object)

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

(6)

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.

hibernate.show_sql

Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.

e.g.true | false

hibernate.format_sql

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

hibernate.default_schema

Qualify unqualified table names with the given schema/tablespace in generated SQL.

e.g.SCHEMA_NAME

hibernate.default_catalog

Qualifies unqualified table names with the given catalog in generated SQL.

e.g.CATALOG_NAME

hibernate.session_factory_name

The org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created.

e.g.jndi/composite/name

hibernate.max_fetch_depth

Sets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching.

e.g. recommended values between 0 and 3

hibernate.default_batch_fetch_size

Sets a default size for Hibernate batch fetching of associations. e.g. recommended values 4, 8, 16

hibernate.default_entity_mode

Sets a default mode for entity representation for all sessions opened from this SessionFactory

(7)

roperty name Purpose

hibernate.order_updates

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

hibernate.generate_statistics

If enabled, Hibernate will collect statistics useful for performance tuning.

e.g.true | false

hibernate.use_identifier_rollback

If enabled, generated identifier properties will be reset to default values when objects are deleted.

e.g.true | false

hibernate.use_sql_comments

If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false.

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. Most applications will not need this configuration property.

e.g.classname.of.BatcherFactory

(8)

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

hibernate.jdbc.use_get_generated_key s

Enables use of JDBC3

PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the 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 custom

org.hibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate.

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

(9)

Property name Purpose

for the JDBC transaction strategy.

e.g.auto (default) | on_close | after_transaction | after_statement

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

hibernate.cache.provider_class

The classname of a custom CacheProvider. e.g.classname.of.CacheProvider

hibernate.cache.use_minimal_puts

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

hibernate.cache.use_second_level_cach e

Can be used to completely disable the second level cache, which is enabled by default for classes which specify a mapping.

e.g.true|false

hibernate.cache.query_cache_factory

The classname of a custom

QueryCacheStandardQueryCache. interface, defaults to the built-in

(10)

Property name Purpose hibernate.cache.region_prefix

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

hibernate.cache.use_structured_entries

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

hibernate.transaction.manager_lookup_class

The classname of a TransactionManagerLookup. It is required when JVM-level caching is enabled or when using hilo generator in a JTA environment.

e.g.classname.of.TransactionManagerLookup

hibernate.transaction.flush_before_completio n

If enabled, the session will be automatically flushed during the before completion phase of the transaction. Built-in and automatic session context management is 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.

(11)

Miscellaneous Properties

Property name Purpose

hibernate.current_session_context_clas s

Supply a custom strategy for the scoping of the "current" Session. See Section 2.5, “Contextual sessions” for more information about the built-in strategies.

e.g.jta | thread | managed | custom.Class

hibernate.query.factory_class

Chooses the HQL parser implementation.

e.g.org.hibernate.hql.ast.ASTQueryTranslatorFactory or org.hibernate.hql.classic.ClassicQueryTranslatorFactory

hibernate.query.substitutions

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 create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g.validate | update | create | create-drop

hibernate.cglib.use_reflection_optimizer

Enables the use of CGLIB instead of runtime reflection (System-level property). Reflection can sometimes be useful when troubleshooting. Hibernate always requires 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.

(12)

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

References

Related documents

Results of the survey are categorized into the following four areas: primary method used to conduct student evaluations, Internet collection of student evaluation data,

Marie Laure Suites (Self Catering) Self Catering 14 Mr. Richard Naya Mahe Belombre 2516591 info@marielauresuites.com 61 Metcalfe Villas Self Catering 6 Ms Loulou Metcalfe

Asst Finance Executive Consultant-SKP Cross Consultant Head Finance CFO Director - Finance Technical Head Accounts Executive VP-Finance MD Finance Executive Manager

UPnP Control Point (DLNA) Device Discovery HTTP Server (DLNA, Chormecast, AirPlay Photo/Video) RTSP Server (AirPlay Audio) Streaming Server.. Figure 11: Simplified

12 Data Science Master Entrepreneur- ship Data Science Master Engineering entrepreneurship society engineering. Eindhoven University of Technology

The study explored the experiences of Barghar-Mukhiyas and other Tharu leaders in the community and their traditions and customs on conflict resolution practiced at research

proyecto avalaría tanto la existencia de una demanda real e insatisfe- cha de este servicio por parte de la población titular de derechos como la capacidad de ambos

innovation in payment systems, in particular the infrastructure used to operate payment systems, in the interests of service-users 3.. to ensure that payment systems