首页 > 解决方案 > 当策略为 IDENTITY 时,休眠 RX 插入和刷新和刷新返回异常

问题描述

当我尝试休眠 rx 库并运行示例时

        // obtain a reactive session
        factory.withTransaction(
                // persist the Authors with their Books in a transaction
                (session, tx) -> session.persist(author1, author2)
                        .flatMap(Mutiny.Session::flush)
                        .flatMap(s -> s.refresh())
        )

class Author {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id;

它会抛出 CompletionException

Exception in thread "main" java.util.concurrent.CompletionException: org.hibernate.PropertyAccessException: Could not set field value [1] value by reflection : [class org.hibernate.example.reactive.Author.id] setter of org.hibernate.example.reactive.Author.id

我在https://github.com/semistone/hibernate-reactive/commit/398b1570666ed81a7d257020166f2ae59f1c5eb8推送测试代码

有人可以帮忙检查一下。

谢谢

标签: hibernatereactive-programminghibernate-reactive

解决方案


更新:这是一个错误,它将在 Hibernate Reactive 1.0 CR1 中修复

答案在评论中,但我会在这里重复一遍。

您需要添加一个 setter 并更改 id 类型以Long使其正常工作。类Author变为:

@Entity
@Table(name="authors")
class Author {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull @Size(max=100)
    private String name;

    @OneToMany(mappedBy = "author", cascade = PERSIST)
    private List<Book> books = new ArrayList<>();

    Author(String name) {
        this.name = name;
    }

    Author() {}

    void setId(Long id) {
        this.id = id;
    }

    Long getId() {
        return id;
    }

    String getName() {
        return name;
    }

    List<Book> getBooks() {
        return books;
    }
}

此外,您不需要添加刷新操作 ( .flatMap(Mutiny.Session::flush)),因为withTransaction已经为您完成了。

而且你也不需要s.refresh. 不知道为什么你会在那里需要它。


推荐阅读