Hibernate

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What's lazy fetching in hibernate in Hibernate?

It loads the child objects on demand. Since Hibernate 3, lazy loading is enabled by default, and you don't need to do lazy="true". It means not to load the child objects when the parent is loaded.

what is ORM?

ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation, and data access.

Which element of hbm.xml is used to map a java.util.SortedMap property in hibernate?

This is mapped with a <map> element and initialized with java.util.TreeMap. The sort attribute can be set to either a comparator or natural ordering.

Which element of hbm.xml is used to map a java.util.Set property in hibernate?

This is mapped with a <set> element and initialized with java.util.HashSet.

Which element of hbm.xml is used to map a java.util.SortedSet property in hibernate?

This is mapped with a <set> element and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering.

What are the best practices that hibernate recommends for persistent classes.

1. All Java classes that will be persisted need a default constructor. 2. All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table. 3. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style. 4. A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods. 5. All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

Mention some of the advantages of using ORM over JDBC.

1. Application development is fast. 2. Management of Transaction. 3. Generates key automatically 4. Details of SQL queries are hidden 5. Lets business code access objects rather than DB tables. 6. No need to deal with the database implementation. 7. Entities based on business concepts rather than database structure.

What are the core interfaces of Hibernate?/ List the key components of Hibernate.

1. Configuration: represents a configuration or properties file required by Hibernate 2. SessionFactory: configures Hibernate for the application using the supplied configuration file and allows for Session object to be instantiated 3. Session: used to get a physical connection with the database 4. Transaction: represent a unit of work with the database, and most of RDBMS support Transaction functionality 5. Criteria: used to create and execute object oriented criteria queries to retrieve objects 6. Query: Use SQL or Hibernate Query Language(HQL) to retrieve data from the database and create objects

Mention two components of Hibernate configuration object.

1. Database Connection: handled through one or more configuration files supported by Hibernate: hibernate.properties and hibernamte.cfg.xml 2. Class mapping setup: create the connection between java classes and database tables

What are the advantages of using Hibernate?

1. Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. 2. Provides simple APIs for storing and retrieving Java objects directly to and from the database. 3. If there is change in Database or in any table then the only need to change XML file properties. 3. Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. 4. Hibernate does not require an application server to operate. 5. Manipulates Complex associations of objects of your database. 6. Minimize database access with smart fetching strategies. 7. Provides Simple querying of data.

How many types of association mapping are possible in hibernate?

1. One to One 2. One to Many 3. Many to One 4. Many to Many

What are the inheritance mapping strategies?

1. Table per hierarchy: In table per hierarchy mapping, single table is required to map the whole hierarchy, an extra column (known as discriminator column) is added to identify the class. But nullable values are stored in the table . 2. Table per concrete class: In case of table per concrete class, tables are created as per class. But duplicate column is added in subclass tables. 3. Table per subclass: In this strategy, tables are created as per class but related by foreign key. So there are no duplicate columns.

What's the possible ways to configure Hibernate framework?/What are possible ways to configure object-table mapping?

1. XML: create an xml file defines the mapping between the database column and the class variable. The xml is known as mapping xml. An entry of every such xml needs to be done in the hibernate.cfg.xml in order to ensure that Hibernate recognizes and precompiles these bindings 2. annotations. Annotated Java classes are automatically scanned fro as long as the path of the folder is specified in the hibernate.cfg.xml. Before 4.0, only xml

Name some of the properties you would require to configure for a databases in a standalone situation.

1. hibernate.dialect: this property makes Hibernate generate the appropriate SQL for the chosen database 2. hibernate.connection.driver_class: the JDBC driver class 3. hibernate.connection.url: the JDBC URL to the database instance 4. hibernate.connection.username: the database username 5. hibernate.connection.password: the database password 6. hibernate.connection.pool_size: limit the number of connections waiting in the hibernate database connection pool 7. hibernate.connection.autocommit: allows autocommit mode to be used for the JDBC connection

How do you configure the dialect in hibernate.cfg.xml?

<property name="org.hibernate.dialect.MySQLDialect"> org.hibernate.dialect.MySQLDialect </property>

Which annotation is used to declare a class as a hibernate bean?

@Entity

How do we define the primary key value generation logic?

@Entity @Table(name="users") public class User{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) int userid; @Column(name="user_name") String username; String password; } GenerationType.AUTO GenerationType.IDENTITY GenerationType.SEQUENCE GenerationType.TABLE

