Managed Bean injection failure? - jsf

I have a bean that is supposed to retrieve people from a database and then put them in a list which is displayed on the webpage. I keep getting a managed bean injection failure though and it seems to be caused by some sort of link between the database and server getting screwed up.
here is the stack trace.
https://gist.github.com/blaxened/85a6861faf2373c26506
Here is the last part of the server log though it looks very similar to the stack trace.
https://gist.github.com/blaxened/f0bc6028d27cabcbd325
I know for a fact that the database/table is there
Here is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="com.jsfprohtml5_AIM_war_1.0PU" transaction-type="JTA">
<jta-data-source>jdbc/__default</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
This is the java class that connects to the database
package com.jsfprohtml5.firstapplication.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author Black
*/
#Entity
#Table(name = "MYTABLE")
#NamedQueries({
#NamedQuery(name = "AimStaff.findAll", query = "SELECT a FROM AimStaff a"),
#NamedQuery(name = "AimStaff.findById", query = "SELECT a FROM AimStaff a WHERE a.id = :id"),
#NamedQuery(name = "AimStaff.findBySname", query = "SELECT a FROM AimStaff a WHERE a.sname = :sname"),
#NamedQuery(name = "AimStaff.findByDatejoined", query = "SELECT a FROM AimStaff a WHERE a.datejoined = :datejoined"),
#NamedQuery(name = "AimStaff.findByLocale", query = "SELECT a FROM AimStaff a WHERE a.locale = :locale"),
#NamedQuery(name = "AimStaff.findByPhone", query = "SELECT a FROM AimStaff a WHERE a.phone = :phone")})
public class AimStaff implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Integer id;
#Size(max = 255)
#Column(name = "SNAME")
private String sname;
#Size(max = 255)
#Column(name = "DATEJOINED")
private String datejoined;
#Size(max = 255)
#Column(name = "LOCALE")
private String locale;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 100)
#Column(name = "PHONE")
private String phone;
public AimStaff() {
}
public AimStaff(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getDatejoined() {
return datejoined;
}
public void setDatejoined(String datejoined) {
this.datejoined = datejoined;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#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 AimStaff)) {
return false;
}
AimStaff other = (AimStaff) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.jsfprohtml5.firstapplication.model.AimStaff[ id=" + id + " ]";
}
}
so I am unsure what is wrong. Let me know what other files need to be uploaded if any.

Your Table MYTABLE cannot be found by the Applicationserver. Can you verify that the server is able to connect and find the Table inside the configured datasource?
Can you post your persistence.xml?

Related

java.lang.TypeNotPresentException: Type bookingSessionBean.Plot not present

