Groovy和JPA阻止Spring Boot CrudRepository执行插入操作

时间:2018-01-06 03:43:26

标签: hibernate jpa spring-boot groovy

我有一个(Groovy)Spring Boot应用程序与H2内存数据库对话(但不要认为这很重要)。我有以下cd实体:

GroceryItem

然后是@MappedSuperclass abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id } @Canonical @TupleConstructor(includeSuperProperties = true) @ToString(includeSuperProperties = true) @Entity(name = 'grocery_items') @AttributeOverrides([ @AttributeOverride(name = "id", column=@Column(name="grocery_item_id")) ]) class GroceryItem extends BaseEntity { @Column(name = 'grocery_item_name') @NotNull @Valid String name @Column(name = 'grocery_item_qty') @NotNull Integer quantity } 接口:

CrudRepository

但由于某些原因,此interface GroceryItemPersistor extends CrudRepository<GroceryItem, Long> { @Query('FROM grocery_items WHERE grocery_item_name = :name') GroceryItem findByName(@Param('name') String name) @Query('FROM grocery_items') List<GroceryItem> getAllGroceries() } CrudRepository方法仅更新并允许我将一个save(...)插入数据库。这意味着如果我运行此代码:

GroceryItem

我在控制台上获得以下输出:

GroceryItem olives = new GroceryItem(1L, '123456', 'Olives', 6)
groceryItemPersistor.save(olives)

List<GroceryItem> allItems = groceryItemPersistor.getAllGroceries()
log.info("There are ${allItems.size()} grocery items.")
log.info("${allItems.first().name} are in there right now")

GroceryItem cheeseWedges = new GroceryItem(2L, '067e6162-3b6f-4ae2-a171-2470b63dff00', 'Cheese Wedges', 4)
groceryItemPersistor.save(cheeseWedges)

allItems = groceryItemPersistor.getAllGroceries()
log.info("There are ${allItems.size()} grocery items.")
log.info("${allItems.first().name} are in there right now")

我需要在There are 1 grocery items. Olives are in there right now. There are 1 grocery items. Cheese Wedges are in there right now. 和/或GroceryItem类中修改哪些内容才能BaseEntity正确插入而不是更新?

2 个答案:

答案 0 :(得分:1)

创建主键为1的橄榄项目后,您在创建cheeseWedges时传递相同的主键。

GroceryItem cheeseWedges = new GroceryItem(1L, '067e6162-3b6f-4ae2-a171-2470b63dff00', 'Cheese Wedges', 4)

尝试创建新项目时,请勿设置主键。如果您设置它,JPA将尝试更新表中具有相同主键的项目。

答案 1 :(得分:0)

我明白了。我正在创建一个主键并保存它,而不是让JPA在调用@Generated时为我创建save密钥。将我的实体实例化更改为null id:

GroceryItem bananas = new GroceryItem(null, '067e6162-3b6f-4ae2-a171-2470b63dff00', 'Bananas', 12)

...解决了这个问题。