gpt4 book ai didi

java - 保存从 DTO 转换的实体时,hibernate 抛出 TransientPropertyValueException : object references an unsaved transient instance"

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

首先 - 我知道,似乎同一个问题已经被问了一百万次。然而,这与 DTO 有关,而不是与实体或缺失的级联有关。如果我自己创建一个实体并保存它,一切都很好。当我创建 DTO、使用 ModelMapper 转换它然后尝试保存转换后的实体时,会出现问题。如果您查看测试类,第一个测试(saveCarByEntity)通过,但第二个测试(saveCarByDto)产生错误。每个类的连接如下所示。预先感谢您。

实体:

@Data
@Entity
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne(mappedBy = "car", cascade = CascadeType.PERSIST)
private CarDetails carDetails;
}
@Data
@Entity
public class CarDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne(mappedBy = "carDetails", cascade = CascadeType.PERSIST)
private Bumper bumper;

@OneToOne
private Car car;
}
@Data
@Entity
public class Bumper {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne
private CarDetails carDetails;
}

DTO-s:

@Data
public class CarDto {
private Long id;
private CarDetailsDto carDetails;
}
@Data
public class CarDetailsDto {
private Long id;
private BumperDto bumper;
private CarDto car;
}
@Data
public class BumperDto {
private Long id;
private CarDetailsDto carDetails;
}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
class CarTests {
@Autowired
private ModelMapper modelMapper;

@Autowired
private CarRepository carRepository;

@BeforeEach
public void setup() {
}

@Test
public void saveCarByEntity() {
Car car = new Car();
CarDetails carDetails = new CarDetails();
Bumper bumper = new Bumper();

car.setCarDetails(carDetails);
carDetails.setCar(car);
carDetails.setBumper(bumper);
bumper.setCarDetails(carDetails);

Car savedEntity = carRepository.save(car);
}

@Test
public void saveCarByDto() {
CarDto carDto = new CarDto();
CarDetailsDto carDetails = new CarDetailsDto();
BumperDto bumper = new BumperDto();

carDto.setCarDetails(carDetails);
carDetails.setCar(carDto);
carDetails.setBumper(bumper);
bumper.setCarDetails(carDetails);

Car car = modelMapper.map(carDto, Car.class);

Car savedEntity = carRepository.save(car);
}
}

产生错误:

nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.somepackage.model.Bumper.carDetails -> com.somepackage.model.CarDetails

汽车存储库:

@Repository
public interface CarRepostiory extends JpaRepository<Car, Long> {
}

最佳答案

我不知道你的模型映射器是做什么的,但我敢打赌,如果你在没有保险杠的情况下坚持汽车细节,然后再保留保险杠,它就会起作用。也许您也可以通过在 carDetails 的 Bumper 中使用 CascadeType.PERSIST 来使其工作?

关于java - 保存从 DTO 转换的实体时,hibernate 抛出 TransientPropertyValueException : object references an unsaved transient instance",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61301600/

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