本文共 46612 字,大约阅读时间需要 155 分钟。
hibernate面试问题
Hibernate is one of the most widely used ORM tool for Java applications. It’s used a lot in enterprise applications for database operations. So I decided to write a post about hibernate interview questions to brush up your knowledge before the interview.
Hibernate是Java应用程序中使用最广泛的ORM工具之一。 在企业应用程序中,数据库操作经常使用它。 因此,我决定写一篇有关冬眠面试问题的文章,以在面试前梳理您的知识。
Whether you are fresher or experienced, having good knowledge or Hibernate ORM tool helps in cracking interview. Here I am providing important hibernate interview questions with answers to help you brush up your knowledge and impress your interviewer. Just like other interview questions posts, chances are that I will be adding more questions to this list in future, so you might want to bookmark it for future reference.
无论您是新手还是经验丰富的人,都有丰富的知识或Hibernate ORM工具都可以帮助您进行面试。 在这里,我提供了重要的冬眠面试问题以及答案,以帮助您提高知识水平并打动面试官。 就像其他面试问题帖子一样,将来我可能会在此列表中添加更多问题,因此您可能希望将其添加书签以供将来参考。
Recently I have written a lot of posts on hibernate, most of them contains complete downloadable projects. I will provide reference to them as and when needed and you can go through them to refresh your knowledge.
最近,我写了很多关于Hibernate的文章,其中大多数包含完整的可下载项目。 我将在需要时为他们提供参考,您可以遍历它们以更新您的知识。
Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.
Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.
Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically. For a quick overview of hibernate framework usage, you can go through .
对象关系映射或对象关系管理 (ORM)是将应用程序域模型对象映射到关系数据库表的编程技术。 Hibernate是基于Java的ORM工具,它提供了用于将应用程序域对象映射到关系数据库表,反之亦然的框架。
Hibernate提供了Java Persistence API的参考实现,这使其成为具有松耦合优势的ORM工具的绝佳选择。 我们可以使用Hibernate持久性API进行CRUD操作。 Hibernate框架提供了使用JPA注释以及基于XML的配置将普通的旧Java对象映射到传统数据库表的选项。
同样,Hibernate配置也很灵活,可以从XML配置文件以及以编程方式完成。 要快速了解hibernate框架的用法,可以阅读 。
Java Persistence API (JPA) provides specification for managing the relational data in applications. Current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013.
JPA specifications is defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code.
Java Persistence API(JPA)提供了用于管理应用程序中的关系数据的规范。 当前的JPA 2.1版于2011年7月作为JSR 338开始。JPA2.1于2013年5月22日获得最终批准。
JPA规范是使用javax.persistence包中的注释定义的。 使用JPA注释有助于我们编写独立于实现的代码。
Some of the important benefits of using hibernate framework are:
Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.
使用Hibernate框架的一些重要好处是:
整体Hibernate是当前ORM工具市场上的最佳选择,它包含您在ORM工具中将需要的所有功能。
Some of the important advantages of Hibernate framework over JDBC are:
SQLException
that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException
or HibernateException
un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.Hibernate框架相对于JDBC的一些重要优点是:
SQLException
,这是一个已检查的异常,因此我们需要编写许多try-catch块代码。 在大多数情况下,它在每个JDBC调用中都是多余的,并用于事务管理。 Hibernate包装JDBC异常并抛出JDBCException
或HibernateException
未经检查的异常,因此我们不需要编写代码来处理它。 Hibernate内置的事务管理消除了try-catch块的使用。 Some of the important interfaces of Hibernate framework are:
java.sql.Connection
and works as a factory for org.hibernate.Transaction
. We should open session only when it’s required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.Hibernate框架的一些重要接口是:
java.sql.Connection
并用作org.hibernate.Transaction
的工厂。 我们仅应在需要时打开会话,并在使用完毕后立即将其关闭。 会话对象是Java应用程序代码和Hibernate框架之间的接口,并提供CRUD操作的方法。 Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
Hibernate配置文件包含特定于数据库的配置,并用于初始化SessionFactory。 我们在Hibernate配置xml文件中提供数据库凭证或JNDI资源信息。 hibernate配置文件的其他一些重要部分是方言信息,因此hibernate知道数据库类型和映射文件或类详细信息。
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can’t use annotations.
Hibernate映射文件用于定义实体bean字段和数据库表列的映射。 我们知道JPA批注可以用于映射,但是当我们使用第三方类并且不能使用批注时,有时XML映射文件会派上用场。
Hibernate supports JPA annotations and it has some other annotations in org.hibernate.annotations
package. Some of the important JPA and hibernate annotations used are:
javax.persistence.GenerationType
enum.OneToMany
, ManyToOne
and ManyToMany
org.hibernate.annotations.CascadeType
org.hibernate.annotations.GenericGenerator
and org.hibernate.annotations.Parameter
Here are two classes showing usage of these annotations.
package com.journaldev.hibernate.model;import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToOne;import javax.persistence.Table;import org.hibernate.annotations.Cascade;@Entity@Table(name = "EMPLOYEE")@Access(value=AccessType.FIELD)public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "emp_id") private long id; @Column(name = "emp_name") private String name; @OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) private Address address; //getter setter methods}
Hibernate支持JPA批注,并且在org.hibernate.annotations
包中还有一些其他批注。 使用的一些重要的JPA和Hibernate注释是:
javax.persistence.GenerationType
枚举结合使用。 OneToMany
, ManyToOne
和ManyToMany
org.hibernate.annotations.CascadeType
结合使用 org.hibernate.annotations.GenericGenerator
和org.hibernate.annotations.Parameter
这是两个类,显示这些注释的用法。
package com.journaldev.hibernate.model;import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToOne;import javax.persistence.Table;import org.hibernate.annotations.Cascade;@Entity@Table(name = "EMPLOYEE")@Access(value=AccessType.FIELD)public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "emp_id") private long id; @Column(name = "emp_name") private String name; @OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) private Address address; //getter setter methods}
SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.
SessionFactory是用于获取Session对象的工厂类。 SessionFactory负责读取Hibernate配置参数,并连接到数据库并提供Session对象。 通常,应用程序具有单个SessionFactory实例,并且服务于客户端请求的线程从该工厂获取Session实例。
SessionFactory的内部状态是不可变的。 创建后,便会设置此内部状态。 此内部状态包括有关对象/关系映射的所有元数据。
SessionFactory还提供方法来获取Class元数据和Statistics实例以获取查询执行的统计信息,二级缓存详细信息等。
Internal state of SessionFactory is immutable, so it’s thread safe. Multiple threads can access it simultaneously to get Session instances.
SessionFactory的内部状态是不可变的,因此是线程安全的。 多个线程可以同时访问它以获取Session实例。
Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction.
Session provide methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.
Hibernate Session是Java应用程序层和hibernate之间的接口。 这是用于执行数据库操作的核心接口。 会话的生命周期受事务的开始和结束的约束。
会话提供了对持久对象执行创建,读取,更新和删除操作的方法。 我们可以执行HQL查询,SQL本机查询并使用Session对象创建条件。
Hibernate Session object is not thread safe, every thread should get it’s own session instance and close it after it’s work is finished.
Hibernate Session对象不是线程安全的,每个线程都应获取其自己的会话实例,并在工作完成后将其关闭。
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.
thread
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.
There is another method openStatelessSession() that returns stateless session, for more details with examples please read .
Hibernate SessionFactory的getCurrentSession()方法返回绑定到上下文的会话。 但是要使其正常工作,我们需要在Hibernate配置文件中对其进行配置。 由于此会话对象属于Hibernate上下文,因此我们不需要关闭它。 会话工厂关闭后,该会话对象将关闭。
Hibernate SessionFactory的openSession()方法总是打开一个新的会话。 一旦完成所有数据库操作,就应该关闭该会话对象。 我们应该在多线程环境中为每个请求打开一个新会话。
还有另一个方法openStatelessSession()返回无状态会话,有关示例的更多详细信息,请阅读 。
Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.
For clarification regarding the differences, please read .
Hibernate会话附带了多种从数据库加载数据的方法。 get和load是最常用的方法,乍一看它们看起来很相似,但是它们之间有一些区别。
为了澄清差异,请阅读 。
As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.
Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.For better explanation, please read .
顾名思义,hibernate缓存查询数据以使我们的应用程序更快。 如果正确使用Hibernate Cache,在获得快速应用程序性能方面将非常有用。 缓存背后的想法是减少数据库查询的数量,从而减少应用程序的吞吐时间。
Hibernate一级缓存与会话对象相关联。 默认情况下,Hibernate一级缓存处于启用状态,无法禁用它。 但是,hibernate提供了一些方法,通过这些方法,我们可以从缓存中删除选定的对象或完全清除缓存。
会话中缓存的任何对象对其他会话都不可见,并且在关闭会话时,所有缓存的对象也将丢失。为了获得更好的解释,请阅读 。
EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.
org.hibernate hibernate-ehcache 4.3.5.Final
That’s it, we are done. Hibernate will use the EHCache for second level caching, read for a complete example with explanation.
EHCache是利用Hibernate二级缓存的最佳选择。 需要执行以下步骤才能在Hibernate应用程序中启用EHCache。
org.hibernate hibernate-ehcache 4.3.5.Final
就是这样,我们完成了。 Hibernate将使用EHCache进行二级缓存,请阅读以获取带有说明的完整示例。
An entity bean instance can exist is one of the three states.
实体bean实例可以存在的三个状态之一。
Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked. For example program, read .
Hibernate merge可用于更新现有值,但是此方法从传递的实体对象创建一个副本并将其返回。 返回的对象是持久性上下文的一部分,并跟踪任何更改,不跟踪传递的对象。 例如,请阅读程序。
Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately.
Hibernate persist is similar to save with transaction. I feel it’s better than save because we can’t use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn’t return the generated id immediately, so data persistence happens when needed.
Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed. For example usage of these methods, read .
Hibernate保存可用于将实体保存到数据库。 save()的问题在于它可以在没有事务的情况下被调用,并且如果我们有映射实体,那么只有主对象会被保存,从而导致数据不一致。 另外,save会立即返回生成的ID。
Hibernate的持久性类似于用事务保存。 我觉得它比保存好,因为我们不能在事务边界之外使用它,因此所有对象映射都被保留了。 而且persist不立即返回生成的id,因此在需要时会发生数据持久性。
Hibernate saveOrUpdate结果根据提供的数据插入或更新查询。 如果数据库中存在数据,则执行更新查询。 我们也可以在不使用事务的情况下使用saveOrUpdate(),但是如果会话未刷新,您将再次遇到映射对象无法保存的问题。 例如,使用这些方法,请阅读 。
Hibernate uses to create instance of Entity beans, usually when you call get() or load() methods. The method Class.newInstance()
is used for this and it requires no-args constructor. So if you won’t have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get HibernateException
.
通常在调用get()或load()方法时,Hibernate使用创建Entity bean的实例。 Class.newInstance()
使用方法Class.newInstance()
,它需要无参数的构造函数。 因此,如果您在实体bean中没有no-args构造函数,则hibernate将无法实例化它,并且您将获得HibernateException
。
When we use Collection API sorting algorithms to sort a collection, it’s called sorted list. For small collections, it’s not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement Comparable
or Comparator
interface for it to work, read more at .
If we are using Hibernate framework to load collection data from database, we can use it’s Criteria API to use “order by” clause to get ordered list. Below code snippet shows you how to get it.
ListempList = session.createCriteria(Employee.class) .addOrder(Order.desc("id")).list();
Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn’t cause memory issues.
当我们使用Collection API排序算法对集合进行排序时,称为排序列表。 对于小型集合,这不是很多开销,但是对于大型集合,这可能会导致性能降低和内存不足错误。 此外,实体bean还应实现Comparable
或Comparator
接口,以使其正常工作,有关更多信息,请 。
如果我们使用Hibernate框架从数据库加载收集数据,则可以使用其Criteria API使用“ order by”子句来获取有序列表。 下面的代码段显示了如何获取它。
有序列表比有序列表更好,因为实际的排序是在数据库级别完成的,这是快速的并且不会引起内存问题。
There are five collection types in hibernate used for one-to-many relationship mappings.
Hibernate中有五种收集类型用于一对多关系映射。
There are various ways to implement joins in hibernate.
在Hibernate中有多种实现联接的方法。
Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.
Hibernate仅在需要时才使用代理类延迟加载数据。 这是通过扩展实体Bean来完成的,如果实体Bean是最终的,则不可能进行延迟加载,因此会降低性能。
Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming.
Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as sELEct is the same as SELECT, but com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE.
The HQL queries are cached but we should avoid it as much as possible, otherwise we will have to take care of associations. However it’s a better choice than native sql query because of Object-Oriented approach. Read more at .
Hibernate Framework随附了功能强大的面向对象的查询语言-Hibernate Query Language(HQL)。 它与SQL非常相似,不同之处在于我们使用对象而不是表名,这使其更接近于面向对象的编程。
Hibernate查询语言不区分大小写,除了Java类和变量名。 因此,SeLeCT与sELEct相同,与SELECT相同,但是com.journaldev.model.Employee与com.journaldev.model.EMPLOYEE不同。
HQL查询已缓存,但我们应尽可能避免使用它,否则我们将不得不注意关联。 但是,由于面向对象的方法,它是比本地sql查询更好的选择。 在阅读更多内容。
Hibernate implements a cache region for queries resultset that integrates closely with the hibernate second-level cache.
This is an optional feature and requires additional steps in code. This is only useful for queries that are run frequently with the same parameters. First of all we need to configure below property in hibernate configuration file.
true
And in code, we need to use setCacheable(true) method of Query, quick example looks like below.
Hibernate为查询结果集实现了一个缓存区域,该区域与hibernate二级缓存紧密集成。
这是一项可选功能,需要其他代码步骤。 这仅对使用相同参数频繁运行的查询有用。 首先,我们需要在Hibernate配置文件中配置以下属性。
true
并且在代码中,我们需要使用Query的setCacheable(true)方法,快速示例如下所示。
Hibernate provide option to execute native SQL queries through the use of SQLQuery
object.
For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching. Read more at .
Hibernate提供了通过使用SQLQuery
对象执行本机SQL查询的选项。
对于正常情况,这不是推荐的方法,因为我们会失去与Hibernate关联和Hibernate一级缓存有关的好处。 在阅读更多内容。
Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.
当我们要执行Hibernate API不支持的特定于数据库的查询(例如查询提示或Oracle数据库中的CONNECT关键字)时,使用本地SQL查询非常方便。
Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.
Hibernate提供了命名查询,我们可以在中央位置进行定义并在代码中的任何位置使用它们。 我们可以为HQL和本机SQL创建命名查询。
可以在Hibernate映射文件中或通过使用JPA批注@NamedQuery和@NamedNativeQuery定义Hibernate命名查询。
Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code.
Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries. Hibernate Named Query is global, means once defined it can be used throughout the application.However one of the major disadvantage of Named query is that it’s hard to debug, because we need to find out the location where it’s defined.
Hibernate命名查询可帮助我们在中央位置对查询进行分组,而不是让它们分散在整个代码中。
创建Hibernate会话工厂时,将检查“Hibernate命名查询”语法,从而使应用程序在命名查询中发生任何错误的情况下快速失败。 Hibernate命名查询是全局的,这意味着一旦定义,它就可以在整个应用程序中使用。但是,命名查询的主要缺点之一是难以调试,因为我们需要找出定义它的位置。
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach.
Some of the common usage of Criteria API are:
Learn some quick examples at .
Hibernate提供的Criteria API更面向对象,用于查询数据库和获取结果。 我们无法使用条件来运行更新或删除查询或任何DDL语句。 它仅用于使用更多面向对象的方法从数据库中获取结果。
Criteria API的一些常见用法是:
在学习一些快速示例。
We can set below property for hibernate configuration to log SQL queries.
true
However we should use it only in Development or Testing environment and turn it off in production environment.
我们可以为Hibernate配置设置下面的属性,以记录SQL查询。
但是,我们应该仅在开发或测试环境中使用它,而在生产环境中将其关闭。
Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.
Hibernate使用代理对象来支持延迟加载。 基本上,当您从表中加载数据时,hibernate不会加载所有映射的对象。 通过getter方法引用子项或查找对象后,如果链接的实体不在会话缓存中,则代理代码将转到数据库并加载链接的对象。 它使用javassist有效且动态地生成实体对象的子类实现。
We can easily implement one-to-one, one-to-many and many-to-many relationships in hibernate. It can be done using JPA annotations as well as XML based configurations. For better understanding, you should go through following tutorials.
我们可以在Hibernate状态下轻松实现一对一,一对多和多对多关系。 可以使用JPA批注以及基于XML的配置来完成。 为了更好地理解,您应该阅读以下教程。
Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session beginTransaction()
to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction.
Overall hibernate transaction management is better than JDBC transaction management because we don’t need to rely on exceptions for rollback. Any exception thrown by session methods automatically rollback the transaction.
Hibernate状态下的事务管理非常容易,因为不允许在事务外部进行大多数操作。 因此,从SessionFactory获得会话后,我们可以调用会话beginTransaction()
启动事务。 此方法返回Transaction引用,以后可以用来提交或回滚该事务。
总体上,Hibernate事务管理比JDBC事务管理好,因为我们不需要依赖异常进行回滚。 会话方法抛出的任何异常都会自动回滚事务。
When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.
Here is a simple example of applying cascading between primary and secondary entities.
import org.hibernate.annotations.Cascade;@Entity@Table(name = "EMPLOYEE")public class Employee {@OneToOne(mappedBy = "employee")@Cascade(value = org.hibernate.annotations.CascadeType.ALL)private Address address;}
Note that Hibernate CascadeType enum constants are little bit different from JPA javax.persistence.CascadeType
, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example.
当我们在实体之间建立关系时,我们需要定义不同的操作将如何影响另一个实体。 这是通过级联完成的,并且有不同的类型。
这是在主要实体和次要实体之间应用级联的简单示例。
注意,Hibernate CascadeType枚举常量与JPA javax.persistence.CascadeType
有点不同,因此我们需要使用Hibernate CascadeType和Cascade批注进行映射,如上面的示例所示。
Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps.
DOMConfigurator
or PropertyConfigurator
. For web applications, you can use ServletContextListener to configure it.That’s it, our setup is ready. Create org.apache.log4j.Logger
instance in the java classes and start logging. For complete example code, you should go through and .
Hibernate 4使用JBoss日志记录,而不是早期版本中使用的slf4j。 对于log4j配置,我们需要执行以下步骤。
DOMConfigurator
或PropertyConfigurator
配置log4j。 对于Web应用程序,可以使用ServletContextListener对其进行配置。 就是这样,我们的设置已经准备就绪。 在java类中创建org.apache.log4j.Logger
实例并开始记录。 对于完整的示例代码,您应该阅读和 。
For web applications, it’s always best to allow servlet container to manage the connection pool. That’s why we define JNDI resource for DataSource and we can use it in the web application. It’s very easy to use in Hibernate, all we need is to remove all the database specific properties and use below property to provide the JNDI DataSource name.
java:comp/env/jdbc/MyLocalDB
For a complete example, go through .
对于Web应用程序,最好始终允许servlet容器管理连接池。 这就是为什么我们为DataSource定义JNDI资源并且可以在Web应用程序中使用它的原因。 在Hibernate中使用它非常容易,我们所需要做的就是删除所有数据库特定的属性,并使用以下属性提供JNDI DataSource名称。
有关完整的示例,请查看 。
Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. The best part with using Spring is that it provides out-of-box integration support for Hibernate with Spring ORM module. Following steps are required to integrate Spring and Hibernate frameworks together.
org.springframework.orm.hibernate3.LocalSessionFactoryBean
or org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
in Spring Bean configuration file. For Hibernate 4, there is single class org.springframework.orm.hibernate4.LocalSessionFactoryBean
that should be configured.@Transactional
annotation.For complete example go through and .
Spring是最常用的Java EE框架之一,而Hibernate是最流行的ORM框架。 这就是为什么Spring Hibernate组合在企业应用程序中大量使用的原因。 使用Spring最好的部分是它为带有Spring ORM模块的Hibernate提供了现成的集成支持。 需要执行以下步骤将Spring和Hibernate框架集成在一起。
org.springframework.orm.hibernate3.LocalSessionFactoryBean
或org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
。 对于Hibernate 4,应该配置单个类org.springframework.orm.hibernate4.LocalSessionFactoryBean
。 @Transactional
批注将其留给Spring声明式事务管理。 有关完整的示例,请通过和 。
When Spring and Hibernate integration started, Spring ORM provided two helper classes – HibernateDaoSupport
and HibernateTemplate
. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management. However from Hibernate 3.0.1, we can use SessionFactory
getCurrentSession() method to get the current session and use it to get the spring transaction management benefits. If you go through above examples, you will see how easy it is and that’s why we should not use these classes anymore.
One other benefit of HibernateTemplate
was exception translation but that can be achieved easily by using @Repository
annotation with service classes, shown in above spring mvc example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.
当Spring和Hibernate集成开始时,Spring ORM提供了两个帮助器类HibernateDaoSupport
和HibernateTemplate
。 使用它们的原因是从Hibernate获取Session并从Spring事务管理中受益。 但是从Hibernate 3.0.1开始,我们可以使用SessionFactory
getCurrentSession()方法来获取当前会话,并使用它来获得Spring事务管理的好处。 如果您看了上面的示例,您将看到它很容易,这就是为什么我们不再使用这些类的原因。
HibernateTemplate
另一个好处是异常翻译,但是可以通过对服务类使用@Repository
批注轻松实现,如上面的spring mvc示例所示。 这是一个判断您的知识以及是否知道最新进展的技巧。
Hibernate integration with Servlet or Struts2 needs to be done using ServletContextListener
, a complete example can be found at .
与Servlet或Struts2的Hibernate集成需要使用ServletContextListener
来完成,有关完整示例,请参见《 。
Some of the design patterns used in Hibernate Framework are:
Hibernate Framework中使用的一些设计模式是:
Some of the best practices to follow in Hibernate are:
@Access(value=AccessType.PROPERTY)
.在Hibernate中应遵循的一些最佳做法是:
@Access(value=AccessType.PROPERTY)
。 Data validation is integral part of any application. You will find data validation at presentation layer with the use of Javascript, then at the server side code before processing it. Also data validation occurs before persisting it, to make sure it follows the correct format.
Validation is a cross cutting task, so we should try to keep it apart from our business logic. That’s why JSR303 and JSR349 provides specification for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specs. Read more at .
数据验证是任何应用程序不可或缺的一部分。 您将在使用Javascript的表示层上找到数据验证,然后在处理它之前在服务器端代码上找到。 数据验证也将在持久化之前进行,以确保其遵循正确的格式。
验证是一项跨领域的任务,因此我们应尝试将其与业务逻辑分开。 这就是JSR303和JSR349提供使用注释来验证bean的规范的原因。 Hibernate Validator提供了这两个bean验证规范的参考实现。 在阅读更多信息。
Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or xml tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes before hand. Learn how to install and use at .
Hibernate Tools插件可帮助我们轻松地编写Hibernate配置和映射文件。 主要的好处是内容辅助可以帮助我们使用属性或xml标签。 它还会根据Hibernate DTD文件对它们进行验证,因此我们会事先知道任何错误。 在了解如何安装和使用。
That’s all for Hibernate Interview Questions and Answers, I hope it will help you for interview as a fresher or experienced person. Please let me know if I have missed any important question here, I will add that to the list.
这就是Hibernate面试问题和答案的全部内容,希望它对您来说是一个新鲜的或有经验的人,可以帮助您进行面试。 如果我错过了任何重要问题,请告诉我,我将其添加到列表中。
翻译自:
hibernate面试问题
转载地址:http://nrmzd.baihongyu.com/