I want to show the list of the plot from the database. I have created plot.java in package bookingSessionBean and viewPlot.java in package viewBean, but it doesn't work.
index.xhtml code:
<h:body>
<h1><h:outputText value="Selected Plot" /></h1>
<h:form>
<f:view>
<h:dataTable value="#{viewPlot.plots}" var="item">
<h:column>
<h:outputText value="#{item.plotno}" />
</h:column>
</h:dataTable>
</f:view>
</h:form>
</h:body>
viewPlot.java code
#ManagedBean
#Named(value = "viewPlot")
#SessionScoped
public class viewPlot implements Serializable {
#PersistenceContext(unitName = "2day4uPU")
private EntityManager em;
public viewPlot() {
}
public List<Plot> getPlots()
{
return em.createNamedQuery("Plot.findAll").getResultList();
}
}
Plot.java code
#Entity
#Table(name = "PLOT")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Plot.findAll", query = "SELECT p FROM Plot p"),
#NamedQuery(name = "Plot.findByPlotno", query = "SELECT p FROM Plot p WHERE p.plotno = :plotno"),
#NamedQuery(name = "Plot.findByStartdate", query = "SELECT p FROM Plot p WHERE p.startdate = :startdate"),
#NamedQuery(name = "Plot.findByEnddate", query = "SELECT p FROM Plot p WHERE p.enddate = :enddate"),
#NamedQuery(name = "Plot.findByAvailableplot", query = "SELECT p FROM Plot p WHERE p.availableplot = :availableplot")})
public class Plot implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "PLOTNO")
private Integer plotno;
#Basic(optional = false)
#NotNull
#Column(name = "STARTDATE")
#Temporal(TemporalType.DATE)
private Date startdate;
#Basic(optional = false)
#NotNull
#Column(name = "ENDDATE")
#Temporal(TemporalType.DATE)
private Date enddate;
#Column(name = "AVAILABLEPLOT")
private Integer availableplot;
#JoinColumn(name = "ACCOMNO", referencedColumnName = "ACCOMNO")
#ManyToOne(optional = false)
private Accomodation accomno;
#JoinColumn(name = "SITENO", referencedColumnName = "SITENO")
#ManyToOne(optional = false)
private Site siteno;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "plotno")
private Collection<Booking> bookingCollection;
public Plot() {
}
public Plot(Integer plotno) {
this.plotno = plotno;
}
public Plot(Integer plotno, Date startdate, Date enddate) {
this.plotno = plotno;
this.startdate = startdate;
this.enddate = enddate;
}
public Integer getPlotno() {
return plotno;
}
public void setPlotno(Integer plotno) {
this.plotno = plotno;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
public Integer getAvailableplot() {
return availableplot;
}
public void setAvailableplot(Integer availableplot) {
this.availableplot = availableplot;
}
public Accomodation getAccomno() {
return accomno;
}
public void setAccomno(Accomodation accomno) {
this.accomno = accomno;
}
public Site getSiteno() {
return siteno;
}
public void setSiteno(Site siteno) {
this.siteno = siteno;
}
#XmlTransient
public Collection<Booking> getBookingCollection() {
return bookingCollection;
}
public void setBookingCollection(Collection<Booking> bookingCollection) {
this.bookingCollection = bookingCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (plotno != null ? plotno.hashCode() : 0);
return hash;
}
#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 Plot)) {
return false;
}
Plot other = (Plot) object;
if ((this.plotno == null && other.plotno != null) || (this.plotno != null && !this.plotno.equals(other.plotno))) {
return false;
}
return true;
}
#Override
public String toString() {
return "bookingSessionBean.Plot[ plotno=" + plotno + " ]";
}
}
[ how can I solve this error? ]

JSF Updating a selectOneMenu based on another one

