简体   繁体   中英

Java JPA extending entity

I have an Attachment class:

@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;

and I want to extend this class with one additional field (which is on this table too):

@Entity
public class AttachmentWithContent extends Attachment {

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

And then I want to query that using JpaRepository:

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

but there's an error

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

I need to be able to query Attachment class one time, and AttachmentWithContent another time.

I've tried with @Inheritance and @MappedSuperClass, but it doesn't work.

I think that message is only a warning by your IDE (I assume you use IntelliJ), because it deduces by the method name and repository type that you should return with a list of Attachment objects for that query. I tried the entity model you described with a sample spring boot project and it works for me. However, if you have an AttachmentRepository like this:

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

the findByIdIn method in this will only find the AttachmentWithContent entities; if you input an id that belongs to a simple Attachment, it will yield an empty result. If you change the return type to Attachment (as the warning suggests) it will return all Attachments with or without content:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM