A Guide to JPA Buddy – JPA伙伴指南

最后修改: 2022年 4月 9日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

JPA Buddy is a widely used IntelliJ IDEA plugin targeted to both new and experienced developers who work with JPA data model and related technologies like Spring Data JPA, DB versioning tools (Flyway, Liquibase), MapStruct, and some others. The plugin provides visual designers, code generation, and additional inspections that should simplify the development and improve the code according to the best practices for JPA.

JPA Buddy 是一个广泛使用的 IntelliJ IDEA 插件,针对使用 JPA 数据模型和相关技术(如 Spring Data JPA)的新手和经验丰富的开发人员。DB版本工具(FlywayLiquibase),MapStruct,以及其他一些。该插件提供了可视化设计器、代码生成和额外的检查,应该可以简化开发并根据JPA的最佳实践改进代码。

The plugin works under both Community and Ultimate versions of IntelliJ IDEA and uses the “freemium” model. Most features are available for free, and we’ll need to buy a subscription to access the paid ones.

该插件在IntelliJ IDEA的社区版和终极版下都可以使用,并采用 “免费 “模式。大多数功能都是免费的,我们需要购买订阅来访问付费的功能。

In this tutorial, we’ll look at the plugin’s main features and see how we can use them during the application development cycle. As an example, we’re going to use the popular reference application – “Spring PetClinic“.

在本教程中,我们将了解该插件的主要功能,并看看我们如何在应用程序开发周期中使用它们。作为一个例子,我们将使用流行的参考应用程序 – “Spring PetClinic” 。

2. Getting Started

2.入门

We can activate JPA Buddy automatically when adding a JPA dependency to the application source code. The plugin is in the “Recommended InteiilJ Plugins” list, so even if we don’t have it installed, IDEA will suggest we do this. We can also install the plugin from IntelliJ’s marketplace:

我们可以在向应用程序源代码添加JPA依赖时自动激活JPA Buddy。该插件在 “推荐的InteiilJ插件 “列表中,所以即使我们没有安装它,IDEA也会建议我们这样做。我们也可以从IntelliJ的市场上安装该插件。

JpaBuddy Notification Window

JPA Buddy functionality may vary depending on the libraries attached to the application. E.g., we won’t see menus for DB versioning scripts generation if we have neither Liquibase nor Flyway attached.

JPA Buddy的功能可能会根据应用程序所附的库而有所不同。例如,如果我们既没有附加Liquibase也没有附加Flyway,我们就不会看到生成DB版本的脚本的菜单。

3. Working with JPA Entities

3.与JPA实体合作

Usually, application development starts with the data model. JPA Buddy provides a visual designer and component palette that allows us to create an entity and add basic attributes and associations to it. We can invoke the corresponding action from a context menu or the JPA Structure tool window:

通常情况下,应用程序的开发是从数据模型开始的。JPA Buddy提供了一个可视化设计器和组件调色板,允许我们创建一个实体并为其添加基本属性和关联。我们可以从上下文菜单或JPA结构工具窗口中调用相应的操作。

JPABuddy context menu

If we need to add or edit an entity attribute, we can use the JPA palette and inspector. To add an attribute, we need to double-click on it or perform drag-and-drop. The visual editor allows us to define the attribute properties:

如果我们需要添加或编辑一个实体属性,我们可以使用JPA调色板和检查器。要添加一个属性,我们需要双击它或执行拖放操作。可视化编辑器允许我们定义属性。

Attribute visual editor

To edit an entity’s attribute, we can use the JPA inspector. According to JPA specs, the inspector allows us to view and edit almost all options for an entity’s attribute. The editor works both ways: when we update an attribute’s property, the code is updated. And vice versa, when the entity’s code is updated, all changes are reflected in the inspector.

要编辑一个实体的属性,我们可以使用JPA检查器。根据JPA规范,检查器允许我们查看和编辑一个实体属性的几乎所有选项。编辑器是双向工作的:当我们更新属性的时候,代码也会被更新。反之亦然,当实体的代码被更新时,所有的变化都会反映在检查器中。

3.1. Lombok Support

3.1.Lombok支持

According to JPA Specs, entities should have getters and setters for attributes, and this is often treated as “boilerplate” code. Lombok is a popular library that allows us to avoid writing boilerplate and replace it with a couple of annotations. Many developers use Lombok in the JPA entities definition, so JPA Buddy supports it fully. We can edit Lombok-related properties in the JPA Inspector:

