gpt4 book ai didi

java - 由于 @RequiredArgsConstructor 似乎不起作用,如何让 lombok 为非空字段创建构造函数?

转载 作者:行者123 更新时间:2023-12-01 14:21:34 25 4
gpt4 key购买 nike

我正在玩 Lombok 并且已经经历了很多链接,但没有一个对我有用。

Person.java

@Setter @Getter
@ToString
@AllArgsConstructor
//@NoArgsConstructor
@RequiredArgsConstructor
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;

@NotNull
@Size(min = 1, max = 20)
private String firstName;

@NotNull
@Size(min = 1, max = 50)
private String lastName;
}

PersonController.java

@RestController
@RequestMapping("/people")
public class PersonController {
@Autowired
private PersonRepository personRepository;

@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void createPerson(@RequestBody Person person) {
personRepository.save(new Person(person.getFirstName(), person.getLastName())); //line-34
}
}

但它不允许我创建两个参数的构造函数

Multiple markers at this line
- The constructor Person(String, String) is undefined
- The method save(S) in the type CrudRepository<Person,Long> is not applicable for the arguments
(Person)

34 号线坏了...

EDIT-1:

 @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updatePerson(@PathVariable("id") Long id, @RequestBody Person person) {
Person existingPerson = personRepository.findOne(id);
existingPerson.setFirstName(person.getFirstName());
existingPerson.setLastName(person.getLastName());
personRepository.save(existingPerson);
}

这里是错误

The method setFirstName(String) is undefined for the type Person

我所做的改变

@Setter @Getter
@ToString
@AllArgsConstructor
//@NoArgsConstructor
@RequiredArgsConstructor()
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;

@NotNull
@Size(min = 1, max = 20)
private final String firstName;

@NotNull
@Size(min = 1, max = 50)
private final String lastName;
}

-===================

Edit-2

最终结果如下:

@Setter @Getter
@ToString
@AllArgsConstructor
@RequiredArgsConstructor
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;

@NotNull
@Size(min = 1, max = 20)
private String firstName;

@NotNull
@Size(min = 1, max = 50)
private String lastName;

public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}

最佳答案

您在这些字段上没有 Lomboks @NonNull 注释。我刚才注意到了。

您在这些字段上只有 @javax.validation.constraints.NotNull 注释ṣ 并且 @RequiredArsg​​Constructor 不适用于该字段。

除了 @NotNull 注释外,还添加了 @NonNull。可能是您不再需要 @NotNull,因此也尝试将其删除。

@NonNull 
@NotNull
@Size(min = 1, max = 20)
private String firstName;

@NonNull
@NotNull
@Size(min = 1, max = 50)
private String lastName;

关于java - 由于 @RequiredArgsConstructor 似乎不起作用,如何让 lombok 为非空字段创建构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017657/

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