我需要帮助。 我想要的是如何通过名称在数据库中查找对象,还能够编辑和保存对象。
Business Logik
更新员工
public void edit(Long id, Customer editCustomer) {
try {
entityTransaction = em.getTransaction();
em.getTransaction().begin();
em.merge(editCustomer);
Customer customer = em.find(Customer.class, id);
customer.setId(id);
customer.setFirstName(editCustomer.getFirstName());
customer.setLastName(editCustomer.getLastName());
customer.setAddress(editCustomer.getAddress());
customer.setId(editCustomer.getId());
em.getTransaction().commit();
} catch (Exception e) {
if (em.isOpen())
em.getTransaction().rollback();
e.printStackTrace();
}
}
FindByName
public Customer getCustomerByName(String firstName){
TypedQuery query = em.createQuery(“SELECT c FROM Customer c WHERE
c.firstName =:firstName“,Customer.class);
return query.setParameter(“firstName”,firstName).getSingleResult();
}
JSF ManagedBean
public String findByName(){
BookstoreManager.getInstance().getCustomerByName(firstName);
System.out.println("Hello " + customer.getFirstName());
return "Customer";
}
**Result**
2017-07-02T16:43:13.927 + 0200 |信息:Hello null
XHTML
答案 0 :(得分:0)
**JSF ManagedBean**
public String findByName(){
Customer customer=
BookstoreManager.getInstance().getCustomerByName(firstName);
System.out.println("Hello " + customer.getFirstName());
return "Customer";
}
**Business Logik**
public Customer getCustomerByName(String firstName) {
Customer cus = null;
try {
TypedQuery<Customer> query = em.createQuery("SELECT cus FROM Customer cus WHERE cus.firstName = :firstName",
Customer.class);
cus = query.setParameter("firstName", firstName).getSingleResult();
} catch (NoResultException e) {
}
System.out.println("Customer"+ ":" + cus.getFirstName());
return cus;
}
**xhtml code**
<h:form id="main">
<h:panelGrid columns="2">
<h:outputText for="firstName" value="#{texts.firstName}"/>
<p:inputText id="firstName" value="#{customerBean.firstName}"/>
<p:commandButton value="#{texts.name}" action="#{customerBean.findByName()}" />
</h:panelGrid>
</h:form>