我有两种型号,购买和标签 购买可以有许多标签(一对多关系)。
什么是最佳(Efficent / Cleanest / etc)返回所有包含一个或多个标签的购买方式? (不必返回实际的标签实体)。
我目前正在购买表中使用一个列来确定它是否已被标记但是想要将其删除(请参阅PurchaseDAO,因为它已被使用)
的 PurchaseController :
@RequestMapping(value = "purchases/tagged", method = RequestMethod.GET)
@ResponseBody
public final List<Purchase> getTagged()
{
return RestPreconditions.checkNotNull(purchaseService.getTagged());
}
@RequestMapping(value = "purchases/pending", method = RequestMethod.GET)
@ResponseBody
public final List<Purchase> getPending()
{
return RestPreconditions.checkNotNull(purchaseService.getPending());
}
的 PurchaseService :
@Service
public class PurchaseService implements IPurchaseService
{
@Autowired
private IPurchaseDAO purchaseDAO;
public PurchaseService()
{
}
@Transactional
public List<Purchase> getAll()
{
return purchaseDAO.findAll();
}
@Transactional
public List<Purchase> getPending()
{
return purchaseDAO.getPending();
}
@Transactional
public List<Purchase> getTagged()
{
return purchaseDAO.getTagged();
}
}
的 PurchaseDAO :
@Repository
public class PurchaseDAO extends AbstractJpaDAO<Purchase> implements IPurchaseDAO {
@PersistenceContext
EntityManager entityManager;
public PurchaseDAO() {
setClazz(Purchase.class);
}
public List<Purchase> getPending() {
return entityManager.createQuery("from Purchase where tagged = 0")
.getResultList();
}
public List<Purchase> getTagged() {
return entityManager.createQuery("from Purchase where tagged = 1")
.getResultList();
}
}
我的购买和标签DAO都扩展了以下 AbstractJpaDAO :
public abstract class AbstractJpaDAO<T extends Serializable> implements
IAbstractJpaDAO<T> {
private Class<T> clazz;
@PersistenceContext
EntityManager entityManager;
public void setClazz(final Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
public T findOne(final Long id) {
return entityManager.find(clazz, id);
}
public List<T> findAll() {
return entityManager.createQuery("from " + clazz.getName())
.getResultList();
}
public void save(final T entity) {
entityManager.persist(entity);
}
}
由于
将PurchaseDAO getTagged()更改为:
public List<Purchase> getTagged() {
return entityManager.createQuery("SELECT p FROM Puchase p INNER JOIN p.tags")
.getResultList();
}
我收到以下错误:
TRACE [http-bio-8080-exec-3] o.s.w.c.s.AnnotationConfigWebApplicationContext [AbstractApplicationContext.java:322] Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/PurchaseAPIServer/api/purchases/tagged]; client=[192.168.1.17]; method=[GET]; servlet=[PurchaseAPIServer]; session=[null]; user=[null]; time=[411ms]; status=[failed: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.ast.QuerySyntaxException: Puchase is not mapped [SELECT p FROM Puchase p JOIN p.tags tag]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: Puchase is not mapped [SELECT p FROM Puchase p JOIN p.tags tag]]
答案 0 :(得分:1)
select p from Purchase p inner join p.tags
内部联接只会使购买至少有一个标签。