gpt4 book ai didi

java - 存储库继承

转载 作者:行者123 更新时间:2023-12-02 07:00:51 24 4
gpt4 key购买 nike

我想创建一个执行基本 CRUD 操作的存储库。

由于我有不同类型的照片(CompanyPhoto、CarPhoto,..),我更愿意使 JPA 存储库通用,同时也使 EJB 服务通用。

这是我的类(class):

    @Entity
@Inheritance
@DiscriminatorColumn(name = "DESCRIMINATOR")
@Table(name = "PHOTOS")
public abstract class Photo {
public Photo() {
}

public Photo(String fileName) {
this.fileName = fileName;
// this.file = file;
}

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "PHOTOS_SEQ")
@TableGenerator(name = "PHOTOS_SEQ", table = "SEQUENCE", pkColumnName = "SEQ_NAME", pkColumnValue = "PHOTOS_SEQ", valueColumnName = "SEQ_COUNT", allocationSize = 50)
@Column(nullable = false)
private long id;

@Column(length = 255)
@Size(min = 0, max = 255, message = "{Photo.description.size}")
protected String description;

@Column(nullable = false, length = 255)
@NotNull(message = "{Photo.fileName.notNull}")
@Size(min = 1, max = 255, message = "{Photo.fileName.size}")
protected String fileName;

// ...

@Entity
@DiscriminatorValue("C")
public class CarPhoto extends Photo {

public CarPhoto() {

}

public CarPhoto(String fileName) {
super.fileName = fileName;
}

@ManyToOne(cascade = { CascadeType.DETACH })
@JoinColumn(name = "CARID", nullable = false)
@NotNull
private Car car;
// ...

@Entity
@DiscriminatorValue("P")
public class PersonPhoto extends Photo {

public PersonPhoto() {

}

public PersonPhoto(String fileName) {
super.fileName = fileName;
}

@ManyToOne(cascade = { CascadeType.DETACH })
@JoinColumn(name = "PERSONID", nullable = false)
@NotNull
private Person person;
// ...

@Stateless
@LocalBean
public class PhotoRepository<E> {

// In this class I would like to do create, remove, update and some basic find //operations..


@PersistenceContext
private EntityManager em;

public PhotoRepository() {
}

PhotoRepository(EntityManager em) {
this.em = em;
}

@Override
public E create(E photo) {
em.persist(photo);
return photo;
}

@Override
public E modify(E photo)
{
Class<E> photoClass;
// QUESTION: How am I going to call the getId() method from the object of type E class?
em.find(photoClass, photo.getId()); // This will not work.. =(
E mergedPhoto = em.merge(photo);
return mergedPhoto;
}
// ...

我希望你明白我想做什么。不同类型的类的通用存储库,这些类都继承自同一基类。您能给我一些最佳实践示例吗? =)

致以诚挚的问候

最佳答案

更改泛型定义以表明 E 必须是从 Photo 扩展的任何类型。然后您将能够访问 E 类型变量上的 Photo 类的方法

@Stateless
@LocalBean
public class PhotoRepository<E extends Photo> {

您可以使用以下方法来检索实际的类。

public Class getEntityClass() {
ParameterizedType parameterizedType =
(ParameterizedType) getClass().getGenericSuperClass();
return (Class) parameterizedtype.getActualTypeArguments()[0];
}

如果您正在使用 spring,您还应该看看 spring-data-jpa - 它提供了此类通用存储库实现。

关于java - 存储库继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678694/

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