How do we specify a different column name for the variables mapping?

@Entity @Table(name="users") public class User{ @Column(name="user_name") String username; String password; }

How do I specify table name linked to an entity using annotation?

@Entity @Table(name="users") public class User{ String username; String password; }

What is many-to-many association?

A Many-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. <many-to-many> element indicates that one object relates to many other objects and column attributes are used to link intermediate column.

What is Transaction in hibernate?

A Transaction represents a unit of work with the database and most of RDBMS supports transaction functionality. Transactions in Hibernate are handled by the underlying transaction manager and transaction(from JDBC or JTA). This is an optional object and Hibernate applications may choose not to use it, instead managing transactions in their own application code.

What are concurrency strategies?

A concurrency strategy is a mediator which responsible for storing items of data in the cache and retrieving them from the cache. If a second-level cache is enabled, we have to decide for each persistent class and collection, which cache concurrency strategy to be used. Transactional: use this strategy for read-mostly data where it is critical to the stale data in concurrent transactions, in the rare case of an update Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update Nonstrict-read-write: this strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern. Read-only: A concurrency strategy suitable for data which never changes. use it for reference data only

What is a dialect?

A dialect is a set of code files or a single file occasionally that defines the process of connecting database to Java class. A dialect in Hibernate plays the role of understanding the communication taking place with the underlying database. Whenever the underlying database changes, all you need to change in the Hibernate configuration is the dialect and database credentials. this is true as long as the code uses HQL queries hibernate.dialect property makes Hibernate to generate the appropriate SQL statements for the chosen database. Dialect is the SQL dialect that your database uses. Hibernate uses "dialect" configuration to know which database you are using so that it can convert hibernate query to database specific query.

What is one-to-one association?

A one-to-one association is similar to many-to-one association with a difference that the column will be set as unique. For example an address object can be associated with a single employee object. <many-to-one> element is used to define one-to-one association. The name attribute is set to the defined variable in the parent class. The column attribute is used to set the column name in the parent table which is set to unique so that only one object can be associated with an other object.

Where Object/relational mappings are defined in hibernate?

An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate how to map the defined class or classes to the database tables. We should save the mapping document in a file with the format <classname>.hbm.xml.

How does a variable in an entity connect to the database column?

By default, Hibernate looks for the column names matching the variable names in the class. However, it is also possible to specify different variable names and bind them to respective columns in the database.

How does JPA help in Hibernate framework?

Before the launch and acceptance of JPA as ORM standards, Hibernate used XML mapping to strict bind the hibernate Value objects to Database objects. This mapping was based on XML and hence prone to high errors and required more effort in configuring the mapping. With JPA, Hibernate simplified the process of mapping by enabling the scanning for JPA annotations. These annotations remove the need to use XML for the mapping.

Define persistent classes

Classes whose objects are stored in a database table

List some of the databases supported by Hibernate.

DB2 MySQL Oracle Sybase SQL Server Informix Dynamic Server HSQL PostgreSQL FrontBase

What are the configurations involved in Hibernate framework?

Database credentials Database dialect Database URL Caching levels ORM mapping Connection pool configuration Table creation mode - Create/Update

What is Hibernate configuration file?

Database credentials Database dialect Database URL Caching levels ORM mapping Connection pool configuration Table creation mode - Create/Update ################### JDBC Configuration ########################## jdbc.driverClassName=org.mysql.jdbcDriver jdbc.url=jdbc:mysql://localhost:3306/mydb;shutdown=true jdbc.username=root jdbc.password=xxxxxx ################### Hibernate Configuration ########################## hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update hibernate.generate_statistics=true This file can be given any name. However, it is necessary to load this configuration in the Java file using this file name. A sample code to load the properties file in the Java configuration is shown below. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.ClassPathResource; @Import({RepositoryConfig.class}) @Configuration public class AppConfig { // @Bean public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocation(new ClassPathResource("hibernate.properties")); ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; } } It can be noticed that in a Java based configuration, the class code contains few Spring framework classes as well. Thus, this sample belongs to integration of Hibernate with Spring. Notice the annotations carefully over here. These annotations define that the class carries configuration for hibernate.

Name some of the ORM frameworks based on JAVA.

Enterprise JavaBeans Entity Beans Java Data Objects Castor TopLink Spring DAO Hibernate

What is the difference between first level cache and second level cache?

