查询:参数中的属性名称

时间:2014-02-09 15:30:57

标签: jpa annotations spring-data

通过此查询,我成功检索到数据库中的电话号码:

import java.util.List;
import org.springframework.data.jpa.repository.JpaReposit ory;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.mc.appcontacts.domain.hibernate.Contact;

public interface ContactRepository extends JpaRepository<Contact, Integer> {


@Query("SELECT c.phoneNumber from Contact c WHERE LOWER(c.name) = LOWER(:name)")
String find(@Param("name") String name);

但是可以在参数中指定要检索的属性的动态名称吗?

在网上我读过的所有tuto中,我知道我们可以在参数中传递属性的值(在我的例子中:@Param(“name”)字符串名称) 但我想在参数中传递的是属性的名称而不是值!

我知道下面的例子不正确但是要提出一般性的想法:

@Query(“SELECT c。(property)from Contact c WHERE LOWER(c.name)= LOWER(:name)”) String find(@Param(“name”)String name,@ Param(“property”)String property);

使用property = phoneNumber(或我的表的其他属性)。

感谢您的帮助!


我不明白该怎么做(对我来说一切都是新的):

我已阅读(并尝试)jpql的定义如下:

import com.mysema.query.jpa.impl.JPAQuery;
import com.mc.appcontacts.repository.ContactRepository;  // managed by spring data 
                                                         //jpa repository

public class ServicesC { 

      @Autowired
      private ContactRepository repository;

      @PersistenceContext                        // try
      private EntityManager em;                  // try
      JPAQuery query = new JPAQuery(em);     // try

      public Contact getOne(Integer id) {
             return repository.findOne(id);
      }

      public String findAtt(String att, String key){
            String jpql = "SELECT c." + att + " from Contact c WHERE LOWER(c.name) = LOWER(:key)";   // try
            List<Contact> l = (List<Contact>) em.createQuery(jpql);   // try
            return "test";
    }
}

但它不起作用(我并不感到惊讶......):

2014-02-24 18:18:34.567:WARN::Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appMapping': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mc.appcontacts.service.ServiceC com.mc.appcontacts.mvc.MappingService.service; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Service' defined in file [C:\Professional\Workspaces\Eclipse\ContactMain\ContactCore\target\classes\com\mc\appcontacts\service\ServiceC.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.mc.appcontacts.service.ServiceC]: Constructor threw exception; nested exception is java.lang.NullPointerException:
    java.lang.NullPointerException
at com.mysema.query.jpa.impl.JPAProvider.get(JPAProvider.java:72)
at com.mysema.query.jpa.impl.JPAProvider.getTemplates(JPAProvider.java:80)
at com.mysema.query.jpa.impl.JPAQuery.<init>(JPAQuery.java:46)

我必须为jpql定义第二个EntityManager吗? (有可能吗?这是正确的方式吗?我不这么认为......) 我已经为xml文件中的Spring-data定义了EntityManager:

<tx:annotation-driven transaction-manager="transactionManager" />   

<!-- Activate Spring Data JPA repository support -->
<jpa:repositories base-package="com.mc.appcontacts.repository" />

<!-- Declare a JPA entityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceXmlLocation" value="classpath:META-INF/contacts/hibernate/persistence.xml" />
    <property name="persistenceUnitName" value="hibernatePersistenceUnit" />
    <!-- <property name="dataSource" ref="dataSource" /> -->
    <property name="jpaVendorAdapter" ref="hibernateVendor" />
</bean>

<!-- Specify our ORM vendor -->
<bean id="hibernateVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="showSql" value="${hibernate.showSql}" />
</bean>

<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

请帮助我......它是如何运作的?

2 个答案:

答案 0 :(得分:1)

不,这样做是不可能的。您必须通过动态生成JPQL查询来自行实现它。

使用查询参数不是一个选项,因为查询参数只能是在给定的预准备语句中替换的值,并且不能改变查询本身的性质。所以你必须做像

这样的事情
String jpql = "select c." + property + " from ...";

答案 1 :(得分:1)

我认为对于动态构建查询的用例,您最好的选择是探索Criteria API,它非常适合这类事情。 http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html