I'm new to JSF, and stuck in a problem.
I have a selectOneMenu for displaying the list of countries. When the user selects one of the country, there's another selectOneMenu having the cities (=regions in my case) should be auto-populated.
I tried several iterations for doing the same but didn't help.
Please let me know if anything else is also needed to help me. Would really appreciate it.
UPDATE:
Here's the code after adding listener:
<p:outputLabel for="countryRegistration">#{msg['country']}:</p:outputLabel>
<p:selectOneMenu id="countryRegistration" value="#{mbcActor.geoData.country}" style="width:120px;" >
<f:attribute name="country" value="java.util.List" />
<f:converter converterId="ViewScopedObjectConverter"/>
<f:selectItem itemLabel="#{msg['selectCountry']}" itemValue=""/>
<f:selectItems value="#{geoLists.countryList}" var="country" itemLabel="#{country.name}"/>
<p:ajax listener="#{mbcActor.geoData.updateRegions}" render="cityRegistration"/>
</p:selectOneMenu>
<p:message for="countryRegistration"/>
<p:outputLabel for="cityRegistration">#{msg['city']}:</p:outputLabel>
<p:selectOneMenu id="cityRegistration" value="#{mbcActor.geoData.region}" style="width:120px;">
<f:attribute name="regions" value="java.util.List" />
<f:converter converterId="ViewScopedObjectConverter"/>
<f:selectItem itemLabel="#{msg['selectCity']}" itemValue=""/>
<!--<f:selectItems value="#{geoLists.regionForCountry}" var="region" itemLabel="#{region.name}"/>-->
<f:selectItems value="#{geoLists.getRegionForCountry(country)}" var="region" itemLabel="#{region.description}"/>
</p:selectOneMenu>
<p:message for="cityRegistration"/>
But it says:
Oct 05, 2013 2:04:53 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: Target Unreachable, identifier 'mbcActor' resolved to null
javax.el.PropertyNotFoundException: Target Unreachable, identifier 'mbcActor' resolved to null
at org.apache.el.parser.AstValue.getTarget(AstValue.java:98)
at org.apache.el.parser.AstValue.invoke(AstValue.java:259)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processCustomListener(AjaxBehaviorListenerImpl.java:70)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processArgListener(AjaxBehaviorListenerImpl.java:59)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:47)
Beans:
package xxx.core.entities;
// Generated Oct 20, 2009 11:07:18 AM by Hibernate Tools 3.2.2.GA
import javax.faces.event.ValueChangeEvent;
import javax.inject.Inject;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static javax.persistence.GenerationType.IDENTITY;
/**
* DataActorGeo
*/
#Entity
#Table(name = "dataActorGeo")
// #org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#Access(AccessType.PROPERTY)
public class DataActorGeo implements java.io.Serializable {
private Integer id;
private Country country;
private Region region;
private String city;
private String province;
private String address;
private String addressLine2;
private String postCode;
private String nationality;
private String phone1;
private String phone2;
private Double latitude;
private Double longitude;
private Actor actor;
private List<Region> regions;
#Inject
EntityManager entityManager;
public void updateRegions() {
//Country ctry = (Country) event.getNewValue();
try{
System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
// if (regions == null) {
this.regions = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
.setParameter("countryId", country.getId())
.getResultList();
//countryIdCache = country.getId();
// }
System.out.println("aaaaaaaaaaa" + regions.toString());
} catch(Exception e){System.out.println("cccccccccc"); }//return new ArrayList<Region>(); }
//return regions;
}
public DataActorGeo() {
}
public DataActorGeo(Country country, String city) {
this.country = country;
this.city = city;
}
public DataActorGeo(Country country, Region region, String city, String address, String postCode, String phone1, String phone2, Actor actor) {
this.country = country;
this.region = region;
this.city = city;
this.address = address;
this.postCode = postCode;
this.phone1 = phone1;
this.phone2 = phone2;
this.actor = actor;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Country")
// #IndexedEmbedded(prefix = "country.")
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Region")
// #IndexedEmbedded(prefix = "region.")
public Region getRegion() {
return this.region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Region> getRegions()
{
return this.regions;
}
public void setRegions(List<Region> regions)
{
this.regions=regions;
}
#Column(name = "City")
// //#Field(index = Index.UN_TOKENIZED)
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "province")
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
#Column(name = "address")
// //#Field(index = Index.TOKENIZED)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "addressLine2")
// //#Field(index = Index.TOKENIZED)
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
#Column(name = "postCode")
// //#Field(index = Index.UN_TOKENIZED)
public String getPostCode() {
return this.postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#Column(name = "nationality")
// //#Field(index = Index.UN_TOKENIZED)
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
#Column(name = "phone1")
// //#Field(index = Index.UN_TOKENIZED)
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
#Column(name = "phone2")
// //#Field(index = Index.UN_TOKENIZED)
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
#OneToOne(mappedBy = "geoData")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "latitude")
public Double getLatitude() {
return latitude;
}
#Column(name = "longitude")
public Double getLongitude() {
return longitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
package xxx.lists;
import xxx.application.configuration.ISNetApp;
import xxx.core.entities.Country;
import xxx.core.entities.Region;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Named
#ViewScoped
public class GeoLists implements Serializable {
#Inject
EntityManager entityManager;
#Inject
ISNetApp sNetApp;
private List<Country> countryList;
public List<Country> getCountryList() {
if (countryList == null) {
String query = "select c from Country c order by c.ordering, c.name";
countryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
private List<Country> deliveryCountryList;
public List<Country> getDeliveryCountryList() {
if (deliveryCountryList == null) {
String query = "select c from Country c where c.groups LIKE '%D,%' order by c.ordering, c.name";
deliveryCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return deliveryCountryList;
}
public void setDeliveryCountryList(List<Country> deliveryCountryList) {
this.deliveryCountryList = deliveryCountryList;
}
public Country getCountryByIsoCode2(String isoCode2) {
String query = "select c from Country c where c.isoCode2=:ic";
try {
return (Country) entityManager.createQuery(query).setParameter("ic", isoCode2).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
private List<Region> regionForCountry;
private int countryIdCache;
private List<Region> regions;
public List<Region> getRegions(){
return this.regions;
}
public void setRegions(List<Region> regions){
this.regions = regions;
}
public List<Region> getRegionForCountryById(Long countryId) {
Country country = entityManager.find(Country.class, countryId.intValue());
return getRegionForCountry(country);
}
public List<Region> getRegionForCountry(Country country) {
try{
System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
//if (regionForCountry == null || countryIdCache != country.getId()) {
regionForCountry = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
.setParameter("countryId", 1)//country.getId())
.getResultList();
// countryIdCache = country.getId();
//}
// System.out.println("aaaaaaaaaaa" + regionForCountry.toString());
} catch(Exception e){System.out.println("cccccccccc"); return new ArrayList<Region>(); }
return regionForCountry;
}
public void setRegionForCountry(List<Region> regionForCountry) {
this.regionForCountry = regionForCountry;
}
private Country mainCountry;
private Country country;
public void setCountry(Country country) {
this.country=country;
}
public Country getCountry(){
return this.country;
}
public Country getMainCountry() {
if (mainCountry == null) {
mainCountry = entityManager.find(Country.class, sNetApp.getMainCountryId());
}
return mainCountry;
}
public void setMainCountry(Country mainCountry) {
this.mainCountry = mainCountry;
}
private List<Country> specificGroupCountryList;
private String groupCache;
public List<Country> getSpecificGroupCountryList(String group) {
if (specificGroupCountryList == null || groupCache == null || groupCache.compareTo(group) != 0) {
String query = "from Country where groups LIKE '%" + group + ",%' order by ordering, name";
specificGroupCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return specificGroupCountryList;
}
public void setSpecificGroupCountryList(List<Country> specificGroupCountryList) {
this.specificGroupCountryList = specificGroupCountryList;
}
}
mbcActor is a param defined as:
<ui:param name="mbcActor" value="#{registrationHelper.newActor}"/>
AbstractActor:
#MappedSuperclass
public class AbstractActor extends AbstractGenericElement implements java.io.Serializable, IGenericElement, EmailContact {
private static Logger log = LoggerFactory.getLogger(AbstractActor.class);
public static enum Gender {
Male,
Female
}
/**
* Transient
*/
private boolean selected;
private Integer id;
private Long version;
private byte type;
private String language;
private byte status;
private byte publicStatus;
private String permalink;
private Boolean customPermalink;
private String displayName;
private String forename;
private String surname;
private Gender gender;
private Date birthday;
private String mobile;
private Byte subType;
private String stringValue1;
private String stringValue2;
private String stringValue3;
#Transient
#XmlTransient
private Integer age;
private String profileMessage;
private String statusMessage;
private String email;
private String username;
private String passwordHash;
private int passwordHashIterations;
private String salt;
private String timezone;
private String activationCode;
private Boolean activationEmailSent;
private Integer completitionPercentage;
private Integer ordering;
// Stats
private ActorStats stats;
// Extensions
private DataActorGeo geoData;
private DataActorExtended dataActorExtended;
private Boolean acceptNewsletter;
private Boolean emailAlertsEnabled;
private Set<ActorTag> actorTags = new HashSet<ActorTag>(0);
private List<Role> roles = new ArrayList<Role>(0);
private Actor newDataToBeModerated;
private Date expireDate;
private Integer points;
private BigDecimal wallet;
private Byte emailAlertsType;
private Byte emailOffersType;
private String emailHash;
// Data blob
private byte[] data;
private Set<ActorInCategory> actorInCategories = new HashSet<ActorInCategory>(
0);
private List<ActorAttribute> actorAttributes = new ArrayList<ActorAttribute>(0);
public AbstractActor() {
this.version = 1l;
this.activationEmailSent = false;
this.acceptNewsletter = true;
this.emailAlertsEnabled = true;
this.completitionPercentage = 0;
this.customPermalink = false;
this.wallet = new BigDecimal(0);
this.points = 0;
this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
}
public AbstractActor(byte type, byte status) {
this.version = 1l;
this.type = type;
this.status = status;
this.publicStatus = ActorConstants.PUBLIC_STATUS_OFFLINE;
this.activationEmailSent = false;
this.acceptNewsletter = true;
this.emailAlertsEnabled = true;
this.completitionPercentage = 0;
this.customPermalink = false;
this.wallet = new BigDecimal(0);
this.points = 0;
this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "geoData", nullable = true)
#org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public DataActorGeo getGeoData() {
return this.geoData;
}
public void setGeoData(DataActorGeo geoData) {
this.geoData = geoData;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
public Set<ActorInCategory> getActorInCategories() {
return this.actorInCategories;
}
public void setActorInCategories(Set<ActorInCategory> actorInCategories) {
this.actorInCategories = actorInCategories;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
public List<ActorAttribute> getActorAttributes() {
return this.actorAttributes;
}
public void setActorAttributes(List<ActorAttribute> actorAttributes) {
this.actorAttributes = actorAttributes;
}
}
Your <p:ajax> tag uses the render attribute, which isn't predefined. The attribute you want is update.
supposing that registrationHelper.newActor is an instance of of a Managed Bean, I think it's probably not initialized. Why don't you make sure it is, by creating it on RegistrationHelper's PostConstruct, or even get it through a method like
public AbstractActor createNewActor() {
newActor = new AbstractActor();
return newActor;
}
<ui:param name="mbcActor" value="#{registrationHelper.createNewActor}"/>

NoSuchMethodException on eclipselink

I'm developing a javaEE project using Glassfish and EclipseLink.
ALthough, when i run my app i get the following exceptions:
Exception [EclipseLink-60] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The method [_persistence_setjuego_vh] or [_persistence_getjuego_vh] is not defined in the object [model.ConcursosJuego].
Internal Exception: java.lang.NoSuchMethodException: model.ConcursosJuego._persistence_getjuego_vh()
i have no clue why i am getting this exception becuase the Entity "Juegos" has that methods, this is the Entity Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author user
*/
#Entity
#NamedQueries({
#NamedQuery(name = "Juego.findAll", query = "SELECT j FROM Juego j"),
#NamedQuery(name = "Juego.findById", query = "SELECT j FROM Juego j WHERE j.id = :id"),
#NamedQuery(name = "Juego.findByNombre", query = "SELECT j FROM Juego j WHERE j.nombre = :nombre"),
#NamedQuery(name = "Juego.findByUrl", query = "SELECT j FROM Juego j WHERE j.url = :url"),
#NamedQuery(name = "Juego.findByMultijugador", query = "SELECT j FROM Juego j WHERE j.multijugador = :multijugador"),
#NamedQuery(name = "Juego.findByTopejugadores", query = "SELECT j FROM Juego j WHERE j.topejugadores = :topejugadores"),
#NamedQuery(name = "Juego.findByEstado", query = "SELECT j FROM Juego j WHERE j.estado = :estado")})
public class Juego implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
private String id;
#Size(max = 255)
private String nombre;
#Size(max = 1000)
private String url;
private BigInteger multijugador;
private BigInteger topejugadores;
#Size(max = 1)
private String estado;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<Partida> partidaList;
#JoinColumn(name = "RANKING_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Ranking ranking;
#JoinColumn(name = "CATEGORIA_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Categoria categoria;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<ConcursosJuego> concursosJuegoList;
public Juego() {
}
public Juego(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public BigInteger getMultijugador() {
return multijugador;
}
public void setMultijugador(BigInteger multijugador) {
this.multijugador = multijugador;
}
public BigInteger getTopejugadores() {
return topejugadores;
}
public void setTopejugadores(BigInteger topejugadores) {
this.topejugadores = topejugadores;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public List<Partida> getPartidaList() {
return partidaList;
}
public void setPartidaList(List<Partida> partidaList) {
this.partidaList = partidaList;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public List<InteraccionUsuarioJuego> getInteraccionUsuarioJuegoList() {
return interaccionUsuarioJuegoList;
}
public void setInteraccionUsuarioJuegoList(List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList) {
this.interaccionUsuarioJuegoList = interaccionUsuarioJuegoList;
}
public List<ConcursosJuego> getConcursosJuegoList() {
return concursosJuegoList;
}
public void setConcursosJuegoList(List<ConcursosJuego> concursosJuegoList) {
this.concursosJuegoList = concursosJuegoList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#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 Juego)) {
return false;
}
Juego other = (Juego) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.Juego[ id=" + id + " ]";
}
public Ranking getRanking() {
return ranking;
}
public void setRanking(Ranking ranking) {
this.ranking = ranking;
}
}
this is the application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" id="Application_ID" version="6">
<display-name>p_ear</display-name>
<module>
<ejb>p.jar</ejb>
</module>
<module>
<web>
<web-uri>p_web.war</web-uri>
<context-root>p_web</context-root>
</web>
</module>
</application>
i have tried eclipse link persistance and methods in other entities and it does work.
(This is the first entity that have more than 1 relation)
thanks

jpql Join query

i have an association table called MenuPrevilege between 2 tables called Menu and Previlege.
In order to get all menus of a specific previlege i created a named query in the Menu entity:
#Entity
#NamedQueries( {
#NamedQuery(name = "getAllMenus", query = "select m from Menu m"),
#NamedQuery(name = "getMenusByPrevilegeId", query = "select m from Menu m
JOIN m.menuPrevilege mp where mp.previlege_id = :p")})
public class Menu implements Serializable {
private String url;
private String description;
private List<MenuPrevilege> menuPrevilges;
private static final long serialVersionUID = 1L;
public Menu() {
super();
}
#Id
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public void setMenuPrevilges(List<MenuPrevilege> menuPrevilges) {
if (menuPrevilges == null)
menuPrevilges = new ArrayList<MenuPrevilege>();
this.menuPrevilges = menuPrevilges;
}
#OneToMany(mappedBy = "menu", cascade = CascadeType.REMOVE)
public List<MenuPrevilege> getMenuPrevilges() {
if (menuPrevilges == null)
menuPrevilges = new ArrayList<MenuPrevilege>();
return menuPrevilges;
}
public Menu(String url, String description) {
super();
this.url = url;
this.description = description;
}
}
i'm having this exception org.hibernate.QueryException: could not resolve property:menuPrevilege , and i don't know how to deal with it. this is the MenuPrevilege entity:
#Entity
#Table(name = "Menu_Previlege")
public class MenuPrevilege implements Serializable {
private IdMenuPrevilege idmenuPrevilege = new IdMenuPrevilege();
private Date activationDate;
private Date deactivationDate;
private Menu menu;
private Previlege previlege;
private static final long serialVersionUID = 1L;
public MenuPrevilege() {
super();
}
#EmbeddedId
public IdMenuPrevilege getIdmenuPrevilege() {
return this.idmenuPrevilege;
}
public void setIdmenuPrevilege(IdMenuPrevilege idmenuPrevilege) {
this.idmenuPrevilege = idmenuPrevilege;
}
#Temporal(TemporalType.DATE)
public Date getActivationDate() {
return this.activationDate;
}
public void setActivationDate(Date activationDate) {
this.activationDate = activationDate;
}
#Temporal(TemporalType.DATE)
public Date getDeactivationDate() {
return this.deactivationDate;
}
public void setDeactivationDate(Date deactivationDate) {
this.deactivationDate = deactivationDate;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
#ManyToOne
#JoinColumn(name = "menu_id", insertable = false, updatable = false)
public Menu getMenu() {
return menu;
}
public void setPrevilege(Previlege previlege) {
this.previlege = previlege;
}
#ManyToOne
#JoinColumn(name = "previlege_id", insertable = false, updatable = false)
public Previlege getPrevilege() {
return previlege;
}
public MenuPrevilege(Menu menu, Previlege previlege) {
super();
getIdmenuPrevilege().setIdMenu(menu.getUrl());
getIdmenuPrevilege().setIdPrevilege(previlege.getPrevilegeId());
this.setMenu(menu);
this.setPrevilege(previlege);
menu.getMenuPrevilges().add(this);
previlege.getPrevilegeMenus().add(this);
}
}
I made name refactoring to my code edit my query and everything seems to be working. Here are the changes :
in the named query:
#NamedQuery(name = "getMenusByPrevilegeId", query = "select m from Menu m JOIN
m.previleges p where p.previlege.previlegeId = :p")})
the entity attribute
private List<MenuPrevilege> previleges;
// getters and setters as well
in the constructor of the MenuPrevilege entity
public MenuPrevilege(Menu menu, Previlege previlege) {
super();
getIdmenuPrevilege().setIdMenu(menu.getUrl());
getIdmenuPrevilege().setIdPrevilege(previlege.getPrevilegeId());
this.setMenu(menu);
this.setPrevilege(previlege);
menu.getPrevileges().add(this);
previlege.getMenus().add(this);
}
as u can notice it was a syntax error in my query that caused the exception.

problem with select statement in many to one relational in EJB3 and JSF

Hi All
i wonder how to select between many to one relational
i have two table Sub_category and Items
sub category is own of relational, it contain list of Items
Two class follow:
#Entity
#Table(name = "item")
#NamedQueries({
#NamedQuery(name = "Items.findAll", query = "SELECT i FROM Items i"),
#NamedQuery(name = "Items.findByItemid", query = "SELECT i FROM Items i WHERE i.itemid = :itemid"),
#NamedQuery(name = "Items.findByItemName", query = "SELECT i FROM Items i WHERE i.itemName = :itemName"),
#NamedQuery(name = "Items.findByItemDescribe", query = "SELECT i FROM Items i WHERE i.itemDescribe = :itemDescribe"),
#NamedQuery(name = "Items.findByImg", query = "SELECT i FROM Items i WHERE i.img = :img"),
#NamedQuery(name = "Items.findByInstock", query = "SELECT i FROM Items i WHERE i.instock = :instock"),
#NamedQuery(name = "Items.findByPrice", query = "SELECT i FROM Items i WHERE i.price = :price"),
#NamedQuery(name = "Items.findByFine", query = "SELECT i FROM Items i WHERE i.fine = :fine"),
#NamedQuery(name = "Items.findByDateexp", query = "SELECT i FROM Items i WHERE i.dateexp = :dateexp"),
#NamedQuery(name = "Items.findByAuthor", query = "SELECT i FROM Items i WHERE i.author = :author"),
#NamedQuery(name = "Items.findByToprent", query = "SELECT i FROM Items i WHERE i.toprent = :toprent"),
#NamedQuery(name = "Items.findByStatus", query = "SELECT i FROM Items i WHERE i.status = :status")})
public class Items implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "itemid")
private Integer itemid;
#Basic(optional = false)
#Column(name = "item_name")
private String itemName;
#Column(name = "item_describe")
private String itemDescribe;
#Lob
#Column(name = "item_detail")
private String itemDetail;
#Column(name = "img")
private String img;
#Basic(optional = false)
#Column(name = "instock")
private int instock;
#Basic(optional = false)
#Column(name = "price")
private BigDecimal price;
#Basic(optional = false)
#Column(name = "fine")
private BigDecimal fine;
#Basic(optional = false)
#Column(name = "dateexp")
private int dateexp;
#Column(name = "author")
private String author;
#Column(name = "toprent")
private Integer toprent;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private ItemStatus status;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<RentItem> rentItemList;
#JoinColumn(name = "cat_id", referencedColumnName = "subcatid")
#ManyToOne(optional = false)
private SubCat subCat;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<Cart> cartList;
public Items() {
}
public Items(Integer itemid) {
this.itemid = itemid;
}
public Items(Integer itemid, String itemName, int instock, BigDecimal price, BigDecimal fine, int dateexp) {
this.itemid = itemid;
this.itemName = itemName;
this.instock = instock;
this.price = price;
this.fine = fine;
this.dateexp = dateexp;
}
public Integer getItemid() {
return itemid;
}
public void setItemid(Integer itemid) {
this.itemid = itemid;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescribe() {
return itemDescribe;
}
public void setItemDescribe(String itemDescribe) {
this.itemDescribe = itemDescribe;
}
public String getItemDetail() {
return itemDetail;
}
public void setItemDetail(String itemDetail) {
this.itemDetail = itemDetail;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getInstock() {
return instock;
}
public void setInstock(int instock) {
this.instock = instock;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getFine() {
return fine;
}
public void setFine(BigDecimal fine) {
this.fine = fine;
}
public int getDateexp() {
return dateexp;
}
public void setDateexp(int dateexp) {
this.dateexp = dateexp;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getToprent() {
return toprent;
}
public void setToprent(Integer toprent) {
this.toprent = toprent;
}
public ItemStatus getStatus() {
return status;
}
public void setStatus(ItemStatus status) {
this.status = status;
}
public List<RentItem> getRentItemList() {
return rentItemList;
}
public void setRentItemList(List<RentItem> rentItemList) {
this.rentItemList = rentItemList;
}
public SubCat getSubCat() {
return subCat;
}
public void setSubCat(SubCat subCat) {
this.subCat = subCat;
}
public List<Cart> getCartList() {
return cartList;
}
public void setCartList(List<Cart> cartList) {
this.cartList = cartList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (itemid != null ? itemid.hashCode() : 0);
return hash;
}
#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 Items)) {
return false;
}
Items other = (Items) object;
if ((this.itemid == null && other.itemid != null) || (this.itemid != null && !this.itemid.equals(other.itemid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Item[itemid=" + itemid + "]";
}
}
and subcategory class :
#Entity
#Table(name = "sub_cat")
#NamedQueries({
#NamedQuery(name = "SubCat.findAll", query = "SELECT s FROM SubCat s"),
#NamedQuery(name = "SubCat.findBySubcatid", query = "SELECT s FROM SubCat s WHERE s.subcatid = :subcatid"),
#NamedQuery(name = "SubCat.findBySubcatName", query = "SELECT s FROM SubCat s WHERE s.subcatName = :subcatName")})
public class SubCat implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "subcatid")
private Integer subcatid;
#Basic(optional = false)
#Column(name = "subcat_name")
private String subcatName;
#JoinColumn(name = "cat_parent", referencedColumnName = "cate_id")
#ManyToOne(optional = false)
private Category category;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "subCat")
private List<Items> itemList;
public SubCat() {
}
public SubCat(Integer subcatid) {
this.subcatid = subcatid;
}
public SubCat(Integer subcatid, String subcatName) {
this.subcatid = subcatid;
this.subcatName = subcatName;
}
public Integer getSubcatid() {
return subcatid;
}
public void setSubcatid(Integer subcatid) {
this.subcatid = subcatid;
}
public String getSubcatName() {
return subcatName;
}
public void setSubcatName(String subcatName) {
this.subcatName = subcatName;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Items> getItemList() {
return itemList;
}
public void setItemList(List<Items> itemList) {
this.itemList = itemList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (subcatid != null ? subcatid.hashCode() : 0);
return hash;
}
#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 SubCat)) {
return false;
}
SubCat other = (SubCat) object;
if ((this.subcatid == null && other.subcatid != null) || (this.subcatid != null && !this.subcatid.equals(other.subcatid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.SubCat[subcatid=" + subcatid + "]";
}
}
i have stateless bean for handle subcat such as:
#Stateless
#LocalBean
public class SubCatDAO {
#PersistenceContext(unitName = "mcGrawLibPro-ejbPU")
private EntityManager em;
public List<SubCat> retrieveAllSubCat(){
return em.createNamedQuery("SubCat.findAll").getResultList();
}
public SubCat updateSubCat(SubCat sc){
return em.merge(sc);
}
public void deleteSubCat(SubCat sc){
em.remove(em.merge(sc));
}
public SubCat addSubCat(SubCat sc){
em.persist(sc);
return sc;
}
public void persist(Object object) {
em.persist(object);
}
public List<Category> retrieveAllCat(){
return em.createNamedQuery("Category.findAll").getResultList();
}
public List<Items> getAllItemsSubCat(SubCat sub){
em.refresh(em.merge(sub));
List<Items> items = sub.getItemList();
ArrayList<Items> toReturn = new ArrayList<Items>(items.size());
for(Items iItem : items){
toReturn.add(iItem);
}
return toReturn;
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
as you can see in stateless bean of subcat , i have written one method return List
and in JSF Managed Bean of subcat i write one method return List to view (JSF)
such as:
public List<Items> getAllItemsSub(){
return subCatDAO.getAllItemsSubCat(sub);
}
(subCatDAO is Stateless bean)
also in JSF Managened Bean of subcat i inital subcat follow:
public BeanConstructor(){
sub = new SubCat(1);
}
my problem is in view (JSF ) i was print list of items to show to user , but i can't get anything,i just see blank,
my code sample :
<h:ouputText value="#{bean.allItemSub.itemid}"/>
when i print bean.allItemSub it return [] <===
why it empty?
I don't really understand your implementation of the getAllItemsSubCat(SubCat sub) method in your EJB. I would rewrite it like this.
First, add a named query to find Items for given a SubCategory:
#NamedQuery(name = "Items.findBySubCat",
query = "SELECT i FROM Items i WHERE i.subCat = :subCat")
And rewrite the EJB method as follow:
public List<Items> getAllItemsSubCat(SubCat sub){
return em.createNamedQuery("Items.findBySubCat").setParameter("subCat", sub)
.getResultList();
}
Then, activate SQL logging (at the JPA provider level) to make sure the method actually returns something.

Resources