jooq生成records

Java 14 introduced a new way to create classes called Records. In this tutorial, we will learn:

Java 14引入了一种创建记录的新方法,称为记录。 在本教程中,我们将学习:

  • Why do we need Java Records为什么我们需要Java记录
  • How to create Records and use it如何创建记录并使用它
  • Overriding and extending Records classes覆盖和扩展Records类

Recommended Reading: Java 14 Features

推荐读物 : Java 14特性

为什么我们需要Java记录? (Why do we need Java Records?)

One of the common complaints with Java has been its verbosity. If you have to create a simple POJO class, it requires the following boiler-plate code.

Java的普遍抱怨之一是它的冗长。 如果必须创建一个简单的POJO类,则需要以下样板代码。

  • Private fields私人领域
  • Getter and Setter Methodsgetter和setter方法
  • Constructors建设者
  • hashCode(), equals(), and toString() methods.hashCode(),equals()和toString()方法。

This verbosity is one of the reasons for high interest in Kotlin and Project Lombok.

这种冗长的语言是引起人们对Kotlin和Project Lombok高度兴趣的原因之一。

In fact, the sheer frustration of writing these generic methods each and every time lead to the shortcuts to create them in Java IDEs such as Eclipse and IntelliJ IDEA.

实际上,每次编写这些通用方法的无奈之举导致在Java IDE(例如Eclipse和IntelliJ IDEA)中创建这些通用方法的捷径。

Here is the screenshot showing Eclipse IDE option to generate the ceremonial methods for a class.

这是显示Eclipse IDE选项以生成类的仪式方法的屏幕截图。

Eclipse Shortcuts to Generate Ceremonial Methods
Eclipse生成仪式方法的快捷方式

Java Records are meant to remove this verbosity by providing a compact structure to create the POJO classes.

Java Records通过提供一个紧凑的结构来创建POJO类来消除这种冗长的含义。

如何创建Java记录 (How to Create Java Records)

Java Records is a preview feature, which is developed under JEP 359. So, you need two things to create Records in your Java projects.

Java Records是预览功能,是在JEP 359下开发的。 因此,您需要两件事在Java项目中创建Records。

  1. JDK 14 installed. If you are using an IDE, then it must provide support for Java 14 too. Both Eclipse and IntelliJ already provide support for Java 14, so we are good here.已安装JDK 14。 如果使用的是IDE,则它也必须提供对Java 14的支持。 Eclipse和IntelliJ都已经提供了对Java 14的支持,因此我们在这里很好。
  2. Enable Preview Feature: By default, the preview features are disabled. You can enable it in Eclipse from the Project Java Compiler setting.启用预览功能 :默认情况下,预览功能处于禁用状态。 您可以在Eclipse中从Project Java Compiler设置启用它。
Java 14 Enable Preview Feature In Eclipse
Java 14在Eclipse中启用预览功能

You can enable Java 14 preview features in the command line using the --enable-preview -source 14 option.

您可以使用--enable-preview -source 14选项在命令行中启用Java 14预览功能。

Let’s say I want to create a Employee model class. It will look something like the following code.

假设我要创建一个Employee模型类。 它看起来像下面的代码。


package com.journaldev.java14;import java.util.Map;public class Employee {private int id;private String name;private long salary;private Map<String, String> addresses;public Employee(int id, String name, long salary, Map<String, String> addresses) {super();this.id = id;this.name = name;this.salary = salary;this.addresses = addresses;}public int getId() {return id;}public String getName() {return name;}public long getSalary() {return salary;}public Map<String, String> getAddresses() {return addresses;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((addresses == null) ? 0 : addresses.hashCode());result = prime * result + id;result = prime * result + ((name == null) ? 0 : name.hashCode());result = prime * result + (int) (salary ^ (salary >>> 32));return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Employee other = (Employee) obj;if (addresses == null) {if (other.addresses != null)return false;} else if (!addresses.equals(other.addresses))return false;if (id != other.id)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;if (salary != other.salary)return false;return true;}@Overridepublic String toString() {return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + ", addresses=" + addresses + "]";}}

Phew, that’s 70+ lines of auto-generated code. Now let’s see how to create an Employee Record class, which essentially provides the same features.

哎呀,这是70多行自动生成的代码。 现在,让我们看看如何创建Employee Record类,该类本质上提供相同的功能。


package com.journaldev.java14;import java.util.Map;public record EmpRecord(int id, String name, long salary, Map<String, String> addresses) {
}

Wow, this can’t go any shorter than this. I am already loving Record classes.

哇,这不能比这短。 我已经喜欢录制课程了。

Now, let’s use the javap command to figure out what is happening behind the scene when a Record is compiled.

现在,让我们使用javap命令找出在编译记录时幕后发生的事情。


