我有一个带有4个表的H2内存数据库。
表Shop与地址表有连接。
现在,我想在PostConstruct方法中插入一些值。
我的表定义也是如此:
商店:
@NotBlank
@Size(min = 2, max = 50)
@Column(name ="name")
private String name;
@NotNull
@ManyToOne
@JoinColumn(name ="address")
private Address address;
@ElementCollection
@JoinTable(name = "shop_products")
private List<Product> products;
地址
@NotBlank
@Size(min = 2, max = 50)
@Column(name ="address", unique = true)
private String address;
产品
@NotBlank
@Size(min = 2, max = 50)
@Column(name ="name", unique = true)
private String name;
@NotBlank
@Size(min = 2, max = 50)
@Column(name ="manufacturer")
private String manufacturer;
@NotNull
@Column(name ="currentPrice")
private BigDecimal currentPrice;
这些是我的带有PostConsutrct方法的Service类:
地址
@PostConstruct
public void initDb() {
Address address1 = Address.builder().address(AddressEnum.BURGENLAND.toString()).build();
Address address2 = Address.builder().address(AddressEnum.WIEN.toString()).build();
Address address3 = Address.builder().address(AddressEnum.TIROL.toString()).build();
addressRepository.saveAll(List.of(address1, address2, address3));
}
产品
@PostConstruct
public void initDb() {
Product product1 = Product.builder().name(ProductEnum.HAMMER.toString()).currentPrice(new BigDecimal(10)).manufacturer("Makita").build();
Product product2 = Product.builder().name(ProductEnum.KNIFE.toString()).currentPrice(new BigDecimal(20)).manufacturer("Bosch").build();
Product product3 = Product.builder().name(ProductEnum.NAIL.toString()).currentPrice(new BigDecimal(30)).manufacturer("Hilti").build();
productRepository.saveAll(List.of(product1, product2, product3));
}
商店
@PostConstruct
public void initDb() {
Shop shop1 = Shop.builder().name("Shop 1").address(new Address(AddressEnum.BURGENLAND.toString())).build();
Shop shop2 = Shop.builder().name("Shop 2").address(new Address(AddressEnum.BURGENLAND.toString())).build();
Shop shop3 = Shop.builder().name("Shop 3").address(new Address(AddressEnum.BURGENLAND.toString())).build();
shopRepository.saveAll(List.of(shop1, shop2, shop3));
}
如果我在ShopService类中删除PostConstruct,它可以工作,但是Shop表中没有任何数据。
在使用PostConstruct运行我的应用程序的同时,我总是收到以下错误消息:
TransientPropertyValueException:非null属性引用一个瞬态值-瞬态实例必须在当前操作之前保存
问题是我不知道如何消除错误消息?
答案 0 :(得分:0)
我现在所做的更改如下:
我在Shop模型类中添加了 cascade = CascadeType.ALL 。
@NotNull
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name ="address")
private Address address;
现在,它可以工作了。