gpt4 book ai didi

java - JPA一对多双向堆栈溢出问题

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

我使用 Java 1.8、Spring Boot、REST、JPA 创建 Spring Boot REST 微服务 API,其实体关系具有以下基数:

Owner can have many Cars.
Cars only have one Owner.

能够通过我的 REST Web 服务创建和查看所有者。

每次我尝试创建具有关联所有者的汽车时,它都会正确填充数据库的行,但似乎它会无限递归,导致堆栈溢出错误(见下文)。

<小时/>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.myapi</groupId>
<artifactId>car-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>car-api</name>
<description>Car REST API</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
<小时/>

src/main/resources/applications.properties:

server.servlet.context-path=/car-api
server.port=8080
server.error.whitelabel.enabled=false

# Database specific
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/car_db?useSSL=false
spring.datasource.ownername=root
spring.datasource.password=
<小时/>

所有者实体:

@Entity
@Table(name = "owner")
public class Owner {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
private String name;


@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "owner")
private List<Car> cars = new ArrayList<>();

public Owner() {
}

// Getter & Setters omitted for brevity.
}

汽车实体:

@Entity
@Table(name="car")
public class Car {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

String make;
String model;
String year;

@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "owner_id", nullable = false)
private Owner owner;

// Getter & Setters omitted for brevity.
}
<小时/>

所有者存储库:

@Repository
public interface OwnerRepository extends JpaRepository<Owner, Long> {
}
<小时/>

汽车存储库:

@Repository
public interface CarRepository extends JpaRepository<Car, Long> {
}
<小时/>

所有者服务:

public interface OwnerService {

boolean createOwner(Owner owner);

Owner getOwnerByOwnerId(Long ownerId);

List<Owner> getAllOwners();

}
<小时/>

OwnerServiceImpl:

@Service
public class OwnerServiceImpl implements OwnerService {


@Autowired
OwnerRepository ownerRepository;

@Autowired
CarRepository carRepository;

@Override
public List<Owner> getAllOwners() {
return ownerRepository.findAll();
}

@Override
public boolean createOwner(Owner owner) {
boolean created = false;
if (owner != null) {
ownerRepository.save(owner);
created = true;
}
return created;
}

@Override
public Owner getOwnerByOwnerId(Long ownerId) {
Optional<Owner> owner = null;
if (ownerRepository.existsById(ownerId)) {
owner = ownerRepository.findById(ownerId);
}
return owner.get();
}
}
<小时/>

汽车服务:

public interface CarService {

boolean createCar(Long ownerId, Car car);
}
<小时/>

CarServiceImpl:

@Service
public class CarServiceImpl implements CarService {

@Autowired
OwnerRepository ownerRepository;

@Autowired
CarRepository carRepository;

@Override
public boolean createCar(Long ownerId, Car car) {
boolean created = false;
if (ownerRepository.existsById(ownerId)) {
Optional<Owner> owner = ownerRepository.findById(ownerId);
if (owner != null) {
List<Car> cars = owner.get().getCars();
cars.add(car);
owner.get().setCars(cars);
car.setOwner(owner.get());
carRepository.save(car);
created = true;
}
}
return created;
}

}

<小时/>

所有者 Controller :

