博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hibernate面试问题_Hibernate面试问答
阅读量:2535 次
发布时间:2019-05-11

本文共 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的文章,其中大多数包含完整的可下载项目。 我将在需要时为他们提供参考,您可以遍历它们以更新您的知识。

Hibernate面试问题 (Hibernate Interview Questions)

Hibernate面试问答 (Hibernate Interview Questions and Answers)

  1. 什么是Hibernate Framework? (What is Hibernate Framework?)

    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框架的用法,可以阅读 。

  2. 什么是Java Persistence API(JPA)? (What is Java Persistence API (JPA)?)

    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注释有助于我们编写独立于实现的代码。

  3. 使用Hibernate Framework有哪些重要好处? (What are the important benefits of using Hibernate Framework?)

    Some of the important benefits of using hibernate framework are:

    1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
    2. Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
    3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
    4. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
    5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
    6. Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
    7. Hibernate cache helps us in getting better performance.
    8. For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

    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框架的一些重要好处是:

    1. Hibernate消除了JDBC附带的所有样板代码,并负责管理资源,因此我们可以专注于业务逻辑。
    2. Hibernate框架提供对XML和JPA批注的支持,这使我们的代码实现独立。
    3. Hibernate提供了一种与SQL类似的强大查询语言(HQL)。 但是,HQL完全面向对象,并且了解诸如继承,多态性和关联之类的概念。
    4. Hibernate是Red Hat Community的一个开源项目,已在全球范围内使用。 这使它成为比其他方法更好的选择,因为学习曲线很小,并且有大量的在线文档,并且可以在论坛中轻松获得帮助。
    5. Hibernate易于与其他Java EE框架集成,因此非常流行,Spring框架提供了将Hibernate与Spring应用程序集成的内置支持。
    6. Hibernate支持使用代理对象进行延迟初始化,并且仅在需要时才执行实际的数据库查询。
    7. Hibernate缓存有助于我们获得更好的性能。
    8. 对于数据库供应商特定的功能,Hibernate是合适的,因为我们还可以执行本机sql查询。

    整体Hibernate是当前ORM工具市场上的最佳选择,它包含您在ORM工具中将需要的所有功能。

  4. Hibernate与JDBC相比有什么优势? (What are the advantages of Hibernate over JDBC?)

    Some of the important advantages of Hibernate framework over JDBC are:

    1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.
    2. Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
    3. Hibernate implicitly provides transaction management, in fact most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. Read more at .
    4. JDBC API throws 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.
    5. Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.
    6. Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
    7. Hibernate provide option through which we can create database tables too, for JDBC tables must exist in the database.
    8. Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for connection pool. This is very important feature in enterprise application and completely missing in JDBC API.
    9. Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.

    Hibernate框架相对于JDBC的一些重要优点是:

    1. Hibernate删除了JDBC API附带的许多样板代码,这些代码看起来更清晰易读。
    2. Hibernate支持继承,关联和集合。 JDBC API不提供这些功能。
    3. Hibernate隐式提供了事务管理,实际上大多数查询不能在事务外部执行。 在JDBC API中,我们需要使用commit和rollback编写用于事务管理的代码。 在了解更多信息。
    4. JDBC API抛出SQLException ,这是一个已检查的异常,因此我们需要编写许多try-catch块代码。 在大多数情况下,它在每个JDBC调用中都是多余的,并用于事务管理。 Hibernate包装JDBC异常并抛出JDBCExceptionHibernateException未经检查的异常,因此我们不需要编写代码来处理它。 Hibernate内置的事务管理消除了try-catch块的使用。
    5. Hibernate查询语言(HQL)更加面向对象,与Java编程语言非常接近。 对于JDBC,我们需要编写本机sql查询。
    6. Hibernate支持更好的性能缓存,不缓存JDBC查询,因此性能低下。
    7. Hibernate提供了一个选项,通过它我们也可以创建数据库表,因为JDBC表必须存在于数据库中。
    8. Hibernate配置可帮助我们将JDBC之类的连接以及JNDI DataSource用于连接池。 这在企业应用程序中是非常重要的功能,而在JDBC API中则完全消失。
    9. Hibernate支持JPA批注,因此代码与实现无关,并且可以轻松地用其他ORM工具替换。 JDBC代码与应用程序紧密结合。
  5. 命名Hibernate框架的一些重要接口? (Name some important interfaces of Hibernate framework?)

    Some of the important interfaces of Hibernate framework are:

    1. SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
    2. Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC 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.
    3. Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.

    Hibernate框架的一些重要接口是:

    1. SessionFactory(org.hibernate.SessionFactory) :SessionFactory是单个数据库的已编译映射的不可变线程安全缓存。 我们需要一次初始化SessionFactory,然后我们可以对其进行缓存和重用。 SessionFactory实例用于获取用于数据库操作的Session对象。
    2. 会话(org.hibernate.Session) :会话是一个单线程的,短暂的对象,表示应用程序与持久性存储之间的对话。 它包装JDBC java.sql.Connection并用作org.hibernate.Transaction的工厂。 我们仅应在需要时打开会话,并在使用完毕后立即将其关闭。 会话对象是Java应用程序代码和Hibernate框架之间的接口,并提供CRUD操作的方法。
    3. 事务(org.hibernate.Transaction) :事务是应用程序用来指定原子工作单元的单线程,短期对象。 它将应用程序从底层的JDBC或JTA事务中抽象出来。 在某些情况下,一个org.hibernate.Session可能跨越多个org.hibernate.Transaction。
  6. 什么是Hibernate配置文件? (What is hibernate configuration file?)

    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知道数据库类型和映射文件或类详细信息。

  7. 什么是Hibernate映射文件? (What is hibernate mapping file?)

    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映射文件会派上用场。

  8. 命名一些用于Hibernate映射的重要注释? (Name some important annotations used for Hibernate mapping?)

    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:

    1. javax.persistence.Entity: Used with model classes to specify that they are entity beans.
    2. javax.persistence.Table: Used with entity beans to define the corresponding table name in database.
    3. javax.persistence.Access: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
    4. javax.persistence.Id: Used to define the primary key in the entity bean.
    5. javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
    6. javax.persistence.Column: Used to define the column name in database table.
    7. javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction with javax.persistence.GenerationType enum.
    8. javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as OneToMany, ManyToOne and ManyToMany
    9. org.hibernate.annotations.Cascade: Used to define the cascading between two entity beans, used with mappings. It works in conjunction with org.hibernate.annotations.CascadeType
    10. javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with 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注释是:

    1. javax.persistence.Entity :与模型类一起使用以指定它们是实体bean。
    2. javax.persistence.Table :与实体bean一起使用,以在数据库中定义相应的表名。
    3. javax.persistence.Access :用于定义访问类型,字段或属性。 默认值为field,如果您希望Hibernate使用getter / setter方法,则需要将其设置为property。
    4. javax.persistence.Id :用于定义实体Bean中的主键。
    5. javax.persistence.EmbeddedId :用于在实体bean中定义复合主键。
    6. javax.persistence.Column :用于定义数据库表中的列名。
    7. javax.persistence.GeneratedValue :用于定义用于生成主键的策略。 与javax.persistence.GenerationType枚举结合使用。
    8. javax.persistence.OneToOne :用于定义两个实体Bean之间的一对一映射。 我们还有其他类似的注释,例如OneToManyManyToOneManyToMany
    9. org.hibernate.annotations.Cascade :用于定义两个实体Bean之间的级联,与映射一起使用。 它与org.hibernate.annotations.CascadeType结合使用
    10. javax.persistence.PrimaryKeyJoinColumn :用于定义外键的属性。 与org.hibernate.annotations.GenericGeneratororg.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}
  9. 什么是Hibernate SessionFactory以及如何配置它? (What is Hibernate SessionFactory and how to configure it?)

    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实例以获取查询执行的统计信息,二级缓存详细信息等。

  10. Hibernate SessionFactory是线程安全的吗? (Hibernate SessionFactory is thread safe?)

    Internal state of SessionFactory is immutable, so it’s thread safe. Multiple threads can access it simultaneously to get Session instances.

    SessionFactory的内部状态是不可变的,因此是线程安全的。 多个线程可以同时访问它以获取Session实例。

  11. 什么是Hibernate Session,如何获取? (What is Hibernate Session and how to get it?)

    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对象创建条件。

  12. Hibernate Session是线程安全的吗? (Hibernate Session is thread safe?)

    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对象不是线程安全的,每个线程都应获取其自己的会话实例,并在工作完成后将其关闭。

  13. openSession和getCurrentSession有什么区别? (What is difference between openSession and getCurrentSession?)

    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()返回无状态会话,有关示例的更多详细信息,请阅读 。

  14. Hibernate Session get()和load()方法有什么区别? (What is difference between Hibernate Session get() and load() method?)

    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.

    1. get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading.
    2. Since load() throws exception when data is not found, we should use it only when we know data exists.
    3. We should use get() when we want to make sure data exists in the database.

    For clarification regarding the differences, please read .

    Hibernate会话附带了多种从数据库加载数据的方法。 get和load是最常用的方法,乍一看它们看起来很相似,但是它们之间有一些区别。

    1. get()会在调用后立即加载数据,而load()返回代理对象并仅在实际需要时才加载数据,因此load()更好,因为它支持延迟加载。
    2. 由于未找到数据时load()会引发异常,因此仅当我们知道数据存在时才应使用它。
    3. 当我们要确保数据存在于数据库中时,应该使用get()。

    为了澄清差异,请阅读 。

  15. 什么是Hibernate缓存? 解释Hibernate一级缓存? (What is hibernate caching? Explain Hibernate first level cache?)

    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提供了一些方法,通过这些方法,我们可以从缓存中删除选定的对象或完全清除缓存。

    会话中缓存的任何对象对其他会话都不可见,并且在关闭会话时,所有缓存的对象也将丢失。

    为了获得更好的解释,请阅读 。

  16. 如何使用EHCache配置Hibernate二级缓存? (How to configure Hibernate Second Level Cache using EHCache?)

    EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.

    • Add hibernate-ehcache dependency in your maven project, if it’s not maven then add corresponding jars.
      org.hibernate
      hibernate-ehcache
      4.3.5.Final
    • Add below properties in hibernate configuration file.
    • Create EHCache configuration file, a sample file myehcache.xml would look like below.
    • Annotate entity beans with @Cache annotation and caching strategy to use. For example,
    • 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。

    • 在您的maven项目中添加hibernate-ehcache依赖项,如果不是maven,则添加相应的jar。
      org.hibernate
      hibernate-ehcache
      4.3.5.Final
    • 在Hibernate配置文件中添加以下属性。
    • 创建EHCache配置文件,示例文件myehcache.xml如下所示。
    • 使用@Cache注释和缓存策略对实体bean进行注释。 例如,
    • 就是这样,我们完成了。 Hibernate将使用EHCache进行二级缓存,请阅读以获取带有说明的完整示例。

  17. 实体bean的不同状态是什么? (What are different states of an entity bean?)

    An entity bean instance can exist is one of the three states.

    1. Transient: When an object is never persisted or associated with any session, it’s in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().
    2. Persistent: When an object is associated with a unique session, it’s in persistent state. Any instance returned by a get() or load() method is persistent.
    3. Detached: When an object is previously persistent but not associated with any session, it’s in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

    实体bean实例可以存在的三个状态之一。

    1. 瞬态 :当对象从不持久化或与任何会话关联时,它处于瞬态状态。 可以通过调用save(),persist()或saveOrUpdate()使临时实例具有持久性。 通过调用delete()可以使持久实例成为瞬态。
    2. 持久性 :当对象与唯一会话相关联时,它处于持久性状态。 get()或load()方法返回的任何实例都是持久性的。
    3. 分离的 :当对象先前是持久性的但不与任何会话关联时,则处于分离状态。 可以通过调用update(),saveOrUpdate(),lock()或plicate()使分离的实例持久化。 通过调用merge(),也可以使临时实例或分离实例的状态作为新的持久实例持久化。
  18. Hibernate Session merge()调用的用途是什么? (What is use of Hibernate Session merge() call?)

    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可用于更新现有值,但是此方法从传递的实体对象创建一个副本并将其返回。 返回的对象是持久性上下文的一部分,并跟踪任何更改,不跟踪传递的对象。 例如,请阅读程序。

  19. Hibernate save(),saveOrUpdate()和persist()方法有什么区别? (What is difference between Hibernate save(), saveOrUpdate() and persist() methods?)

    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(),但是如果会话未刷新,您将再次遇到映射对象无法保存的问题。 例如,使用这些方法,请阅读 。

  20. 如果我们在实体bean中没有no-args构造函数,将会发生什么? (What will happen if we don’t have no-args constructor in Entity bean?)

    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

  21. 排序收集和有序收集之间有什么区别,哪个更好? (What is difference between sorted collection and ordered collection, which one is better?)

    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.

    List
    empList = 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还应实现ComparableComparator接口,以使其正常工作,有关更多信息,请 。

    如果我们使用Hibernate框架从数据库加载收集数据,则可以使用其Criteria API使用“ order by”子句来获取有序列表。 下面的代码段显示了如何获取它。

    有序列表比有序列表更好,因为实际的排序是在数据库级别完成的,这是快速的并且不会引起内存问题。

  22. Hibernate中的收集类型是什么? (What are the collection types in Hibernate?)

    There are five collection types in hibernate used for one-to-many relationship mappings.

    1. Bag
    2. Set
    3. List
    4. Array
    5. Map

    Hibernate中有五种收集类型用于一对多关系映射。

    1. 清单
    2. 数组
    3. 地图
  23. 如何在Hibernate中实现Joins? (How to implement Joins in Hibernate?)

    There are various ways to implement joins in hibernate.

    • Using associations such as one-to-one, one-to-many etc.
    • Using JOIN in the HQL query. There is another form “join fetch” to load associated data simultaneously, no lazy loading.
    • We can fire native sql query and use join keyword.

    在Hibernate中有多种实现联接的方法。

    • 使用诸如一对一,一对多等的关联。
    • 在HQL查询中使用JOIN。 还有另一种形式的“联合获取”可以同时加载关联的数据,而无需延迟加载。
    • 我们可以触发本地sql查询并使用join关键字。
  24. 为什么我们不应该将实体类定型为最终的? (Why we should not make Entity Class final?)

    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是最终的,则不可能进行延迟加载,因此会降低性能。

  25. 什么是HQL?它有什么好处? (What is HQL and what are it’s benefits?)

    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查询更好的选择。 在阅读更多内容。

  26. 什么是Hibernate中的查询缓存? (What is Query Cache in Hibernate?)

    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)方法,快速示例如下所示。

  27. 我们可以在Hibernate状态下执行本地SQL查询吗? (Can we execute native sql query in hibernate?)

    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一级缓存有关的好处。 在阅读更多内容。

  28. 在Hibernate中支持本机sql查询有什么好处? (What is the benefit of native sql query support in 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查询非常方便。

  29. 什么是命名SQL查询? (What is Named SQL Query?)

    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命名查询。

  30. 命名SQL查询的好处是什么? (What are the benefits of Named SQL Query?)

    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命名查询是全局的,这意味着一旦定义,它就可以在整个应用程序中使用。

    但是,命名查询的主要缺点之一是难以调试,因为我们需要找出定义它的位置。

  31. Hibernate Criteria API有什么好处? (What is the benefit of Hibernate Criteria API?)

    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:

    • Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
    • Criteria API can be used with ProjectionList to fetch selected columns only.
    • Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
    • Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
    • Criteria API provides addOrder() method that we can use for ordering the results.

    Learn some quick examples at .

    Hibernate提供的Criteria API更面向对象,用于查询数据库和获取结果。 我们无法使用条件来运行更新或删除查询或任何DDL语句。 它仅用于使用更多面向对象的方法从数据库中获取结果。

    Criteria API的一些常见用法是:

    • Criteria API提供了Projection,我们可以将其用于汇总函数,例如sum(),min(),max()等。
    • Criteria API可以与ProjectionList一起使用,以仅获取选定的列。
    • 通过连接多个表,可以将Criteria API用于连接查询,有用的方法是createAlias(),setFetchMode()和setProjection()
    • Criteria API可用于获取有条件的结果,有用的方法是add(),我们可以在其中添加限制。
    • Criteria API提供了addOrder()方法,可用于对结果进行排序。

    在学习一些快速示例。

  32. 如何在日志文件中记录Hibernate生成的sql查询? (How to log hibernate generated sql queries in log files?)

    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查询。

    但是,我们应该仅在开发或测试环境中使用它,而在生产环境中将其关闭。

  33. 什么是Hibernate Proxy,它如何帮助延迟加载? (What is Hibernate Proxy and how it helps in lazy loading?)

    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有效且动态地生成实体对象的子类实现。

  34. 如何在Hibernate状态下实现关系? (How to implement relationships in hibernate?)

    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的配置来完成。 为了更好地理解,您应该阅读以下教程。

  35. 事务管理在Hibernate中如何工作? (How transaction management works in Hibernate?)

    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事务管理好,因为我们不需要依赖异常进行回滚。 会话方法抛出的任何异常都会自动回滚事务。

  36. 什么是级联,什么是不同类型的级联? (What is cascading and what are different types of cascading?)

    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.

    Commonly used cascading types as defined in CascadeType enum are:

    1. None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
    2. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
    3. SAVE_UPDATE: Cascades save and update, available only in hibernate.
    4. DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
    5. DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
    6. LOCK: Corresponds to the Hibernate native LOCK action.
    7. REPLICATE: Corresponds to the Hibernate native REPLICATE action.

    当我们在实体之间建立关系时,我们需要定义不同的操作将如何影响另一个实体。 这是通过级联完成的,并且有不同的类型。

    这是在主要实体和次要实体之间应用级联的简单示例。

    注意,Hibernate CascadeType枚举常量与JPA javax.persistence.CascadeType有点不同,因此我们需要使用Hibernate CascadeType和Cascade批注进行映射,如上面的示例所示。

    在CascadeType枚举中定义的常用级联类型为:

    1. 无:没有级联,它不是类型,但是当我们不定义任何级联时,父级中的任何操作都不会影响子级。
    2. 全部:级联保存,删除,更新,逐出,锁定,复制,合并,持久。 基本上一切
    3. SAVE_UPDATE:级联保存和更新,仅在Hibernate状态下可用。
    4. DELETE:仅在Hibernate状态下对应于Hibernate本机的DELETE操作。
    5. DETATCH,MERGE,PERSIST,REFRESH和REMOVE –用于类似操作
    6. LOCK:与Hibernate本机LOCK操作相对应。
    7. REPLICATE:与Hibernate本机REPLICATE操作相对应。
  37. 如何在Hibernate应用程序中集成log4j日志记录? (How to integrate log4j logging in hibernate application?)

    Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps.

    • Add log4j dependencies for maven project, if not maven then add corresponding jar files.
    • Create log4j.xml configuration file or log4j.properties file and keep it in the classpath. You can keep file name whatever you want because we will load it in next step.
    • For standalone projects, use static block to configure log4j using 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配置,我们需要执行以下步骤。

    • 为maven项目添加log4j依赖项,如果不是maven,则添加相应的jar文件。
    • 创建log4j.xml配置文件或log4j.properties文件,并将其保存在类路径中。 您可以随意保留文件名,因为我们将在下一步中加载它。
    • 对于独立项目,请使用static块通过DOMConfiguratorPropertyConfigurator配置log4j。 对于Web应用程序,可以使用ServletContextListener对其进行配置。

    就是这样,我们的设置已经准备就绪。 在java类中创建org.apache.log4j.Logger实例并开始记录。 对于完整的示例代码,您应该阅读和 。

  38. 如何在Hibernate框架中使用应用服务器JNDI DataSource? (How to use application server JNDI DataSource with Hibernate framework?)

    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名称。

    有关完整的示例,请查看 。

  39. 如何集成Hibernate和Spring框架? (How to integrate Hibernate and Spring frameworks?)

    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.

    1. Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.
    2. Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
    3. If you are using Hibernate 3, you need to configure 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.
    4. Note that we don’t need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using @Transactional annotation.

    For complete example go through and .

    Spring是最常用的Java EE框架之一,而Hibernate是最流行的ORM框架。 这就是为什么Spring Hibernate组合在企业应用程序中大量使用的原因。 使用Spring最好的部分是它为带有Spring ORM模块的Hibernate提供了现成的集成支持。 需要执行以下步骤将Spring和Hibernate框架集成在一起。

    1. 添加hibernate-entitymanager,hibernate-core和spring-orm依赖项。
    2. 创建用于数据库操作的模型类和相应的DAO实现。 请注意,DAO类将使用由Spring Bean配置注入的SessionFactory。
    3. 如果使用的是Hibernate 3,则需要在Spring Bean配置文件中配置org.springframework.orm.hibernate3.LocalSessionFactoryBeanorg.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean 。 对于Hibernate 4,应该配置单个类org.springframework.orm.hibernate4.LocalSessionFactoryBean
    4. 注意,我们不需要使用Hibernate Transaction Management,我们可以使用@Transactional批注将其留给Spring声明式事务管理。

    有关完整的示例,请通过和 。

  40. 什么是HibernateTemplate类? (What is HibernateTemplate class?)

    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提供了两个帮助器类HibernateDaoSupportHibernateTemplate 。 使用它们的原因是从Hibernate获取Session并从Spring事务管理中受益。 但是从Hibernate 3.0.1开始,我们可以使用SessionFactory getCurrentSession()方法来获取当前会话,并使用它来获得Spring事务管理的好处。 如果您看了上面的示例,您将看到它很容易,这就是为什么我们不再使用这些类的原因。

    HibernateTemplate另一个好处是异常翻译,但是可以通过对服务类使用@Repository批注轻松实现,如上面的spring mvc示例所示。 这是一个判断您的知识以及是否知道最新进展的技巧。

  41. 如何将Hibernate与Servlet或Struts2 Web应用程序集成? (How to integrate Hibernate with Servlet or Struts2 web applications?)

    Hibernate integration with Servlet or Struts2 needs to be done using ServletContextListener, a complete example can be found at .

    与Servlet或Struts2的Hibernate集成需要使用ServletContextListener来完成,有关完整示例,请参见《 。

  42. Hibernate框架中使用了哪些设计模式? (Which design patterns are used in Hibernate framework?)

    Some of the design patterns used in Hibernate Framework are:

    • Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
    • Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
    • for lazy loading
    • in SessionFactory

    Hibernate Framework中使用的一些设计模式是:

    • 域模型模式–包含行为和数据的域对象模型。
    • 数据映射器–映射器层,用于在对象和数据库之间移动数据,同时使它们彼此之间以及映射器本身保持独立。
    • 延迟加载的
    • SessionFactory中的
  43. Hibernate框架应遵循哪些最佳实践? (What are best practices to follow with Hibernate framework?)

    Some of the best practices to follow in Hibernate are:

    • Always check the primary key field access, if it’s generated at the database layer then you should not have a setter for this.
    • By default hibernate set the field values directly, without using setters. So if you want hibernate to use setters, then make sure proper access is defined as @Access(value=AccessType.PROPERTY).
    • If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
    • Use native sql query only when it can’t be done using HQL, such as using database specific feature.
    • If you have to sort the collection, use ordered list rather than sorting it using Collection API.
    • Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity specific query, you can keep them in the entity bean itself.
    • For web applications, always try to use JNDI DataSource rather than configuring to create connection in hibernate.
    • Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
    • For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit of lazy loading.
    • Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that in-memory state accurately represents the persistent state.
    • Prefer DAO pattern for exposing the different methods that can be used with entity bean
    • Prefer lazy fetching for associations

    在Hibernate中应遵循的一些最佳做法是:

    • 始终检查主键字段访问,如果它是在数据库层生成的,那么您不应该对此进行设置。
    • 默认情况下,hibernate直接设置字段值,而不使用设置器。 因此,如果您希望Hibernate使用setter,请确保将正确的访问定义为@Access(value=AccessType.PROPERTY)
    • 如果访问类型是属性,请确保批注与getter方法一起使用,而不是setter方法。 避免在字段方法和getter方法上混合使用注释。
    • 仅当无法使用HQL(例如,使用数据库特定功能)来完成时,才使用本机sql查询。
    • 如果必须对集合进行排序,请使用有序列表,而不要使用Collection API对其进行排序。
    • 明智地使用命名查询,将其放在一个位置以便于调试。 仅将它们用于常用查询。 对于特定于实体的查询,您可以将它们保留在实体bean本身中。
    • 对于Web应用程序,请始终尝试使用JNDI DataSource,而不是配置为在Hibernate状态下创建连接。
    • 避免多对多关系,可以使用双向一对多和多对一关系轻松实现。
    • 对于集合,请尝试使用列表,地图和集合。 避免使用数组,因为您不会从延迟加载中受益。
    • 不要将异常视为可恢复的,请回滚事务并关闭会话。 如果您不这样做,则Hibernate无法保证内存中状态准确地表示持久状态。
    • 首选DAO模式来公开可与实体bean一起使用的不同方法
    • 优先选择懒惰获取关联
  44. 什么是Hibernate Validator Framework? (What is Hibernate Validator Framework?)

    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验证规范的参考实现。 在阅读更多信息。

  45. Hibernate Tools Eclipse插件有什么好处? (What is the benefit of Hibernate Tools Eclipse plugin?)

    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/

你可能感兴趣的文章
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>
vs无法加载项目
查看>>
Beanutils基本用法
查看>>
玉伯的一道课后题题解(关于 IEEE 754 双精度浮点型精度损失)
查看>>
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>