根据JPA规范,实体应该有属性的getters和setters,而这通常被视为 “模板 “代码。Lombok是一个流行的库,它允许我们避免编写模板,而用几个注释来代替它。许多开发人员在JPA实体定义中使用Lombok,所以JPA Buddy完全支持它。我们可以在JPA检查器中编辑Lombok相关的属性。

Lombok support in inspector

The plugin functionality is not limited to inspection and editing. The important part of the support is inspections. Some Lombok annotations might cause performance issues or unexpected errors when used with JPA. For example, using @ToString annotation might cause LazyInitException because it uses all attributes for an object string representation, including lazy ones.

该插件的功能不限于检查和编辑。支持的重要部分是检查。当与JPA一起使用时,一些Lombok注解可能会导致性能问题或意外错误。例如,使用@ToString注解可能会导致LazyInitException,因为它将所有属性用于对象的字符串表示,包括懒惰的。

JPA Buddy shows warnings for such cases and provides quick fixes, and it helps us to avoid bugs in the JPA code:

JPA Buddy会显示此类情况的警告,并提供快速修复,它可以帮助我们避免JPA代码中的错误。

Lombok code inspection warning

4. DB Migration with Liquibase and Flyway

4.用Liquibase和Flyway进行数据库迁移

To create a database from the JPA data model, we usually use DB versioning tools; Liquibase and Flyway are two big players in this area. The most error-prone part of the DB migration process is writing the migration script based on the JPA entity’s changes. JPA Buddy provides schema differential script generation for both Liquibase and Flyway. The plugin can compare the existing DB schema to the JPA model or even two schemas:

为了从JPA数据模型中创建一个数据库,我们通常使用DB版本管理工具;Liquibase和Flyway是这个领域的两个大玩家。DB迁移过程中最容易出错的部分是根据JPA实体的变化来编写迁移脚本。JPA Buddy为Liquibase和Flyway提供了模式差异脚本的生成。该插件可以将现有的DB模式与JPA模型,甚至是两个模式进行比较。

Migration scripts preview window

In addition to this, JPA Buddy provides scripts autocompletion and smart preview. In this mode, the plugin analyzes the generated scripts and shows a warning if changes can cause failures in the target data source on update:

除此之外,JPA Buddy还提供脚本自动完成和智能预览。在这种模式下,插件会分析生成的脚本,并在变化可能导致目标数据源在更新时出现故障时显示警告。

Warning for a potentially dangerous code

5. Spring Data JPA Support

5.Spring Data JPA支持

When the data model is created, the next step is the implementation of the data access repositories. Spring Data JPA is probably the most popular framework for this. JPA Buddy allows us to generate new repositories based on entity definitions. In the repository code, we can use the JPA palette to create various derived methods and queries in a repository code using visual tools:

当数据模型被创建后,下一步就是实现数据访问库。Spring Data JPA可能是这方面最流行的框架。JPA Buddy允许我们根据实体定义来生成新的资源库。在资源库代码中,我们可以使用JPA调色板,使用可视化工具在资源库代码中创建各种派生方法和查询。

Spring JPA Repository creation window

For each method, we can change its properties using the JPA inspector. The plugin allows us to add pagination and ordering as well as create projections for a method’s return data type:

对于每个方法,我们可以使用JPA检查器改变其属性。该插件允许我们添加分页和排序,以及为方法的返回数据类型创建投影。

Spring JPA Repository method inspector

One more useful feature is query extraction. Sometimes derived method names might become too long for complex queries like this:

还有一个有用的功能是查询提取。有时,派生方法的名称对于像这样复杂的查询来说可能会变得太长。

List<Owner> findDistinctByFirstNameIgnoreCaseOrLastNameIgnoreCaseOrPets_NameIgnoreCaseAllIgnoreCaseOrderByFirstNameAsc(
  String firstName, String lastName, String name);

JPA Buddy analyzes a derived method name and allows us to refactor it by renaming and moving the JPQL query to @Query annotation:

JPA Buddy分析了一个派生方法的名称,并允许我们通过重命名和移动JPQL查询到@Query注解来重构它。

JPA Repository query extraction window

@Query("select distinct o from Owner o left join o.pets pets " +
  "where upper(o.firstName) = upper(:firstName) " +
  "or upper(o.lastName) = upper(:lastName) " +
  "or upper(pets.name) = upper(:name) " +
  "order by o.firstName")
List<Owner> findByAnyName(@Param("firstName") String firstName,
  @Param("lastName") String lastName,
  @Param("name") String name);

6. Entities Generation Based on DB Tables

6.基于DB表的实体生成

