Java Hibernate ORM 5 中有哪些新功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31965179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's new in Hibernate ORM 5?
提问by Shri S Softwares
I just saw that the 4th candidate got released for Hibernate 5. What's new in 5 compared to earlier versions?
我刚刚看到 Hibernate 5 的第 4 个候选版本发布了。与早期版本相比,5 中有哪些新内容?
采纳答案by Bacteria
Some exciting features has been added/enhanced in Hibernate 5.x. Have a quick look.
在 Hibernate 5.x 中添加/增强了一些令人兴奋的功能。快看一下。
1. Hibernate Search
1.休眠搜索
Hibernate Search transparently indexes your objects and offers fast regular, full-text and geolocation search. Ease of use and easy clustering are core.
Hibernate Search 透明地索引您的对象并提供快速的常规、全文和地理定位搜索。易用性和易于聚类是核心。
- Full-text search for entities - find by approximation (fuzzy search)
- Cluster-friendly - offers several easy to setup clustering strategies
- Faceting and geolocation - Geolocalized entities are as easy as @Spatial
- 实体的全文搜索 -通过近似查找(模糊搜索)
- 集群友好 -提供多种易于设置的集群策略
- 分面和地理定位 - 地理定位实体就像@Spatial 一样简单
For more details on Hibernate Search view this.
有关 Hibernate Search 的更多详细信息,请查看此内容。
2. Hibernate Validator
2. 休眠验证器
Hibernate Validator comes with a handful of built-in validation rules like Email, Length, NotBlank etc.
Hibernate Validator 带有一些内置的验证规则,如电子邮件、长度、NotBlank 等。
Express validation rules in a standardized way using annotation-based constraints and benefit from transparent integration with a wide variety of frameworks.
使用基于注释的约束以标准化方式表达验证规则,并受益于与各种框架的透明集成。
For more details on Hibernate Validator view this.
有关 Hibernate Validator 的更多详细信息,请查看此内容。
3. Improved Java 8 Support
3. 改进的 Java 8 支持
Java 8 date/time data types (JSR 310) are supported and can be validated via @Past and @Future. Also Optional and JavaFX types are supported via an improved ValidatedValueUnwrapper.
支持 Java 8 日期/时间数据类型 (JSR 310),并且可以通过 @Past 和 @Future 进行验证。还通过改进的 ValidatedValueUnwrapper 支持 Optional 和 JavaFX 类型。
4. Hibernate OGM
4.休眠OGM
Just released the first stable version.
刚刚发布了第一个稳定版本。
5. Bootstrapping API
5. 引导 API
New bootstrapping API - better determinism, better integration
新的引导 API - 更好的确定性,更好的集成
A few other things:
其他一些事情:
- Scanning support for non-JPA usage
- NamingStrategy has been removed in favor of a better designed API
- Ability to handle additional Java types for id attributes marked as GenerationType#AUTO. Built-in support for Number and UUID. Expandable via new org.hibernate.boot.model.IdGeneratorStrategyInterpreter extension.
- Additionally, support for AttributeConverters has been expanded and more fully realized
- 对非 JPA 使用的扫描支持
- NamingStrategy 已被删除,以支持设计更好的 API
- 能够处理标记为 GenerationType#AUTO 的 id 属性的其他 Java 类型。内置支持 Number 和 UUID。可通过新的 org.hibernate.boot.model.IdGeneratorStrategyInterpreter 扩展进行扩展。
- 此外,对 AttributeConverters 的支持也得到了扩展和更全面的实现
Check Hibernate ORM Roadmapfor more details.
查看Hibernate ORM 路线图以获取更多详细信息。
回答by Vlad Mihalcea
There's a long list of things that have been changed in Hibernate 5:
在 Hibernate 5 中有一长串改变的东西:
New bootstrap API so we can bootstrap a JPA environment programmatically without the need of a
persistence.xml
file.Starting in 5.0 Hibernate Spatial is part of the Hibernate project so we can handle GIS data too.
The Java 8 Date and Time typesare supported in domain model mappings. The mapping between the standard SQL Date/Time types and the supported Java 8 Date/Time class types looks as follows;
- DATE:
java.time.LocalDate
- TIME:
java.time.LocalTime
,java.time.OffsetTime
- TIMESTAMP:
java.time.Instant
,java.time.LocalDateTime
,java.time.OffsetDateTime
andjava.time.ZonedDateTime
- DATE:
The bytecode enhancement mechanism was redesigned from scratch, and Hibernate features both a Maven and a Gradle plugin. There are three main aspects which we can enhance with bytecode instrumentation:
Lazy initialization: Fields can be declared as
LAZY
and they will be fetched only when being accessed for the first time.Dirty checking: Entities are enhanced so that they can keep track of all the properties that get changed after being loaded in a Persistence Context.
Bidirectional associations: It's possible to synchronize both sides of a bidirectional association automatically, even if the developer only updates a single side.
Hibernate's native APIs (
Session
, etc) have been updated to use generic types. No need to cast when fetching entities.Hibernate 5.0 extends this to a broader set of types (e.g.
UUID
).Second-level cache by reference. This feature enables direct storage of entity references into the second level cache for immutable entities.
Starting with Hibernate 5.0, we have a completely new User Guidethat was written from scratch.
新的引导程序 API,因此我们可以在不需要
persistence.xml
文件的情况下以编程方式引导 JPA 环境。从 5.0 开始,Hibernate Spatial 是 Hibernate 项目的一部分,因此我们也可以处理 GIS 数据。
在Java的8日期和时间类型的域模型映射支持。标准 SQL 日期/时间类型与受支持的 Java 8 日期/时间类类型之间的映射如下所示;
- 日期:
java.time.LocalDate
- 时间:
java.time.LocalTime
,java.time.OffsetTime
- 时间戳:
java.time.Instant
,java.time.LocalDateTime
,java.time.OffsetDateTime
和java.time.ZonedDateTime
- 日期:
字节码增强机制从头开始重新设计,Hibernate 具有 Maven 和 Gradle 插件。我们可以通过字节码检测增强三个主要方面:
延迟初始化:字段可以声明为,
LAZY
并且只有在第一次访问时才会获取它们。脏检查:实体得到增强,以便它们可以跟踪在持久性上下文中加载后发生更改的所有属性。
双向关联:可以自动同步双向关联的两侧,即使开发人员只更新一侧。
Hibernate 的本机 API(
Session
等)已更新为使用泛型类型。获取实体时无需强制转换。Hibernate 5.0 将此扩展到更广泛的类型集(例如
UUID
)。二级缓存引用。此功能支持将实体引用直接存储到不可变实体的二级缓存中。
从 Hibernate 5.0 开始,我们有一个从头开始编写的全新用户指南。
Hibernate 5.1adds the following features:
Hibernate 5.1添加了以下功能:
Hibernate 5.2adds support for:
Hibernate 5.2添加了对以下内容的支持:
- Java 1.8, so you can now use
Query.stream()
- The Hibernate
Session
extendsEntityManager
so you can get access to all JPA methods right from aSession
- Support for JCache
- Session-level batch size
- Global timezone setting (e.g. UTC) for
Timestamp
andTime
- Distinct pass-through hint
- More efficient JPQL and HQL parsing of constant values
- The
hibernate.connection.provider_disables_autocommit
resource-local transaction optimization. - Better handling of Criteria API literals.
- Java 1.8,所以你现在可以使用
Query.stream()
- Hibernate
Session
扩展,EntityManager
因此您可以直接从Session
- 支持 JCache
- 会话级批量大小
- 全球时区设置(例如,UTC)的
Timestamp
和Time
- 独特的直通提示
- 更高效的 JPQL 和 HQL 解析常量值
- 该
hibernate.connection.provider_disables_autocommit
资源本地事务优化。 - 更好地处理 Criteria API 文字。
回答by Vijay Barot
There are 5 New features in Hibernate 5
Hibernate 5 有 5 个新特性
1. Support classes of the Date and Time API as BasicTypesThe new Date and Time API was one of the most anticipated changes in Java 8. The old java.util.Date has a lot of issues which got finally fixed.
1. 支持日期和时间 API 的类作为 BasicTypes新的日期和时间 API 是 Java 8 中最令人期待的变化之一。旧的 java.util.Date 有很多问题,最终得到了修复。
Unfortunately, JPA 2.1 and Hibernate 4 don't provide direct support for it. But that's not a huge issue. It just takes a few lines of code to implement an AttributeConverter that maps a LocalDate.
不幸的是,JPA 2.1 和 Hibernate 4 不提供直接支持。但这不是一个大问题。只需几行代码即可实现映射 LocalDate 的 AttributeConverter。
But obviously, the explicit support as a BasicType is still a lot better. Hibernate implemented that in version 5.0. Since then you don't need any additional annotations or converter to persist the classes of the Date and Time API. You can use them in the same way as any other supported attribute types.
但显然,作为 BasicType 的显式支持仍然要好得多。Hibernate 在 5.0 版中实现了它。从那时起,您不需要任何额外的注释或转换器来持久化日期和时间 API 的类。您可以像使用任何其他支持的属性类型一样使用它们。
2. Get query results as a StreamIntroducing a new method to give you your query result as a Stream doesn't sound like a big thing. But the stream method of Hibernate's Query interface provides an additional benefit that makes it especially interesting for huge result sets. It fetches the result set in multiple batches and uses Hibernate's ScrollableResults implementation to scroll through it. This approach is a great fit if you use a Stream to process the result set records one by one and helps you to implement your use case efficiently.
2. 以流的形式获取查询结果介绍一种将查询结果以流的形式提供给您的新方法听起来并不是什么大事。但是 Hibernate 的 Query 接口的 stream 方法提供了一个额外的好处,使它对巨大的结果集特别有趣。它分批获取结果集,并使用 Hibernate 的 ScrollableResults 实现来滚动它。如果您使用 Stream 逐个处理结果集记录并帮助您有效地实现用例,则此方法非常适合。
You can use the new method since Hibernate 5.2 to get your query results. The following code snippet shows a simple example that selects all Book entities from the database and processes them as a Stream.
您可以使用自 Hibernate 5.2 以来的新方法来获取查询结果。以下代码片段显示了一个简单示例,该示例从数据库中选择所有 Book 实体并将它们作为流进行处理。
3. Fetch multiple entities by their primary key
3. 通过主键获取多个实体
Fetching multiple entities by their ID is a very common use case. Most developers either implement it with a loop that calls the find method of the EntityManager for each primary key or with a JPQL query that checks all primary key values in an IN clause. The first option requires Hibernate to perform a database query for each primary key. That can create huge performance issues. The second one allows you to fetch all entities with one query and is obviously the better option.
通过 ID 获取多个实体是一个非常常见的用例。大多数开发人员要么使用为每个主键调用 EntityManager 的 find 方法的循环来实现它,要么使用检查 IN 子句中所有主键值的 JPQL 查询来实现它。第一个选项要求 Hibernate 为每个主键执行数据库查询。这会造成巨大的性能问题。第二个允许您通过一个查询获取所有实体,显然是更好的选择。
Hibernate 5.1 introduced a third option that avoids the issues of the first and is easier to use than the second one. The new MultiIdentifierLoadAccess interface provides a comfortable option to load multiple entities with one query. You just need to call the byMultipleIds method on the Hibernate Session to get a MultiIdentifierLoadAccess interface and provide a list of primary key values to the multiLoad method. Hibernate's implementation also provides an additional advantage: It splits huge lists of primary key values into multiple batches. This is sometimes required because some databases limit the number of elements in an IN clause.
Hibernate 5.1 引入了第三个选项,它避免了第一个选项的问题,并且比第二个选项更易于使用。新的 MultiIdentifierLoadAccess 接口提供了一种使用一个查询加载多个实体的舒适选项。您只需要在 Hibernate Session 上调用 byMultipleIds 方法即可获取 MultiIdentifierLoadAccess 接口并向 multiLoad 方法提供主键值列表。Hibernate 的实现还提供了一个额外的优势:它将庞大的主键值列表拆分为多个批次。这有时是必需的,因为某些数据库限制 IN 子句中的元素数量。
4. Join unassociated entities in a query
4. 在查询中加入未关联的实体
You can easily join mapped associations between entities in JPQL queries. The mapping already provides the required join conditions, and you don't need to provide them in your query.
您可以轻松地在 JPQL 查询中加入实体之间的映射关联。映射已提供所需的连接条件,您无需在查询中提供它们。
But what about entities that map associated database tables but have no mapped association?
但是映射关联数据库表但没有映射关联的实体呢?
And that's not a rhetorical question.
这不是一个修辞问题。
Most entity models don't map all the possible associations. They only map the ones that seem to provide value in the domain model and not the ones where 2 database tables (seemingly by accident) store the same foreign key. It also happens quite often that a to-many association with lots of records on the many side doesn't get mapped with Hibernate. The risk that someone calls the getter of the association and fetches several hundred or thousand entities is just too high.
大多数实体模型不会映射所有可能的关联。它们只映射那些似乎在域模型中提供价值的那些,而不是那些 2 个数据库表(似乎是偶然)存储相同外键的那些。也经常发生这样的情况,即多侧有大量记录的多对多关联没有被 Hibernate 映射。有人调用关联的 getter 并获取数百或数千个实体的风险太高了。
That's totally fine as long as you just look at the domain model. You probably don't need these associations in the model. But that doesn't mean that you don't need them in one of your JPQL queries.
只要您只看域模型,那完全没问题。您可能不需要模型中的这些关联。但这并不意味着您在 JPQL 查询之一中不需要它们。
If that's the case, you have 3 options:
如果是这种情况,您有 3 个选择:
1 Model the association between the entities or
2 Use a cross join in your JPQL query which might create performance issues or
3 Use Hibernate's proprietary JOIN clause.
I prefer option 3. It's the easiest and most natural one.
1 对实体之间的关联进行建模或
2 在您的 JPQL 查询中使用交叉联接,这可能会产生性能问题或
3 使用 Hibernate 的专有 JOIN 子句。我更喜欢选项 3。这是最简单、最自然的选项。
Since Hibernate 5.1, you can use an SQL-like syntax to join entities without a modeled association.
从 Hibernate 5.1 开始,您可以使用类似 SQL 的语法来连接实体,而无需建模关联。
5. @Repeatable annotations
5.@Repeatable注解
Repeatable annotations are one of the smaller changes in Java 8. It allows you to annotate a class, attribute or interface with the same annotation multiple times. A typical JPA example in which you want to do that is defining multiple named queries for an entity.
可重复注解是 Java 8 中较小的变化之一。它允许您使用相同的注解多次注解类、属性或接口。一个典型的 JPA 示例是为一个实体定义多个命名查询。
So far, you had to annotate your entity with a @NamedQueries annotation which contained an array of @NamedQuery annotations. The annoying thing about that is that the @NamedQueries annotation is just a container. It doesn't provide any value on its own. Since Hibernate 5.2, you don't have to do that anymore. At least not as long as you use Hibernate's version of the org.hibernate.annotations.NamedQuery annotation. @NamedQuery and a lot of other Hibernate annotations are now repeatable and can be assigned multiple times. As you can see in the following code snippet, that makes the code easier to read and is much more comfortable to use.
到目前为止,您必须使用包含@NamedQuery 注释数组的@NamedQueries 注释来注释您的实体。令人讨厌的是@NamedQueries 注释只是一个容器。它本身不提供任何价值。从 Hibernate 5.2 开始,您不必再这样做了。至少只要您使用 Hibernate 版本的 org.hibernate.annotations.NamedQuery 注释。@NamedQuery 和许多其他 Hibernate 注释现在是可重复的,可以多次分配。正如您在以下代码片段中看到的那样,这使代码更易于阅读并且使用起来更加舒适。
Creadit/Source: https://www.thoughts-on-java.org/5-new-features-hibernate-5-every-developer-know/
信用/来源:https: //www.thoughts-on-java.org/5-new-features-hibernate-5-every-developer-know/