First Level Cache: associated with Session, enabled by default. it is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database. Second Level Cache: associated with SessionFactory, not enabled by default. it is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions

What does HQL stand for?

Hibernate Query Language

What is HQL (Hibernate Query Language)?

Hibernate Query Language is known as an object-oriented query language, and it is database independent. It is like a structured query language (SQL). The main advantage of HQL over SQL is: You don't need to learn SQL Database independent Simple to write a query

What is Query level cache in hibernate?

Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters

What is Hibernate framework?

Hibernate framework is a collection of Java classes built to simplify the process of database connection and interaction. Hibernate framework provides an intermediate layer of code between the database and Java code. This layer facilitates the configuration of database, connection pool, query execution as well as caching. Hibernate enables the developer to stay considerably independent of the changes of database.

How do we specify a variable to be primary key for the table?

Hibernate is able to create the database tables for an application directly based on the mappings that are provided in the Java code. In such a scenario, Hibernate requires to know which columns are expected to be primary keys. This can be configured using the annotation @Id. Hibernate not only takes care of creating this column as primary key column but also validates its unique constraint during every database insertion and update.

What is hibernate?

Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate and retrieve data from the database. It is powerful, high performance object-relational persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks

How does Hibernate create the database connection?

Hibernate reads the configured dialect to decide the driver jar to be used. Hibernate comes pre-packaged with the database driver jars. These jars are same as the ones used for connecting to database using JDBC. Based on the dialect, Hibernate dynamically registers the respective driver class and uses the URL and credentials to connect to the database using JDBC in the backend

How to make an immutable class in hibernate?

If you mark a class as mutable="false", the class will be treated as an immutable class. By default, it is mutable="true".

What is one-to-many association?

In One-to-Many mapping association, an object can be can be associated with multiple objects. For example Employee object relates to many Certificate objects. A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element. <one-to-many> element of set element indicates that one object relates to many other objects.

What is a connection pool?

In an enterprise application, the application will be hit by numerous users. If the application server establishes a new connection for every request, it will be a burden on the database server. On the other hand, if there is a single database connection only, there will be a huge overhead of requests for query. Hence, it is preferred to have a limited number of database connections pre-configured in Hibernate. Hibernate framework ensures that new connections are established until the defined maximum limit is reached. Post the limit, Hibernate reuses the database connection object. Thus, Hibernate connection pool is a bunch of Database connection objects created for managing parallel communication with the database.

What is JPA?

JPA is an acronym for Java persistence API. This API from Java provides certain predefined annotations in Java which makes database ORM simpler. All you need to do is place these annotations above the class name and variables to map them to the database table.

What is lazy loading in hibernate?

Lazy loading in hibernate improves the performance. It loads the child objects on demand. Since Hibernate 3, lazy loading is enabled by default, and you don't need to do lazy="true". It means not to load the child objects when the parent is loaded.

Is it possible to perform collection mapping with One-to-One and Many-to-One?

No, collection mapping can only be performed with One-to-Many and Many-to-Many.

What's the Query in Hibernate

Query object use SQL or HQL to retrieve data from the database and create object. A Query instance is used to bind query parameters, limited the number of results returned by the query, and finally to execute the query.

Which element of hbm.xml is used to map a java.util.List property in hibernate?

This is mapped with a <list> element and initialized with java.util.ArrayList.

Which element of hbm.xml is used to map a java.util.Map property in hibernate?

This is mapped with a <map> element and initialized with java.util.HashMap.

What is Session?

Session object provides an interface between the application and data stored in the database, and it is used to get a physical connection with a database. Session interface provides methods to insert, update and delete the object. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. Session is not thread safe, should be created and destroyed as needed

How can we add criteria to a query?

Session.createCriteria. create a new Criteria instance, for the given entity class, or a super class of an entity class

How is HQL query created?

Session.createQuery

How is SQL query created in Hibernate?

Session.createSQLQuery

Which method is used to create a SQL query?

Session.createSQLQuery

Which method is used to remove a persistent instance from the datastore?

Session.delete()

Which method is used to get a persistent instance from the datastore?

Session.get(): return the persistent instance of the given name entity with the given identifier, or null if there is no such persistent instance

Which method is used to re-read the state of the given instance from the underlying database?

Session.refresh()

Which method is used to save the state of the given instance from the underlying database?

Session.save()

Which method is used to save or update the state of the given instance from the underlying database?