# javac --enable-preview -source 14 EmpRecord.java
Note: EmpRecord.java uses preview language features.
Note: Recompile with -Xlint:preview for details.# javap EmpRecord
Compiled from "EmpRecord.java"
public final class EmpRecord extends java.lang.Record {public EmpRecord(int, java.lang.String, long, java.util.Map<java.lang.String, java.lang.String>);public java.lang.String toString();public final int hashCode();public final boolean equals(java.lang.Object);public int id();public java.lang.String name();public long salary();public java.util.Map<java.lang.String, java.lang.String> addresses();
}
#
Java Record Class Details
Java记录类详细信息

If you want more internal details, run the javap command with -v option.

如果需要更多内部详细信息,请运行带有-v选项的javap命令。


# javap -v EmpRecord

有关记录类的要点 (Important Points about Record Classes)

  1. A Record class is final, so we can’t extend it.Record类是最终的,因此我们无法扩展它。
  2. The Record classes implicitly extend java.lang.Record class.Record类隐式扩展了java.lang.Record类。
  3. All the fields specified in the record declaration are final.记录声明中指定的所有字段均为最终字段。
  4. The record fields are “shallow” immutable and depend on the type. For example, we can change the addresses field by accessing it and then making updates to it.记录字段是“浅”不变的,并取决于类型。 例如,我们可以通过访问地址字段然后对其进行更新来更改地址字段。
  5. A single constructor is created with all the fields specified in the record definition.使用记录定义中指定的所有字段创建单个构造函数。
  6. The Record class automatically provides accessor methods for the fields. The method name is the same as the field name, not like generic and conventional getter methods.Record类自动为字段提供访问器方法。 方法名称与字段名称相同,与通用和常规getter方法不同。
  7. The Record class provides hashCode(), equals(), and toString() implementations too.Record类也提供hashCode() ,equals()和toString()实现。

在Java程序中使用记录 (Using Records in Java Program)

Let’s look at a simple example of using our EmpRecord class.

让我们看一个使用EmpRecord类的简单示例。


