gpt4 book ai didi

Java JPA 扩展实体

转载 作者:行者123 更新时间:2023-12-02 11:38:28 25 4
gpt4 key购买 nike

我有一个附件类:

@Entity
@Table(name = "ATTACHMENT")
public class Attachment implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_gen")
@SequenceGenerator(name = "seq_gen", sequenceName = "attachment_seq", allocationSize = 1)
@Column(name = "ATTACHMENT_ID", nullable = false)
private Long id;

@ManyToOne
@JoinColumn(name = "CREATED_BY", nullable = false)
private User createdBy;

@Column(name = "FILE_NAME", nullable = false)
private String fileName;

@Column(name = "CONTENT_TYPE", length = 100, nullable = false)
private String contentType;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATE_DATE", nullable = false)
private Date createDate;

我想用一个附加字段来扩展这个类(该字段也在这张表上):

@Entity
public class AttachmentWithContent extends Attachment {

@Column(name = "FILE_CONTENT")
@Lob
private byte[] fileContent;

然后我想使用 JpaRepository 查询:

 List<AttachmentWithContent> findByIdIn(List<Long> attachmentsIds);

但是有一个错误

'Attachment' domain type or valid projection interface expected here.

我需要能够一次查询 Attachment 类,另一次查询 AttachmentWithContent。

我尝试过使用@Inheritance和@MappedSuperClass,但它不起作用。

最佳答案

我认为该消息只是您的 IDE 发出的警告(我假设您使用 IntelliJ),因为它根据方法名称和存储库类型推断出您应该返回该查询的附件对象列表。我尝试了您使用示例 Spring Boot 项目描述的实体模型,它对我有用。但是,如果您有这样的 AttachmentRepository:

public interface AttachmentRepository implements JpaRepository<Attachment,Long>{
List<AttachmentWithContent> findByIdIn(List<Long> attachmentsIds);
}

其中的findByIdIn方法只会查找AttachmentWithContent实体;如果您输入属于简单附件的 ID,则会产生空结果。如果您将返回类型更改为附件(如警告所示),它将返回所有带或不带内容的附件:

public interface AttachmentRepository implements JpaRepository<Attachment,Long>{
List<Attachment> findByIdIn(List<Long> attachmentsIds);
}

关于Java JPA 扩展实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48747599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com