Session.saveOrUpdate()

Which method is used to update the state of the given instance from the underlying database?

Session.update()

What is SessionFactory?

The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache(optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session. The SessionFactory is a thread safe object and used by all threads of an application. It is usually created during application start up and kept for later use. One SessionFactory per database using a separate configuration file.

Which element of hbm.xml defines a specific mappings from a Java classes to the database tables?

The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

Which element of hbm.xml is used to automatically generate the primary key values?

The <generator> element within the id element is used to automatically generate the primary key values. Set the class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.

Which element of hbm.xml defines maps the unique ID attribute in class to the primary key of the database table?

The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

Which element of hbm.xml is used to map a Java class property to a column in the database table?

The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

What is a configuration object in hibernate?

The Configuration object is the first Hibernate object created in any Hibernate applications. usually create once during application initialization. represent a configuration or properties file required by the Hibernate.

What is automatic dirty checking in hibernate?

The automatic dirty checking feature of Hibernate, calls update statement automatically on the objects that are modified in a transaction. Let's understand it by the example given below: ... SessionFactory factory = cfg.buildSessionFactory(); Session session1 = factory.openSession(); Transaction tx=session2.beginTransaction(); Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101)); e1.setSalary(70000); tx.commit(); session1.close(); Here, after getting employee instance e1 and we are changing the state of e1. After changing the state, we are committing the transaction. In such a case, the state will be updated automatically. This is known as dirty checking in hibernate.

What is root node of hbm.xml?

The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements.

Define criteria in terms of Hibernate.

The objects of criteria are used for the creation and execution of the object-oriented criteria queries

Which element of hbm.xml is used to map a java.util.Collection property in hibernate?

This is mapped with a <bag> or <ibag> element and initialized with java.util.ArrayList.

What are the states of the object in hibernate?

Transient: transient − A new instance of a a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate. Persistent: if a session is open, and save to the database or retrieved the instance from the database. A persistent instance has a representation in the database, an identifier value and is associated with a Session. Detached: an object is in a detached state if a session is closed. Call lock() or update() to converse detached state into persistent state

What is the purpose of Session.beginTransaction() method?

begin a unit of work and return the associated Transaction object

What is the difference between get and load method?

get(): return null if an object is not found, always hit the database, return the real object, use if not sure the instance exists load(): throws ObjectNotFoundException if the object is not found; not hit the database; return proxy object, use if know an instance exists

Hibernate openSession() vs getCurrentSession()

openSession: When you call SessionFactory.openSession, it always create new Session object afresh and give it to you. You need to explicitly flush and close these session objects. As session objects are not thread safe, you need to create one session object per request in multithreaded environment and one session per request in web applications too. getCurrentSession: When you call SessionFactory. getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope. When you call SessionFactory. getCurrentSession , it creates a new Session if not exists , else use same session which is in current hibernate context. It automatically flush and close session when transaction ends, so you do not need to do externally. If you are using hibernate in single threaded environment , you can use getCurrentSession, as it is faster in performance as compare to creating new session each time. You need to add following property to hibernate.cfg.xml to use getCurrentSession method. <session-factory> <!-- Put other elements here --> <property name="hibernate.current_session_context_class"> thread </property> </session-factory> otherwise get HibernateException

What is the difference between session.save() and session.persist() method?

public Serializable save(Object o); return the id of the instance public void persist(Object o)

What is many-to-one association?

the most common kind of association where an Object can be associated with multiple objects. <many-to-one> element is used to define many-to-one association. The name attribute is set to the defined variable in the parent class. The column attribute is used to set the column name in the parent table.

What is the difference between update and merge method?

update() should be used if the session doesn't contain an already persistent state with the same id. It means an update should be used inside the session only. After closing the session, it will throw the error. merge() should be used if you don't know the state of the session, means you want to make the modification at any time.


Set pelajaran terkait

The Founding and the Constitution

View Set

FINAL EXAM PEDI 2023/ PrepU CH26

View Set

Actividades turísticas en la ciudad

View Set

Fundamental Principles and Documents that influenced the Writing of the Constitution

View Set

AP Statistics Semester 2 Quiz/Checkpoint Questions

View Set

Chapter 23 - Functions of the Liver

View Set

intro to marketing: chapter 10 questions

View Set

Data Analysis: Descriptive and Inferential Statistics -Chapter 14

View Set