package com.journaldev.java14;public class RecordTest {public static void main(String[] args) {EmpRecord empRecord1 = new EmpRecord(10, "Pankaj", 10000, null);EmpRecord empRecord2 = new EmpRecord(10, "Pankaj", 10000, null);// toString()System.out.println(empRecord1);// accessing fieldsSystem.out.println("Name: "+empRecord1.name()); System.out.println("ID: "+empRecord1.id());// equals()System.out.println(empRecord1.equals(empRecord2));// hashCode()System.out.println(empRecord1 == empRecord2);      }
}

Output:

输出:


EmpRecord[id=10, name=Pankaj, salary=10000, addresses=null]
Name: Pankaj
ID: 10
true
false

The Record object works in the same way as any model class, data object, etc.

Record对象的工作方式与任何模型类,数据对象等相同。

扩展记录构造器 (Extending Records Constructor)

Sometimes, we want to have some validations or logging in our constructor. For example, employee id and salary should not be negative. The default constructor won’t have this validation. We can create a compact constructor in the record class. The code of this constructor will be placed at the start of the auto-generated constructor.

有时,我们想进行一些验证或登录我们的构造函数 。 例如,员工ID和薪水不应为负数。 默认的构造函数将没有此验证。 我们可以在记录类中创建一个紧凑的构造函数。 该构造函数的代码将放置在自动生成的构造函数的开头。


public record EmpRecord(int id, String name, long salary, Map<String, String> addresses) {public EmpRecord {if (id < 0)throw new IllegalArgumentException("employee id can't be negative");if (salary < 0)throw new IllegalArgumentException("employee salary can't be negative");}}

If we create an EmpRecord like the following code:

如果我们创建一个类似以下代码的EmpRecord:


EmpRecord empRecord1 = new EmpRecord(-10, "Pankaj", 10000, null);

We will get runtime exception as:

我们将获得运行时异常为:


Exception in thread "main" java.lang.IllegalArgumentException: employee id can't be negativeat com.journaldev.java14.EmpRecord.<init>(EmpRecord.java:9)

记录类可以有方法吗? (Can Records Classes Have Methods?)

Yes, we can create method in records.

是的,我们可以在记录中创建方法。


public record EmpRecord(int id, String name, long salary, Map<String, String> addresses) {public int getAddressCount() {if (this.addresses != null)return this.addresses().size();elsereturn 0;}
}

But, records are meant to be data carriers. We should avoid having utility methods in a record class. For example, the above method can be created in a utility class.

但是,记录本来是数据载体。 我们应该避免在记录类中使用实用程序方法。 例如,可以在实用工具类中创建上述方法。

If you think that having a method is must for your Record class, think carefully if you really need a Record class?

如果您认为Record类必须具有方法,请仔细考虑是否确实需要Record类?

结论 (Conclusion)

Java Records are a welcome addition to the core programming features. You can think of it as a “named tuple”. It’s meant to create a data carrier object with compact structure, avoiding all the boiler-plate code.

Java Records是核心编程功能的一个受欢迎的补充。 您可以将其视为“命名元组”。 它旨在创建结构紧凑的数据载体对象,从而避免所有样板代码。

翻译自: https://www.journaldev.com/39987/java-records-class

jooq生成records

jooq生成records_Java 14 Records类相关推荐

  1. jooq 生成数据库_jOOQ类型安全数据库查询教程

    jooq 生成数据库 课程大纲 SQL是用于关系数据库查询的功能强大且表达能力强的语言. SQL已建立,标准化并且几乎不受其他查询语言的挑战. 但是,在Java生态系统中,自JDBC以来,几乎没有采取 ...

  2. 生成sql条件的类(转)

    在进行sql查询的时候,有时候要进行很多条件限制,自己来拼写SQLwhere条件容易出错,而且判断条件复杂,后期维护困难, 基于这个原因我在一个小项目中写了一套生成sql条件的类.总共包括一个Cond ...

  3. generator自动生成mybatis配置和类信息

    generator自动生成mybatis的xml配置.model.map等信息: 1.下载mybatis-generator-core-1.3.2.jar包.        网址:http://cod ...

  4. 四种Sandcastle方法生成c#.net帮助类帮助文档

    阅读目录(Content) 方法一.Visual Studio新建documentation生成帮助文档 一.下载 二.安装 三.设置 五.生成 方法二.cmd生成帮助文档 方法三.Sandcastl ...

  5. java生成验证码工具类_Java生成图形验证码工具类

    生成验证码效果 validatecode.java 验证码生成类 package cn.dsna.util.images; import java.awt.color; import java.awt ...

  6. 让Visual Studio 2013为你自动生成XML反序列化的类

    Visual Sutdio 2013增加了许多新功能,其中很多都直接提高了对代码编辑的便利性.如: 1. 在代码编辑界面的右侧滚动条上显示不同颜色的标签,让开发人员可以对所编辑文档的修改.查找.定位情 ...

  7. java自动生成类_自动生成优化的Java类专业知识

    java自动生成类 如果您今年访问过JavaOne,您可能已经参加了我的演讲"如何从数据库生成定制的Java 8代码". 在那次演讲中,我展示了如何使用Speedment Open ...

  8. 自动生成优化的Java类专业知识

    如果您今年访问过JavaOne,您可能已经参加了我的演讲"如何从数据库生成定制的Java 8代码". 在那次演讲中,我展示了如何使用Speedment Open Source工具包 ...

  9. Mybatis generator自动生成mybatis配置和类信息

    自动生成代码方式两种: 1.命令形式生成代码,详细讲解每一个配置参数. 2.Eclipse利用插件形式生成代码. 安装插件方式: eclipse插件安装地址:http://mybatis.google ...

最新文章

  1. ASP.NET的一套笔试题
  2. mysql 百度bae乱码 php,[PHP]如何在百度(BAE)和新浪(SAE)的云平台使用PHP连接MySQL并返...
  3. 获取线程结束代码(Exit Code)
  4. 在线rss阅读聚合器lilina-0.7安装笔记
  5. Python 使用 itchat+pillow 实现微信消息自动回复
  6. springcloud(九):配置中心和消息总线(配置中心终结版)
  7. php curl ajax get请求,PHP的curl的get,post请求-Fun言
  8. 使用NSURLProtocol实现离线缓存
  9. matlab 冒泡排序函数,MATLAB实现冒泡排序算法
  10. 快门光圈感光度口诀_曝光补偿怎么调,快门光圈感光度口诀,深度解析曝光补偿...
  11. 第二章 软件项目确立
  12. unity游戏重新开始,退出,停止,继续按钮及打包发布
  13. word图文混排复制到FCKEditor图片不显示
  14. 相册计算机软件,电脑相册制作软件免费版,windows自带安全又免费相册制作软件...
  15. 第六周小组作业:软件测试与评估
  16. 解决!Android Studio 设计 UI 界面控件全在左上角
  17. java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter 报错的解决办法
  18. 【多元统计分析】聚类分析【期末复习】
  19. 完美解决WebSocket 服务器 The WebSocket session [0] has been closed and no method...异常信息
  20. DDR2 MIG核与DDR3 MIG核使用区别

热门文章

  1. go15---select
  2. 第十四章----面向对象equals和toString的重写
  3. dynamic结合匿名类型 匿名对象传参
  4. Scrum Meeting---Ten(2015-11-5)
  5. 20140708testC
  6. 搭建开发环境之串口线的选择
  7. 程序员和美工是否可共存?
  8. 2101 Problem A Snake Filled
  9. linux centos 系统php支持jpeg的安装方法
  10. 2005数据库结构显示收藏