我现在正在使用hibernate,JPA和guice来实现持久性。当我尝试在html页面上创建一个实体时,它不会抛出任何错误,但是在数据库中找不到数据。实际上该实体已创建,但我不知道它保存在哪里。因为当我尝试使用相同的主键创建实体时,它会跳转到entityexistsexception。
service.java
package com.edit.foo.service;
import com.edit.common.domain.Party;
import com.edit.foo.persistence.PartyStore;
import com.google.inject.persist.Transactional;
import org.apache.commons.lang.StringUtils;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
@Singleton
public class PartyService {
private final PartyStore store;
@Inject
public PartyService (PartyStore store) {
this.store = store;
}
@Transactional
public Party findById(String key) {
if (StringUtils.isBlank(key))
throw new IllegalArgumentException("");
return store.findById(key);
}
@Transactional
public List<Party> search(String filter) {
if (StringUtils.isBlank(filter))
throw new IllegalArgumentException("");
return store.findAllWithNameContaining(filter);
}
@Transactional
public Party create(Party party) {
return store.create(party);
}
@Transactional
public Party update(Party party) {
return store.update(party);
}
}
接口
package com.edit.foo.persistence;
import com.google.inject.persist.Transactional;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;
public abstract class HibernatePersistentStore<E> implements PersistentStore<E> {
private final Class<E> clazz;
@Inject
protected EntityManager entityManager;
protected HibernatePersistentStore(Class<E> clazz) {
this.clazz = clazz;
}
@Override
public E findById(String id) {
return entityManager.find(clazz, id);
}
@Transactional
@Override
public List<E> findAll(Specification<E> filter) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(clazz);
Root<E> root = criteriaQuery.from(clazz);
criteriaQuery.select(root).where(
filter.toPredicate(root, criteriaQuery, criteriaBuilder)
);
return entityManager
.createQuery(criteriaQuery)
.getResultList();
}
@Transactional
@Override
public E create(E entity) {
entityManager.persist(entity);
return entity;
}
@Transactional
@Override
public E update(E entity) {
return entityManager.merge(entity);
}
}
这可能是什么原因?