Groovy和JPA阻止Spring Boot CrudRepository进行插入



我有一个(Groovy(Spring Boot应用程序,可以与H2内存数据库通信(但不要认为这很重要(。我有以下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()
}

然而,由于某种原因,这个CrudRepositorysave(...)方法只是更新并允许我将一个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类中修改哪些内容才能正确插入和不更新save(...)

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

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

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

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

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

。修复了此问题。

相关内容

  • 没有找到相关文章

最新更新