Interview Questions On Java,Java EE


Enter your email address:



Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Sunday, January 3, 2010

How to use Annotations with Hibernate?

Before getting into details of using annotations with Hibernate, I would suggest you to go through the previous example . The example posted here is similar to the old one except it uses annotations.Here .hbm.xml will not be required.

In addition to existing jar files, following jar files are also required in class path:

-hibernate-commons-annotations.jar
-ejb3-persistence.jar
-hibernate-annotations.jar

Download these binaries from here

The annotations are supported Java 5 environment(both by Java SE 5.0 and Java EE 5.0) onwards and having strong coupling with under lying database.In order to support multiple databases, annotations are not meant for that and better to use hibernate mapping files.

Let us start writing with Department.java class:
package com.iqjava.department; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="DEPTT") public class Department { private long departmentId; private String departmentName; public Department() { } public Department(String departmentName) { this.departmentName = departmentName; } @Id @GeneratedValue @Column(name="DEPTT_ID") public long getDepartmentId() { return this.departmentId; } public void setDepartmentId(long departmentId) { this.departmentId = departmentId; } @Column(name="DEPTT_NAME", nullable=false) public String getDepartmentName() { return this.departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } }


Some highlights of the above code:

- Hibernate supports EJB 3 Annotations persistence which are contained inside javax.persistence package.
The following annotations are used in the above code:

-@Entity: represents the Entity bean class.
-@Table: underlying RDBMS table is mapped with this tag where data is persisted.If this annotation is not mentioned then Hibernate takes class name as default table name
-@Id: represents identifier property of Entity bean class.It determines default access strategy used by Hibernate.So if @Id is put over field then field access will be used and if it is placed over getter method then property access will be used.
-@GenertaedValue: specify Primary Key generation strategy
-@Column: represents the column of the table to which a property is mapped to

hibernate.cfg.xml looks like as given below:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="connection.password"></property> <property name="connection.pool_size">1</property> <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping class="com.iqjava.department.Department" /> </session-factory> </hibernate-configuration>


In HibernateUtil.java file, AnnotationConfiguration object is used instead of Configuration object.

package com.iqjava.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Continue reading...

Wednesday, November 4, 2009

How to persist the java objects using Hibernate ORM framework?

The answer to this question takes the form of a tutorial, where I will go in details, step by step. Hibernate reduces number of lines of coding/writing SQLs for persisting object into the database considerably. This takes focus from doing repetitive work to focus on implementing business logic to address a business problem.

Hibernate uses a object relation mapping file in form of an XML or properties file. In this file there exists a mapping between a Java object and corresponding database table.First thing first, let us create the needed environment to achieve our objective.

We need following tools and binaries:

1.The IDE used is Eclipse Galileo(latest one while writing this post).
2.Hibernate binaries(Hibernate Core 3.3.2 GA and Hibernate Tools 3.2.4 GA)can be downloaded from here
3.Database HSQLDB 1.9

The next step is unzip Hibernate Tools 3.2.4 GA and put features and plugins contents to features and plugins directory of Eclipse Galileo. Ensure you have closed Eclipse IDE prior to this step and once you are done with copying part then restart the Eclipse Galileo.


You have to ensure following JARs have been included in the project:


-hibernate3.jar(contains all core Hibernate files)
-antlr-2.7.6.jar
-commons-collections-3.1.jar
-dom4j-1.6.1.jar
-javassist-3.9.0.GA.jar
-jta-1.1.jar
-slf4j-api-1.5.8.jar(used for logging purposes)
-slf4j-simple-1.5.8.jar(download it from here)
-hsqldb.jar(used for connecting to HSQL Database)


Once all above steps are over then choose Hibernate perspective in Eclipse IDE.Go to Window-Open Perspective-Other and select Hibernate perspective as show in the image given below:


Next step is to define object relation mapping XML file which has .hbm.xml extension. First create a package named com.iqjava.employee and inside this package we will create a new OR mapping XML named 'employee.hbm.xml'.(Right click on package com.iqjava.employee, select New -Hibernate XML Mapping File)


having contents as given below:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.iqjava.employee.Employee" table="EMP"> <meta attribute="class-description"> This class contains the employee details. </meta> <id name="employeeId" type="long" column="EMP_ID"> <generator class="native"/> </id> <property name="employeeName" type="string" column="EMP_NAME" not-null="true" /> </class> </hibernate-mapping>


In this OR Mapping file, class element depicts the class which will be mapped with an underlying table of RDBMS, in this case EMP table.The id element represents primary key of the table wherein attribute name represents a variable(employeeId) in Java class which is mapped with the column (attribute of id element) of the table(EMP_ID).

