gpt4 book ai didi

java - Spring官方文档中的问题

转载 作者:行者123 更新时间:2023-12-02 09:12:49 26 4
gpt4 key购买 nike

这是来自 official documentation (You need to scroll down a little) 的示例:

class Person {

private final @Id Long id;
private final String firstname, lastname;
private final LocalDate birthday;
private final int age;

private String comment;
private @AccessType(Type.PROPERTY) String remarks;

static Person of(String firstname, String lastname, LocalDate birthday) {

return new Person(null, firstname, lastname, birthday,
Period.between(birthday, LocalDate.now()).getYears());
}

Person(Long id, String firstname, String lastname, LocalDate birthday, int age) {

this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.birthday = birthday;
this.age = age;
}

Person withId(Long id) {
return new Person(id, this.firstname, this.lastname, this.birthday);
}

void setRemarks(String remarks) {
this.remarks = remarks;
}
}

我对此有几个问题。

  1. Person withId(Long id)示例中引用的构造函数不存在吗?

  2. Person withId(Long id) 官方文档中有这样的描述:“相同的模式通常应用于其他由存储管理但可能需要更改以实现持久化的属性行动”。我是不是可以这样理解:成功保存实例后,可以使用WithOutIdPerson进行其他字段更改并再次保存,而可以使用SavedPerson进行其他上层操作吗?

  3. 例子中为什么调用工厂of()的最后一步?

谢谢~

最佳答案

问题 1

Person withId(Long id) Does the referenced construction function not exist in the example?

这可能是文档中的错误,它应该如下所示:

Person withId(Long id) {                                                  
return new Person(id, this.firstname, this.lastname, this.birthday, this.age);
}

问题 2

After successfully saving the instance, WithOutIdPerson can be used for other field changes and saved again, and SavedPerson can be used for other upper level operations?

如果我理解你的意思是正确的,你想知道这是否可行:

Person p = Person.of( "Peter", "Parker", someDate);
Person saved = personRepository.save(p);
Person savedAgain = personRepository.save(p);

如果 Person 的 id 属性由数据库设置,并且它是一个不可变属性(它有一个wither,如例如),则 psaved(以及 savedAgain)是不同的实体,并且两个 save 操作会生成两行存储在数据库中,并且 savedsavedAgain 具有不同的 id,并且 p 的 id 仍然等于 null

问题 3

Why is the last step of the factory of() called in the example?

实际上,示例代码中根本没有调用of()。为什么建议使用工厂方法而不是重载构造函数,代码注释 (6) 中对此进行了解释:

The class exposes a factory method and a constructor for object creation. The core idea here is to use factory methods instead of additional constructors to avoid the need for constructor disambiguation through @PersistenceConstructor. Instead, defaulting of properties is handled within the factory method.

如果没有工厂,您将有两个构造函数,并且需要 use @PersistenceConstructor on one in order to tell Spring Data which one to use for instance creation .

关于java - Spring官方文档中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com