2016-05-24 56 views
-6

我想写这让我回通过cardIdcustomerId的方法,但是这是不工作时,Eclipse说customerId不能被解析为一个变量JPA的EntityManager find方法不起作用

public CustomerMapping getCustomerMapping(String cardId) { 

      this.getEntityManager(); 
      return em.find(CustomerMapping.class, customerId); 
    } 




@Stateless 
public class CustomerMappingEJB { 

    private EntityManager em; 


    private void getEntityManager() { 
     em = MultiTenantEntityManagerFactory.getEntityManager(); 
    } 

    private void beginTransaction() { 
     em.getTransaction().begin(); 
    } 

    private void commitTransaction() { 
     em.getTransaction().commit(); 
    } 


    private void insert(CustomerMapping customerMapping) { 
     em.persist(customerMapping); 
    } 

    public CustomerMapping getCustomerMapping(long id) { 

     this.getEntityManager(); 
     return em.find(CustomerMapping.class, id); 
    } 

    public List<CustomerMapping> getCustomerMappings() { 

     TypedQuery<CustomerMapping> query = null; 

      this.getEntityManager(); 
      query = em.createNamedQuery("AllCustomerIds", CustomerMapping.class);  

     return query.getResultList(); 
    } 

    public CustomerMappingHelper getCustomerMappingHelper(String cardId) { 

     this.getEntityManager(); 
     return em.find(CustomerMappingHelper.class, cardId); 
    } 

    public CustomerMapping addNew(CustomerMapping customerMapping) { 
     this.getEntityManager(); 
     this.beginTransaction(); 
     this.insert(customerMapping); 
     this.commitTransaction(); 
     return customerMapping; 
    } 
} 

我没有把MultiTenantEntityManagerFactory这个类放在这里,因为我猜你不会需要这个类,那么当你调用它时,我有CustomerMapping类与“一堆列表”,并且只有一些设置和获取id的方法, cardId和customerId我没有复制,因为这将是非常大,如果你也想我也会做

public class CustomerMapping { 

    @Id 
    @GeneratedValue 
    public Long id; 

    @Basic 
    private String customerId; 

    @Basic 
    private String cardId; 

    @Basic 
    private String hashKey; 

} 
+0

您没有在该方法中定义'customerId',并且'customerId'没有作为参数传递,它没有声明为变量,所以您会得到该错误。 – Unknown

回答

2

您可以通过cardId使用JPQL获取CustomerMapping。更优化的解决方案将是使用投影。

public String getCustomerMappingCustomerId(String cardId) { 
    getEntityManager();   
    CustomerMapping result = first(em.createQuery(
     "select c from CustomerMapping c where c.cardId = :cardId") 
     .setParameter("cardId", cardId).getResultList()); 
    return result == null ? null : result.getCustomerId(); 
} 

private static <T> T first(List<T> items) { 
    return items == null || items.isEmpty() ? null : items.get(0); 
} 
+0

你写的东西完全不是我要求的东西,我的customerId是一个字符串不是一个long,其次是代码中的操作在哪里,你通过cardId找到customerId? – ECasio

+0

@ECasio我不是传心者:)请将您的实体添加到问题中。快点,因此关闭;) –

+0

@ECasio,你愿意从cardId找到customerId对不对?如果是这样,那么您将从find方法获得一个类型为CustomerMapping的实例。从相同的实例获取customerId。 – VSK