Data usually outlives the code, so when we build a JPA Data layer over an existing database, we need to create JPA entities based on the current tables. JPA Buddy provides this functionality and allows developers to create entities in a “cherry-pick” manner, selecting tables one by one:

数据通常比代码要长,所以当我们在现有的数据库上建立JPA数据层时,我们需要基于当前的表来创建JPA实体。JPA Buddy提供了这一功能,并允许开发者以 “偷梁换柱 “的方式创建实体,逐一选择表。

JPA Entity creation wizard

In contrast to the existing solutions, the plugin performs “smart” generation and tries to detect associations between entities. We will generate the corresponding attributes even for OneToMany and ManyToMany entities that are not backed with columns:

与现有的解决方案相比,该插件执行 “智能 “生成并试图检测实体之间的关联。我们将生成相应的属性,即使是没有列支持的OneToManyManyToMany实体。

Associaton creation on JPA creation

JPA Buddy generates “empty” entities with an ID column only and a TODO comment in the body for such associations. By clicking on this TODO, we can run the column import process for the existing entity:

JPA Buddy会生成只有ID列的 “空 “实体,并在正文中为这种关联提供一个TODO注释。通过点击这个TODO,我们可以为现有的实体运行列导入过程。

TODO Action window

7. DTOs and Mappers Generation

7.DTOs和映射器的生成

DTO is a valuable design pattern for the case of passing data that we cannot map directly to JPA entities. For example, when creating REST API, we might want to expose only some entity attributes.

DTO是一种有价值的设计模式,用于传递我们无法直接映射到JPA实体的数据的情况。例如,在创建REST API时,我们可能只想公开一些实体属性。

JPA Buddy can generate DTOs and mappers with the MapStruct library. All we need to do is to select desired attributes for generated DTOs:

JPA Buddy可以通过MapStruct库生成DTOs和映射器。我们所需要做的就是为生成的DTO选择所需的属性。

DTO Generation window

The plugin generates a DTO and a mapper, including proper mapping for the associations. JPA Buddy supports Lombok for this case too and generates proper annotations for DTOs:

该插件生成了一个DTO和一个映射器,包括适当的关联映射。JPA Buddy在这种情况下也支持Lombok,并为DTOs生成适当的注释。

@Data
public class OwnerDto implements Serializable {
   private final Integer id;
   @NotEmpty
   private final String firstName;
   @NotEmpty
   private final String lastName;
   private final List<PetDto> pets;
}

8. Minimalistic Mode

8.极简主义模式

JPA Buddy has a friendly UI, but for those who prefer a “focused” view in IntelliJ IDEA, the plugin provides “minimalistic mode”. We can hide all tool windows and use the keyboard only for entities generation, Spring Data JPA repositories creation and edit, invoke DTO creation wizards, and so on:

JPA Buddy有一个友好的用户界面,但对于那些喜欢在IntelliJ IDEA中 “集中 “查看的人,该插件提供了 “极简模式”。我们可以隐藏所有的工具窗口,只使用键盘来生成实体、创建和编辑Spring Data JPA资源库、调用DTO创建向导等等。

JPABuddy minimalistic mode

9. Conclusion

9.结语

JPA Buddy provides a set of powerful tools that make JPA development easier. The good thing about the plugin is that it supports not only JPA but also related libraries used in data access layer development: Spring Data JPA, MapStruct, Lombok, and DB versioning solutions.

JPA Buddy提供了一套强大的工具,使JPA的开发更加容易。该插件的好处是,它不仅支持JPA,还支持用于数据访问层开发的相关库。Spring Data JPA、MapStruct、Lombok和DB版本解决方案。

If we consider IntelliJ IDEA Community, this plugin can significantly simplify the work with JPA. IDEA Ultimate users can get some of the JPA Buddy functionality from the bundled plugins for JPA and Spring Framework support. Still, it looks like DB versioning scripts generation and DTOs creation features remain unique in DB development automation.

如果我们考虑IntelliJ IDEA社区,这个插件可以大大简化JPA的工作。IDEA Ultimate用户可以从支持JPA和Spring框架的捆绑插件中获得一些JPA Buddy功能。尽管如此,看起来DB版本脚本的生成和DTOs的创建功能在DB开发自动化中仍然是独一无二的。

For those who prefer video format, there is a fifteen-minute recording showing JPA Buddy in action. We can see how to create an application with JPA Buddy and Spring Boot using IntelliJ IDEA:

对于那些喜欢视频格式的人来说,有一段15分钟的录音,展示了JPA Buddy的操作。我们可以看到如何使用IntelliJ IDEA,用JPA Buddy和Spring Boot创建一个应用程序。