Уважаемые, нужен совет... Взялся за JSF... Сгенерировал код в NetBeans 5.5... проанализировал его - пытаюсь заставить работать... Существуют нормально работающие бины EJB3 (например, CountryEJB с полями id, ncodeCountry, nameCountry)... Что делает NetBeans... Как я понимаю, он работает через фасад... То есть JSF подрубается к классу-фасаду (т.н. managed-bean), а тот уже разруливает дела с персистентными бинами EJB3... Вот класс CountryEJB | Код | /* * CountryEJB.java * * Created on 2 Март 2007 г., 10:22 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */
package addressEJB;
import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;
/** * Entity class CountryEJB * * @author U0109 */ @Entity @Table(name="Country") public class CountryEJB implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String codeCountry; private String nameCountry; /** Creates a new instance of CountryEJB */ public CountryEJB() { }
/** * Gets the id of this CountryEJB. * @return the id */ public Long getId() { return this.id; }
/** * Sets the id of this CountryEJB to the specified value. * @param id the new id */ public void setId(Long id) { this.id = id; }
/** * Returns a hash code value for the object. This implementation computes * a hash code value based on the id fields in this object. * @return a hash code value for this object. */ @Override public int hashCode() { int hash = 0; hash += (this.getId() != null ? this.getId().hashCode() : 0); return hash; }
/** * Determines whether another object is equal to this CountryEJB. The result is * <code>true</code> if and only if the argument is not null and is a CountryEJB object that * has the same id field values as this object. * @param object the reference object with which to compare * @return <code>true</code> if this object is the same as the argument; * <code>false</code> otherwise. */ @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CountryEJB)) { return false; } CountryEJB other = (CountryEJB)object; if (this.getId() != other.getId() && (this.getId() == null || !this.getId().equals(other.getId()))) return false; return true; }
/** * Returns a string representation of the object. This implementation constructs * that representation based on the id fields. * @return a string representation of the object. */ @Override public String toString() { return "addressEJB.CountryEJB[id=" + getId() + ", codeCountry="+getCodeCountry()+", nameCountry="+getNameCountry()+"]"; }
public String getCodeCountry() { return codeCountry; }
public void setCodeCountry(String codeCountry) { this.codeCountry = codeCountry; }
public String getNameCountry() { return nameCountry; }
public void setNameCountry(String nameCountry) { this.nameCountry = nameCountry; } }
|
Он нормально работает.. находится в том же EAR, куда лежат и JSF страницы... Вот фасад-менеджер JSF... | Код | /* * CountryEJBController.java * * Created on 19 Март 2007 г., 16:56 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */
package addressJSF;
import addressEJB.CountryEJB; import java.util.ArrayList; import java.util.Collection; import javax.annotation.Resource; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import javax.persistence.Query; import javax.transaction.UserTransaction;
/** * * @author U0109 */ public class CountryEJBController { /** Creates a new instance of CountryEJBController */ public CountryEJBController() { }
private CountryEJB countryEJB;
private DataModel model;
@Resource private UserTransaction utx;
@PersistenceUnit(unitName = "Address-warPU") private EntityManagerFactory emf;
private EntityManager getEntityManager() { return emf.createEntityManager(); }
private int batchSize = 20;
private int firstItem = 0;
public CountryEJB getCountryEJB() { return countryEJB; }
public void setCountryEJB(CountryEJB countryEJB) { this.countryEJB = countryEJB; }
public DataModel getDetailCountryEJBs() { return model; }
public void setDetailCountryEJBs(Collection<CountryEJB> m) { model = new ListDataModel(new ArrayList(m)); }
public String createSetup() { this.countryEJB = new CountryEJB(); return "countryEJB_create"; }
public String create() { EntityManager em = getEntityManager(); try { utx.begin(); em.persist(countryEJB); utx.commit(); addSuccessMessage("CountryEJB was successfully created."); } catch (Exception ex) { try { addErrorMessage(ex.getLocalizedMessage()); utx.rollback(); } catch (Exception e) { addErrorMessage(e.getLocalizedMessage()); } } finally { em.close(); } return "countryEJB_list"; }
public String detailSetup() { setCountryEJBFromRequestParam(); return "countryEJB_detail"; }
public String editSetup() { setCountryEJBFromRequestParam(); return "countryEJB_edit"; }
public String edit() { EntityManager em = getEntityManager(); try { utx.begin(); countryEJB = em.merge(countryEJB); utx.commit(); addSuccessMessage("CountryEJB was successfully updated."); } catch (Exception ex) { try { addErrorMessage(ex.getLocalizedMessage()); utx.rollback(); } catch (Exception e) { addErrorMessage(e.getLocalizedMessage()); } } finally { em.close(); } return "countryEJB_list"; }
public String destroy() { EntityManager em = getEntityManager(); try { utx.begin(); CountryEJB countryEJB = getCountryEJBFromRequestParam(); countryEJB = em.merge(countryEJB); em.remove(countryEJB); utx.commit(); addSuccessMessage("CountryEJB was successfully deleted."); } catch (Exception ex) { try { addErrorMessage(ex.getLocalizedMessage()); utx.rollback(); } catch (Exception e) { addErrorMessage(e.getLocalizedMessage()); } } finally { em.close(); } return "countryEJB_list"; }
public CountryEJB getCountryEJBFromRequestParam() { EntityManager em = getEntityManager(); try{ CountryEJB o = (CountryEJB) model.getRowData(); o = em.merge(o); return o; } finally { em.close(); } }
public void setCountryEJBFromRequestParam() { CountryEJB countryEJB = getCountryEJBFromRequestParam(); setCountryEJB(countryEJB); }
public DataModel getCountryEJBs() { EntityManager em = getEntityManager(); try{ Query q = em.createQuery("select object(o) from CountryEJB as o"); q.setMaxResults(batchSize); q.setFirstResult(firstItem); model = new ListDataModel(q.getResultList()); return model; } finally { em.close(); } }
public static void addErrorMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(null, facesMsg); }
public static void addSuccessMessage(String msg) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage("successInfo", facesMsg); }
public CountryEJB findCountryEJB(Long id) { EntityManager em = getEntityManager(); try{ CountryEJB o = (CountryEJB) em.find(CountryEJB.class, id); return o; } finally { em.close(); } }
public int getItemCount() { EntityManager em = getEntityManager(); try{ int count = ((Long) em.createQuery("select count(o) from CountryEJB as o").getSingleResult()).intValue(); return count; } finally { em.close(); } }
public int getFirstItem() { return firstItem; }
public int getLastItem() { int size = getItemCount(); return firstItem + batchSize > size ? size : firstItem + batchSize; }
public int getBatchSize() { return batchSize; }
public String next() { if (firstItem + batchSize < getItemCount()) { firstItem += batchSize; } return "countryEJB_list"; }
public String prev() { firstItem -= batchSize; if (firstItem < 0) { firstItem = 0; } return "countryEJB_list"; } }
|
есть еще конвертер, смысла которого я еще не понял (если кто подскажет - буду благодарен)... | Код | /* * CountryEJBConverter.java * * Created on 19 Март 2007 г., 16:56 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */
package addressJSF;
import addressEJB.CountryEJB; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter;
/** * * @author U0109 */ public class CountryEJBConverter implements Converter { /** Creates a new instance of CountryEJBConverter */ public CountryEJBConverter() { }
public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String string) { if (string == null) { return null; } Long id = new Long(string); CountryEJBController controller = (CountryEJBController) facesContext.getApplication().getELResolver().getValue( facesContext.getELContext(), null, "countryEJB"); return controller.findCountryEJB(id); }
public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object object) { if (object == null) { return null; } if(object instanceof CountryEJB) { CountryEJB o = (CountryEJB) object; return "" + o.getId(); } else { throw new IllegalArgumentException("object:" + object + " of type:" + object.getClass().getName() + "; expected type: addressEJB.CountryEJB"); } } }
|
А вот и полученная JSF-страница... | Код | <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>New CountryEJB</title> </head> <body> <f:view> <h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/> <h1>New countryEJB</h1> <h:form> <h:panelGrid columns="2"> <h:outputText value="CodeCountry:"/> <h:inputText id="codeCountry" value="#{countryEJB.countryEJB.codeCountry}" title="CodeCountry" /> <h:outputText value="NameCountry:"/> <h:inputText id="nameCountry" value="#{countryEJB.countryEJB.nameCountry}" title="NameCountry" /> </h:panelGrid> <h:commandLink action="#{countryEJB.create}" value="Create"/> <br> <h:commandLink action="countryEJB_list" value="Show All CountryEJB"/> <br> <a href="/Address-war/index.jsp">Back to index</a> </h:form> </f:view> </body> </html>
|
Эта страница появляется на экране браузера, однако при поптыке нажать кнопку CREATE для создания данных появляется ошибка... | Код | javax.el.PropertyNotFoundException: Target Unreachable, 'countryEJB' returned null
|
Я так понимаю - самого экземпляра бина-менеджера не существует... Он не создается... Почему же? И где его надо создать?
|