我想创建一个执行基本 CRUD 操作的存储库。
因为我有不同类型的照片(CompanyPhoto、CarPhoto、..),所以我更愿意让 JPA 存储库通用,但也让 EJB 服务也通用。
这是我的课程:
@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;
}
// ...
我希望你明白我想表演什么。不同类型的类的通用存储库,这些类都继承自同一个基类。你能给我一些最佳实践的例子吗?=)
此致