The type attribute represents the hibernate mapping type which will convert data from Java String type to underlying database String datatype .The generator element is used for automatically generate the primary key values.The native value of class attributes ascertain that hibernate picks either identitysequence or hilo algorithm depending upon the capabilities of the underlying database. The property element is used to link a property in the Java class to a column in the database table.

The next step is to create Hibernate configuration file.Select 'src' folder, right click and choose New--Hibernate Configuration File menu option.


The following wizard window will appear and you will have to enter the data as shown in the picture given below:



The content of the Hibernate configuration file is shown as below:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="connection.password"></property> <property name="connection.pool_size">1</property> <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping resource="com/iqjava/employee/employee.hbm.xml"/> </session-factory> </hibernate-configuration>

Once you are done with this step then next step is to create a new a Hibernate console configuration. To do this right click the project folder, select New --- Hibernate Console Configuration.The following Wizard appears:





By default the wizard will load the Hibernate configuration file information. Just click the Finish button to create the Hibernate console configuration.
Once above step is done, you can generate code by selecting the Hibernate Code Generation Configurations option form Run option on toolbar as depicted below:


Once the Wizard shows up, please ensure following tabs have details according to images shown as below:




Once all these settings are ensured then hit Run button and you get Employee.java file being generated from .hbm.xml file and its contents are as shown below:
package com.iqjava.employee; // Generated Nov 3, 2009 6:02:21 PM by Hibernate Tools 3.2.4.GA /** * This class contains the employee details. */ public class Employee implements java.io.Serializable { private long employeeId; private String employeeName; public Employee() { } public Employee(String employeeName) { this.employeeName = employeeName; } public long getEmployeeId() { return this.employeeId; } public void setEmployeeId(long employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return this.employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } }
Now we create HibernateUtil.java file which creates a SessionFactory from the Hibernate configuration file. The implementation of HibernateUtil.java is given as below:


package com.iqjava.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure() .buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }

The next step is to create an ExecutionClass.java. The implementation of this class is given as below:

package com.iqjava.employee; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.List; import java.util.Iterator; import com.iqjava.util.HibernateUtil; public class ExecutionClass { public static void main(String[] args) { ExecutionClass obj = new ExecutionClass(); Long empId1 = obj.saveEmployee("John"); Long empId2 = obj.saveEmployee("Paul"); Long empId3 = obj.saveEmployee("Bill"); obj.listEmployee(); System.out.println("Updating emp3...."); obj.updateEmployee(empId3, "Michael"); System.out.println("Deleting emp2...."); obj.deleteEmployee(empId2); System.out.println("List employees...."); obj.listEmployee(); } public Long saveEmployee(String employeeName) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; Long empId = null; try { transaction = session.beginTransaction(); Employee emp = new Employee(); emp.setEmployeeName(employeeName); empId = (Long) session.save(emp); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } return empId; } public void listEmployee() { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); List emps = session.createQuery("from Employee").list(); for (Iterator iterator = emps.iterator(); iterator.hasNext();) { Employee emp = (Employee) iterator.next(); System.out.println(emp.getEmployeeName()); } transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } public void updateEmployee(Long empId, String employeeName) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Employee emp = (Employee) session.get(Employee.class, empId); emp.setEmployeeName(employeeName); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } public void deleteEmployee(Long empId) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Employee emp = (Employee) session.get(Employee.class, empId); session.delete(emp); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } }

The code details of the above are self explanatory.The project structure in Eclipse is depicted as shown below:

Before executing the ExecutionClass.java., please ensure you have started the HSQLDB server as depicted in image shown below



Once the code in ExecutionClass.java is executed then console of Eclipse IDE shows following output:
31 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.2.GA 31 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 47 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 47 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 219 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml 219 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml 437 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : com/iqjava/employee/employee.hbm.xml 594 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: com.iqjava.employee.Employee -> EMP 625 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null 750 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 750 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 1 750 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 781 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://localhost 781 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=sa, password=****} 1140 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: HSQL Database Engine, version: 1.9.0 1140 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: HSQL Database Engine Driver, version: 1.9.0 1203 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.HSQLDialect 1219 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 1219 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 1219 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 1234 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 1234 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 1359 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 1797 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 1812 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - Running hbm2ddl schema export 1812 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - exporting generated schema to database 1812 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - schema export complete Hibernate: insert into EMP (EMP_ID, EMP_NAME) values (null, ?) Hibernate: insert into EMP (EMP_ID, EMP_NAME) values (null, ?) Hibernate: insert into EMP (EMP_ID, EMP_NAME) values (null, ?) Hibernate: select employee0_.EMP_ID as EMP1_0_, employee0_.EMP_NAME as EMP2_0_ from EMP employee0_ John Paul Bill Updating emp3.... Hibernate: select employee0_.EMP_ID as EMP1_0_0_, employee0_.EMP_NAME as EMP2_0_0_ from EMP employee0_ where employee0_.EMP_ID=? Hibernate: update EMP set EMP_NAME=? where EMP_ID=? Deleting emp2.... Hibernate: select employee0_.EMP_ID as EMP1_0_0_, employee0_.EMP_NAME as EMP2_0_0_ from EMP employee0_ where employee0_.EMP_ID=? Hibernate: delete from EMP where EMP_ID=? List employees.... Hibernate: select employee0_.EMP_ID as EMP1_0_, employee0_.EMP_NAME as EMP2_0_ from EMP employee0_ John Michael

