2个表之间的Quarkus / Hiberante关系

时间:2020-05-27 13:54:15

标签: java hibernate quarkus quarkus-panache

我尝试用数据库创建一个简单的Web应用程序。我的数据库只有2列:

CREATE TABLE IF NOT EXISTS `Board` (
  `BoardID` Integer NOT NULL AUTO_INCREMENT,
  `Title` Varchar(255),
  `Position` Integer NOT NULL,
  PRIMARY KEY (`BoardID`)
);

CREATE TABLE IF NOT EXISTS `Task` (
  `TaskID` Integer NOT NULL AUTO_INCREMENT,
  `BoardID` Integer NOT NULL,
  `Title` Varchar(255),
  `Description` Varchar (1000),
  PRIMARY KEY (`TaskID`),
  FOREIGN KEY (`BoardID`)
  REFERENCES Board(`BoardID`)
);

模型:

@Entity
public class Task extends PanacheEntity {

    @Column(name = "TaskID")
    private Long taskId;

    @ManyToOne (fetch = FetchType.LAZY)
    @JoinColumn(name = "BoardID")
    private Board board;
...
}
@Entity
public class Board extends PanacheEntity{

    @Column(name = "BoardID")
    private Long boardId;

    @OneToMany(mappedBy = "board", orphanRemoval = true)
    private Set<Task> task;
...
}

我的REST方法

@Path("/hello")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ExampleResource {

    @Inject
    BoardRepository boardRepository;

    @GET
    @Transactional
    public List<Board> getAll() {
        return boardRepository.listAll();
    }
}

我的代码正在编译,但是当我调用REST方法时,我收到错误消息: enter image description here

请帮助我做错了

1 个答案:

答案 0 :(得分:1)

检查PanacheEntity的代码。从JavaDoc:

表示一个实体,该实体具有类型为{@link Long}的ID字段{@link #id}。如果您的Hibernate实体扩展了此类,则它们将获得ID字段并自动生成对其所有公共字段的访问器(除非使用{@link Transient}进行注释),以及{@link PanacheEntityBase}中的所有有用方法。

如果要使用自定义ID类型或策略,则可以直接扩展{@link PanacheEntityBase},然后编写自己的ID字段。您仍将获得自动生成的访问器和 所有有用的方法。

从此处复制的JavaDoc:https://github.com/quarkusio/quarkus/blob/master/extensions/panache/hibernate-orm-panache/runtime/src/main/java/io/quarkus/hibernate/orm/panache/PanacheEntity.java

您的id列没有名称“ id”。因此,您应该改用PanacheEntityBase,并且必须更改实体并将@Id批注添加到id字段:

@Entity
public class Task extends PanacheEntityBase {

    @Id
    @Column(name = "TaskID")
    private Long taskId;

    @ManyToOne (fetch = FetchType.LAZY)
    @JoinColumn(name = "BoardID")
    private Board board;
...
}
@Entity
public class Board extends PanacheEntityBase {

    @Id
    @Column(name = "BoardID")
    private Long boardId;

    @OneToMany(mappedBy = "board", orphanRemoval = true)
    private Set<Task> task;
...
}

如果要使用PanacheEntity作为基类,则必须更改数据库中的列名,并从实体中删除taskId和boardId。