@RestController
public class OwnerController {


private HttpHeaders headers = null;

@Autowired
OwnerService ownerService;

public OwnerController() {
headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
}

@RequestMapping(value = { "/owners" }, method = RequestMethod.POST, produces = "APPLICATION/JSON")
public ResponseEntity<Object> createOwner(@Valid @RequestBody Owner owner) {
boolean isCreated = ownerService.createOwner(owner);
if (isCreated) {
return new ResponseEntity<Object>(headers, HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
}


@RequestMapping(value = { "/owners" }, method = RequestMethod.GET, produces = "APPLICATION/JSON")
public ResponseEntity<Object> getAllOwners() {
List<Owner> owners = ownerService.getAllOwners();

if (owners.isEmpty()) {
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Object>(owners, headers, HttpStatus.OK);
}


@RequestMapping(value = { "/owners/{ownerId}" }, method = RequestMethod.GET, produces = "APPLICATION/JSON")
public ResponseEntity<Object> getOwnerByOwnerId(@PathVariable Long ownerId) {
if (null == ownerId || "".equals(ownerId)) {
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
Owner owner = ownerService.getOwnerByOwnerId(ownerId);
return new ResponseEntity<Object>(owner, headers, HttpStatus.OK);
}

}
<小时/>

汽车 Controller :

@RestController
public class CarController {

private HttpHeaders headers = null;

@Autowired
CarService carService;

public VehicleController() {
headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
}

@RequestMapping(value = { "/cars/{ownerId}" }, method = RequestMethod.POST, produces = "APPLICATION/JSON")
public ResponseEntity<Object> createVehicleBasedOnOwnerId(@Valid @RequestBody Car car, Long ownerId) {
boolean isCreated = carService.createCar(ownerId, vehicle);
if (isCreated) {
return new ResponseEntity<Object>(headers, HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
}

<小时/>

然而,我可以通过将其作为请求正文传递来创建新所有者(并在数据库中查看它们,还可以通过curl/Postman调用getAllOwners来查看它们):

{
"owner": "John Doe"
}
<小时/>

数据库内部car_db.owner:

-------------------------------------
|id | name |
-------------------------------------
|1 | John Doe |
-------------------------------------
<小时/>

当我尝试使用此 REST 调用 /cars/{ownerId} 为车主创建全新汽车时,出现问题:

POST http://localhost:8080/car-api/cars/1

具有以下请求正文:

{
"make": "Honda",
"model": "Accord"
"year": 2020
}

它会将其正确插入 MySQL 数据库的 car_db.car 表中,如下所示:

---------------------------------------
|id | make | model | year | owner_id|
---------------------------------------
|1 | Honda | Accord | 2020 | 1 |
---------------------------------------

我在 CarServiceImpl.createCar() 方法 中执行的操作是否会导致双向关系中断?

创建堆栈溢出流:空执行:

-03-08 01:43:20,106 ERROR org.apache.juli.logging.DirectJDKLog [http-nio-8080-exec-1] Servlet.service() for servlet [dispatcherServlet] in context with path [/car-api] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null
at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:512)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:141)
at com.myapi.model.Car.toString(Car.java:87)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:473)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:622)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at com.myapi.model.Owner.toString(Owner.java:105)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at com.myapi.model.Car.toString(Car.java:87)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:473)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:622)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at com.myapi.model.Owner.toString(Owner.java:105)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at com.myapi.model.Car.toString(Car.java:87)
at java.base/java.lang.String.valueOf(String.java:2788)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:135)
at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:473)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:622)
<小时/>

奇怪的是,尽管这是每次我创建新车时出现的堆栈跟踪,但数据库中的一切都很好(插入位于汽车表内,行内有正确的ownerId)并且我当我执行以下任一 GET 请求时,我能够查看 JSON 响应负载:

GET http://localhost:8080/owners/1

产量:

{
"name": "John Doe",
"cars": [
{
"make": "Honda",
"model": "Accord",
"year": 2020
}
]
}
<小时/>
GET http://localhost:8080/owners

产量:

[
{
"name": "John Doe",
"cars": [
{
"make": "Honda",
"model": "Accord",
"year": 2020
}
]
}
]
<小时/>

尽管所有 GET 和数据库插入都正常工作,但为什么我会收到此堆栈溢出错误?

最佳答案

JPA 与此错误无关。查看堆栈跟踪 - 您的 Car#toString() 打印其 Owner。而 Owner#toString() 则打印其汽车集合。

因此,当代码中的某些内容对这些对象之一调用 toString() 时,它会导致无限的调用链,只有在达到线程堆栈的最大深度时才会结束,从而导致 StackOverflowError。

通常在 toString() 中,我们只想打印当前类中的基元/ValueObject。如果我们也开始打印关联的实体 - 这将导致惰性字段被初始化。

关于java - JPA一对多双向堆栈溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60573876/

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