2009-09-09 77 views
0

我想知道是否有可能使用示例对象一样,你可以在休眠找到一个对象:查找对象属性的JPA

Cat cat = new Cat(); 
cat.Sex = 'F'; 
cat.Color = Color.Black; 
List results = session.CreateCriteria(typeof(Cat)).Add(Example.Create(cat)).List(); 

我知道我可以通过主键找到,只是没有找转发写了一百万行findByX,findByY等等。

谢谢。

尼科

回答

0

如此,因为它不是当前JPA API中,只有这样,我可以看到如何实现它会利用这一点:

public <T> List<T> findByAttribute(T object) { 
    List<T> found = new ArrayList<T>(); 
    Map m = null; 
    try { 
     m = BeanUtils.describe(object); 
    } catch (Exception ex) { 
     return null; 
    } 

    String query = "select c from " + object.getClass().getSimpleName() + " c where "; 
    if (m != null) { 
     for (Object key : m.keySet()) { 
      if (!key.equals("class")) { 
       Object value = m.get(key); 

       if (value != null) { 
        try { 
         ConvertUtils.convert(m.get(key), PropertyUtils.getPropertyType(object, key.toString())); 
         query += " c." + key + " = :" + key + " and"; 

        } catch (Exception ex) { 
         // the reason for this noncy try catch is so that you don't add parameters that are not primitives 
        } 
       } 
      } 
     } 
     query = query.substring(0, query.lastIndexOf("and")); 
     Query q = getEntityManager().createQuery(query); 
     for (Object key : m.keySet()) { 
      if (!key.equals("class")) { 
       if (m.get(key) != null) { 
        try { 
         Object o = ConvertUtils.convert(m.get(key), PropertyUtils.getPropertyType(object, key.toString())); 
         q.setParameter(key.toString(), o); 
        } catch (Exception ex) { 
         System.out.println("what we have here is a failure to communicate"); 
         System.out.println("only primitive types allowed"); 
        } 
       } 
      } 
     } 
     List resultList = q.getResultList(); 
     if (resultList != null) { 
      found.addAll(resultList); 
     } 
    } 
    return found; 
} 

但这只会对基本类型,我认为工作。我想这是某种东西。

还是要谢谢你

ň

2

看来,如果在条件API正在考虑下一个JPA版本。有一些关于它的讨论here

现在看来,如果您希望通过示例和条件查询功能,那么您将不得不使用Hibernate。

+0

+1感谢..好知道它的到来。 – Nico 2009-09-09 14:55:00