我不确定,如果我在我的服务/持久层中正确行事。 在我的情况下,我有四个实体:用户,类别,投资和Investmentrepeat:
public class User implements Identifiable, Serializable {
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL, fetch = FetchType.LAZY,
orphanRemoval = true)
private List<Investment> investmentList;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "user_investment", joinColumns = { @JoinColumn(name = "user") },
inverseJoinColumns = { @JoinColumn(name = "investment") })
private List<Investment> publicInvestmentList;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL,
fetch = FetchType.LAZY, orphanRemoval = true)
private List<Category> categoryList;
...
}
public class Category implements Identifiable, Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "owner", columnDefinition = "BIGINT(20)")
@NotNull
private User owner;
@OneToMany(mappedBy = "category", fetch = FetchType.LAZY)
private List<Investment> investmentList;
...
}
public class Investment implements Identifiable, Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "owner")
@NotNull
private User owner;
@ManyToMany(mappedBy = "publicInvestmentList")
private List<User> publicUserList;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category")
@NotNull
private Category category;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "investmentrepeat")
@NotNull
private InvestmentRepeat investmentRepeat;
@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.REFRESH }, fetch = FetchType.LAZY)
@JoinColumn(name = "owninginvestmentrepeat", columnDefinition = "BIGINT(20)")
private InvestmentRepeat owningInvestmentRepeat;
...
}
public class InvestmentRepeat implements Identifiable, Serializable {
@OneToMany(mappedBy = "investmentRepeat", fetch = FetchType.LAZY)
private List<Investment> investmentList;
@OneToOne(mappedBy = "owningInvestmentRepeat", fetch = FetchType.LAZY)
@NotNull
private Investment parentInvestment;
...
}
对于每个实体,存在无状态服务类,例如UserService,CategoryService。
我的第一个问题是,如果我为用户创建新类别的功能是正确的,我是否需要在保留类别后更新用户实体?
public Category createWithReferences(String categoryTitle, User owner,
boolean deleteable) throws ServiceException,
EntityPersistenceException {
if (owner == null) {
throw new ServiceException(getMessageService()
.getMessageFromBundle("error.user_not_found_by_id"));
}
if (categoryTitle == null || categoryTitle.isEmpty()) {
throw new ServiceException(getMessageService()
.getMessageFromBundle("error.category.no_title"));
}
Category newCategory = new Category(categoryTitle, owner, deleteable);
owner.addCategorie(newCategory);
newCategory = this.repository.create(newCategory);
userService.update(owner);
return newCategory;
}
@Override
public T create(T obj) throws EntityPersistenceException {
EntityTransaction tx = getEntityManager().getTransaction();
tx.begin();
try {
getEntityManager().persist(obj);
tx.commit();
} catch (PersistenceException e) {
if (tx.isActive()) {
tx.rollback();
}
throw new EntityPersistenceException(
"Could not create Object of Instance: "
+ obj.getClass().getCanonicalName()
+ "; ErrorMessage: " + e.getMessage());
}
return obj;
}
@Override
public T update(T obj) throws EntityPersistenceException {
EntityTransaction tx = getEntityManager().getTransaction();
tx.begin();
try {
obj = this.getEntityManager().merge(obj);
tx.commit();
} catch (PersistenceException e) {
if (tx.isActive()) {
tx.rollback();
}
throw new EntityPersistenceException(
"Could not update Object of Instance: "
+ obj.getClass().getCanonicalName()
+ "; ErrorMessage: " + e.getMessage() + "; ID: "
+ obj.getId());
}
return obj;
}
@Override
public void delete(T obj) throws EntityPersistenceException {
EntityTransaction tx = getEntityManager().getTransaction();
tx.begin();
try {
if (obj != null) {
long id = 0;
if (obj instanceof Identifiable) {
id = ((Identifiable) obj).getId();
T entity = getEntityManager().find(getType(), id);
//entity = getEntityManager().merge(entity);
getEntityManager().remove(entity);
tx.commit();
}
}
} catch (PersistenceException e) {
if (tx.isActive()) {
tx.rollback();
}
throw new EntityPersistenceException(
"Could not delete Object of Instance: "
+ obj.getClass().getCanonicalName()
+ "; ErrorMessage: " + e.getMessage() + "; ID: "
+ obj.getId());
}
}
当我在创建实体后没有更新用户时,当我通过em.find(...)刷新用户时,用户不包含新类别,但是在数据库中创建了新类别。 / p>
另一点是,当我持有一个带有投资重复的新投资时,那么在db-table investmentrepeat中,父投资的id是每次0或当我删除@NotNull注释时,id为null。我是如何在该类别中添加投资的?这是我创建新投资的功能:
public Investment createWithReferences(User owner, String description,
double amount, Date investDate, Category category,
InvestmentRepeat investmentRepeat, boolean isParentInvestment)
throws ServiceException, EntityPersistenceException {
if (owner == null) {
throw new ServiceException(getMessageService()
.getMessageFromBundle("error.user_not_found_by_id"));
}
if (category == null) {
throw new ServiceException(getMessageService()
.getMessageFromBundle("error.category_is_null"));
}
if (investmentRepeat == null) {
throw new ServiceException(getMessageService()
.getMessageFromBundle("error.investmenterepeat_is_null"));
}
// Create investment
Investment newInvestment = new Investment(investDate,
new LocalDateTime(DateTimeZone.UTC), amount, description,
owner, category, investmentRepeat);
// add Investment to investmentRepeat and Category
investmentRepeat.getInvestmentList().add(newInvestment);
if (isParentInvestment) {
investmentRepeat.setParentInvestment(newInvestment);
newInvestment.setOwningInvestmentRepeat(investmentRepeat);
}
owner.findCategory(category).addInvestment(newInvestment);
owner.addInvestment(newInvestment);
// create investment
newInvestment = this.create(newInvestment);
// update Owner
userService.update(owner);
return newInvestment;
}
我希望有人可以告诉我我正在做哪些错误以及我对jpa的了解是错误的:)
谢谢!
答案 0 :(得分:0)
向用户添加类别的最简单方法是执行以下操作。
现在看第二个问题。