Check if the database schema is created and the data is inserted into the EMP table or not. Simply open a new command prompt, go to the hsqldb installed directory and type the following command.
java -cp ./lib/hsqldb.jar org.hsqldb.util.DatabaseManager
The dialog box as shown below pops up


and here select Type as "HSQL Database Engine Server" and click Ok.You see the HSQL Database Manager window as shown below, type the SQL as shown and press execute button. The result shown depicts data existing in the database.


One can exit from the database by typing 'shutdown' and hitting Execute button.
Continue reading...

Sunday, October 21, 2007

Explain different inheritance mapping models in Hibernate.

There can be three kinds of inheritance mapping in hibernate

1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass

Example:
We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and UtilityVan.

1. Table per concrete class with unions
In this scenario there will be 2 tables
Tables: Car, UtilityVan, here in this case all common attributes will be duplicated.

2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.
Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan

3. Table per subclass
Simply there will be three tables representing Vehicle, Car and UtilityVan
Continue reading...

Thursday, June 14, 2007

Can you compare JDBC/DAO with Hibernate?

Hibernate and straight SQL through JDBC are different approaches.They both have their specific significance in different scenarios.If your application is not to big and complex,not too many tables and queries involved then it will be better to use JDBC. While Hibernate is a POJO based ORM tool,using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset,meaning less LOC but more of configuration work.It will suit better when you have large application involving large volume of data and queries.Moreover lazy loading,caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.
Continue reading...

Interview Questions on Hibernate

Continue reading...

What are different fetch strategies Hibernate have?

A fetching strategy in Hibernate is used for retrieving associated objects if the application needs to navigate the association. They may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

Hibernate3 defines the following fetching strategies:

Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is loaded.

Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)

"Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)

Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.

"No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.

Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.

We use fetch to tune performance. We may use lazy to define a contract for what data is always available in any detached instance of a particular class.

[Source:Hibernate Reference Documentation]

Continue reading...

Wednesday, June 13, 2007

What is dirty checking in Hibernate?

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.
Continue reading...

More Hibernate Questions

Question: What are common mechanisms of configuring Hibernate?
Answer: 1. By placing hibernate.properties file in the classpath.
2. Including elements in hibernate.cfg.xml in the classpath.

Question:How can you create a primary key using Hibernate?
Answer: The 'id' tag in .hbm file corresponds to primary key of the table:

Here Id ="empid", that will act as primary key of the table "EMPLOYEE".

Question: In how many ways one can map files to be configured in Hibernate?
Answer: 1. Either mapping files are added to configuration in the application code or,
2.hibernate.cfg.xml can be used for configuring in .

Question: How to set Hibernate to log all generated SQL to the console?
Answer: By setting the hibernate.show_sql property to true.

Question: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
Answer: The settings of the XML configuration file will override the settings used in the properties.

Question: What methods must the persistent classes implement in Hibernate?
Answer: 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.

Question: How can Hibernate be configured to access an instance variable directly and not through a setter method?
Answer: 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.

Question: How to declare mappings for multiple classes in one mapping file?
Answer:Use multiple elements. But, the recommended practice is to use one mapping file per persistent class.

Question: How are the individual properties mapped to different table columns?
Answer: By using multiple elements inside the element.

Question: What are derived properties?
Answer: 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.

Question: How can you make a property be read from the database but not modified in anyway (make it immutable)?
Answer: Use insert="false" and update="false" attributes.

Question: How can a whole class be mapped as immutable?
Answer: By using the mutable="false" attribute in the class mapping.

Continue reading...

What are core interfaces for Hibernate framework?

Most Hibernate-related application code primarily interacts with four interfaces provided by Hibernate Core:

org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query

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 thread safe.

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.

The Criteria provides a provision for conditional search over the resultset.One can retrieve entities by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually obtained via the factory methods on Restrictions.

Query represents object oriented representation of a Hibernate query. A Query instance is obtained by calling Session.createQuery().
Continue reading...
 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker