JSF Updating a selectOneMenu based on another one - jsf

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}"/>

Related

Get JSF Drop down value and save to database [duplicate]

This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 7 years ago.
I have two tables into database: Book and Category. Now I want to make page where user can add books into Book table, but with selecting appropriate category from Category table.
I can add book into table but I can not save value category in Book table.
[
As you can see category from Book table is Foreign key with category_id from Category table.
Here are model classes:
Book model
#Entity
#Table(name = "book")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b"),
#NamedQuery(name = "Book.findByBookId", query = "SELECT b FROM Book b WHERE b.bookId = :bookId")})
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "book_id")
private Integer bookId;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "name")
private String name;
#Lob
#Size(max = 65535)
#Column(name = "description")
private String description;
#JoinColumn(name = "category", referencedColumnName = "category_id")
#ManyToOne
private Category category;
public Book() {
}
public Book(Integer bookId) {
this.bookId = bookId;
}
public Book(Integer bookId, String name) {
this.bookId = bookId;
this.name = name;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
#Override
public int hashCode() {
int hash = 0;
hash += (bookId != null ? bookId.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 Book)) {
return false;
}
Book other = (Book) object;
if ((this.bookId == null && other.bookId != null) || (this.bookId != null && !this.bookId.equals(other.bookId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.biblioteka.app.domen.Book[ bookId=" + bookId + " ]";
}
}
Category model
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findByCategoryId", query = "SELECT c FROM Category c WHERE c.categoryId = :categoryId")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "category_id")
private Integer categoryId;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "name")
private String name;
#Lob
#Size(max = 65535)
#Column(name = "description")
private String description;
#OneToMany(mappedBy = "category")
private Collection<Book> bookCollection;
public Category() {
}
public Category(Integer categoryId) {
this.categoryId = categoryId;
}
public Category(Integer categoryId, String name) {
this.categoryId = categoryId;
this.name = name;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (categoryId != null ? categoryId.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 Category)) {
return false;
}
Category other = (Category) object;
if ((this.categoryId == null && other.categoryId != null) || (this.categoryId != null && !this.categoryId.equals(other.categoryId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.biblioteka.app.domen.Category[ categoryId=" + categoryId + " ]";
}
}
Now I have JSF page where I add bookes to database. I have dropdown lists that loads categories into it. User should select one category and save book to table.
This is code from JSF addBook page.
<p:layoutUnit position="center">
<h:form>
<p:inputText value="#{bookBean.name}" a:placeholder="Ime knjige"></p:inputText><br/>
<p:inputText value="#{bookBean.description}" a:placeholder="Opis knjige"></p:inputText><br/>
<p:selectOneMenu value="#{bookBean.category}">
<f:selectItems value="#{categoryBean.allCategories}" var="c"
itemLabel="#{c.name}" itemValue="#{c.categoryId}"/>
</p:selectOneMenu>
<b/><b/>
<p:commandButton value="Dodaj knjigu" action="#{bookBean.addBook()}"/>
</h:form>
</p:layoutUnit>
As you can see I use selectOneMenu with value bookBean.category and then I am not sure what I need to set as value in selectItems.
This is BookBean code:
#ManagedBean
#ApplicationScoped
public class BookBean {
String name;
String description;
int categoryId;
Category category;
#Inject
public BookEJB bookEJB;
public void addBook(){
Book book = new Book();
book.setName(name);
book.setDescription(description);
book.setCategory(category);
bookEJB.addBook(book);
}
public List<Book> getAllBooks(){
return bookEJB.getAll();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public BookEJB getBookEJB() {
return bookEJB;
}
public void setBookEJB(BookEJB bookEJB) {
this.bookEJB = bookEJB;
}
}
Try this :
<f:selectItems value="#{categoryBean.allCategories}" var="c"
itemLabel="#{c.name}" itemValue="#{c}"/>
Listed item name would be category name and category will be assigned to bookBean.category and this can be set as book category and persisted.
Hope this helps.

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? ]

Transactions in JSF Netbeans 7.3.1 generated code

I'm new to Java EE, following the learning by doing approach. In a very simple Mysql database with Netbeans 7.3.1 having a Patient table relates to a Person table, I'm having trouble understanding Netbeans generated code. I want to create a transaction where a Person and a Patient should be created and persisted with roll back possibility. Should i create a separate controller to handle such a transaction. Kindly help with a link to some similar example code. Code generated by Netbeans is below. (Some imports and redundant code removed)
Person.java
package entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "person")
#XmlRootElement
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "firstname")
private String firstname;
#Size(max = 255)
#Column(name = "email")
private String email;
#Size(max = 15)
#Column(name = "mobile")
private String mobile;
#Size(max = 15)
#Column(name = "residence")
private String residence;
#Size(max = 15)
#Column(name = "office")
private String office;
#Size(max = 255)
#Column(name = "address")
private String address;
#Size(max = 20)
#Column(name = "nic")
private String nic;
#Basic(optional = false)
#NotNull
#Column(name = "regdate")
#Temporal(TemporalType.DATE)
private Date regdate;
#Basic(optional = false)
#NotNull
#Column(name = "dob")
#Temporal(TemporalType.DATE)
private Date dob;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "lastname")
private String lastname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 25)
#Column(name = "city")
private String city;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
private Collection<Patient> patientCollection;
public Person() {
}
public Person(Integer id) {
this.id = id;
}
public Person(Integer id, String firstname, Date regdate, Date dob, String lastname, String city) {
this.id = id;
this.firstname = firstname;
this.regdate = regdate;
this.dob = dob;
this.lastname = lastname;
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getResidence() {
return residence;
}
public void setResidence(String residence) {
this.residence = residence;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlTransient
public Collection<Patient> getPatientCollection() {
return patientCollection;
}
public void setPatientCollection(Collection<Patient> patientCollection) {
this.patientCollection = patientCollection;
}
}
Patient.java
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "patient")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Patient.findAll", query = "SELECT p FROM Patient p"),
#NamedQuery(name = "Patient.findById", query = "SELECT p FROM Patient p WHERE p.id = :id"),
#NamedQuery(name = "Patient.findByPatientcode", query = "SELECT p FROM Patient p WHERE p.patientcode = :patientcode"),
#NamedQuery(name = "Patient.findByHistory", query = "SELECT p FROM Patient p WHERE p.history = :history"),
#NamedQuery(name = "Patient.findByExtPatientCode", query = "SELECT p FROM Patient p WHERE p.extPatientCode = :extPatientCode")})
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "patientcode")
private String patientcode;
#Size(max = 255)
#Column(name = "history")
private String history;
#Size(max = 20)
#Column(name = "ExtPatientCode")
private String extPatientCode;
#JoinColumn(name = "personid", referencedColumnName = "id")
#ManyToOne(optional = false)
private Person personid;
public Patient() {
}
public Patient(Integer id) {
this.id = id;
}
public Patient(Integer id, String patientcode) {
this.id = id;
this.patientcode = patientcode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPatientcode() {
return patientcode;
}
public void setPatientcode(String patientcode) {
this.patientcode = patientcode;
}
public String getHistory() {
return history;
}
public void setHistory(String history) {
this.history = history;
}
public String getExtPatientCode() {
return extPatientCode;
}
public void setExtPatientCode(String extPatientCode) {
this.extPatientCode = extPatientCode;
}
public Person getPersonid() {
return personid;
}
public void setPersonid(Person personid) {
this.personid = personid;
}
}
AbstractFacade.java
package session;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
}
PatientFacade.java
package session;
import entity.Patient;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PatientFacade extends AbstractFacade<Patient> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PatientFacade() {
super(Patient.class);
}
}
PersonFacade.java
package session;
import entity.Person;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PersonFacade extends AbstractFacade<Person> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PersonFacade() {
super(Person.class);
}
}
PersonController.java
package controllers;
import entity.Person;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PersonFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("personController")
#SessionScoped
public class PersonController implements Serializable {
private Person current;
private DataModel items = null;
#EJB
private session.PersonFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PersonController() {
}
public Person getSelected() {
if (current == null) {
current = new Person();
selectedItemIndex = -1;
}
return current;
}
private PersonFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Person();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Person getPerson(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Person.class)
public static class PersonControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PersonController controller = (PersonController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "personController");
return controller.getPerson(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
}
}
PatientController.java
package controllers;
import entity.Patient;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PatientFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("patientController")
#SessionScoped
public class PatientController implements Serializable {
private Patient current;
private DataModel items = null;
#EJB
private session.PatientFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PatientController() {
}
public Patient getSelected() {
if (current == null) {
current = new Patient();
selectedItemIndex = -1;
}
return current;
}
private PatientFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Patient();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Patient getPatient(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Patient.class)
public static class PatientControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PatientController controller = (PatientController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "patientController");
return controller.getPatient(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Patient) {
Patient o = (Patient) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Patient.class.getName());
}
}
}
}
Thanks in advance.
Fact: a single #Stateless EJB method call counts as a single full transaction.
Just make use of this fact. Create a new method in the #Stateless EJB which executes all necessary queries at once and then let your JSF backing bean call exactly that single method.
That's by the way exactly one of main reasons why EJBs exist: transparent transaction management. You seem to have missed this not unimportant fact while learning Java EE.

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.

java.lang.IllegalArgumentException at javax.faces.component.UIComponentBase.validateId

Exception
java.lang.IllegalArgumentException: partidosPK.idEquipo
at javax.faces.component.UIComponentBase.validateId(UIComponentBase.java:551)
at javax.faces.component.UIComponentBase.setId(UIComponentBase.java:366)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply (ComponentTagHandlerDelegateImpl.java:168)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:114)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:91)
at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:120)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:204)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:114)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:91)
at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:120)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:204)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:114)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:91)
at com.sun.faces.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:97)
at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:172)
and keeps going... also
Entity bean
private String ganador;
#Column(name = "fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date fecha;
#Column(name = "golesEquipoGanador")
private Integer golesEquipoGanador;
#Column(name = "golesEquipoPerdedor")
private Integer golesEquipoPerdedor;
#Column(name = "perdedor")
private String perdedor;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "partidos")
private Collection<Goleadores> goleadoresCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "partidos")
private Collection<SancionesJugadores> sancionesJugadoresCollection;
#JoinColumns({
#JoinColumn(name = "idCampeonato", referencedColumnName = "idCampeonato", insertable = false, updatable = false),
#JoinColumn(name = "idPartido", referencedColumnName = "idEquipo", insertable = false, updatable = false)})
#ManyToOne(optional = false)
private EquiposPorCampeonato equiposPorCampeonato;
public Partidos() {
}
public Partidos(PartidosPK partidosPK) {
this.partidosPK = partidosPK;
}
public Partidos(int idCampeonato, int idEquipo, int idPartido) {
this.partidosPK = new PartidosPK(idCampeonato, idEquipo, idPartido);
}
public PartidosPK getPartidosPK() {
return partidosPK;
}
public void setPartidosPK(PartidosPK partidosPK) {
this.partidosPK = partidosPK;
}
public String getGanador() {
return ganador;
}
public void setGanador(String ganador) {
this.ganador = ganador;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Integer getGolesEquipoGanador() {
return golesEquipoGanador;
}
public void setGolesEquipoGanador(Integer golesEquipoGanador) {
this.golesEquipoGanador = golesEquipoGanador;
}
public Integer getGolesEquipoPerdedor() {
return golesEquipoPerdedor;
}
public void setGolesEquipoPerdedor(Integer golesEquipoPerdedor) {
this.golesEquipoPerdedor = golesEquipoPerdedor;
}
public String getPerdedor() {
return perdedor;
}
public void setPerdedor(String perdedor) {
this.perdedor = perdedor;
}
public Collection<Goleadores> getGoleadoresCollection() {
return goleadoresCollection;
}
public void setGoleadoresCollection(Collection<Goleadores> goleadoresCollection) {
this.goleadoresCollection = goleadoresCollection;
}
public Collection<SancionesJugadores> getSancionesJugadoresCollection() {
return sancionesJugadoresCollection;
}
public void setSancionesJugadoresCollection(Collection<SancionesJugadores> sancionesJugadoresCollection) {
this.sancionesJugadoresCollection = sancionesJugadoresCollection;
}
public EquiposPorCampeonato getEquiposPorCampeonato() {
return equiposPorCampeonato;
}
public void setEquiposPorCampeonato(EquiposPorCampeonato equiposPorCampeonato) {
this.equiposPorCampeonato = equiposPorCampeonato;
}
#Override
public int hashCode() {
int hash = 0;
hash += (partidosPK != null ? partidosPK.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 Partidos)) {
return false;
}
Partidos other = (Partidos) object;
if ((this.partidosPK == null && other.partidosPK != null) || (this.partidosPK != null && !this.partidosPK.equals(other.partidosPK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "" + partidosPK + "";
}
}
related primaryKey entitybean
#Embeddable
public class PartidosPK implements Serializable {
#Basic(optional = false)
#Column(name = "idCampeonato")
private int idCampeonato;
#Basic(optional = false)
#Column(name = "idEquipo")
private int idEquipo;
#Basic(optional = false)
#Column(name = "idPartido")
private int idPartido;
public PartidosPK() {
}
public PartidosPK(int idCampeonato, int idEquipo, int idPartido) {
this.idCampeonato = idCampeonato;
this.idEquipo = idEquipo;
this.idPartido = idPartido;
}
public int getIdCampeonato() {
return idCampeonato;
}
public void setIdCampeonato(int idCampeonato) {
this.idCampeonato = idCampeonato;
}
public int getIdEquipo() {
return idEquipo;
}
public void setIdEquipo(int idEquipo) {
this.idEquipo = idEquipo;
}
public int getIdPartido() {
return idPartido;
}
public void setIdPartido(int idPartido) {
this.idPartido = idPartido;
}
#Override
public int hashCode() {
int hash = 0;
hash += (int) idCampeonato;
hash += (int) idEquipo;
hash += (int) idPartido;
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 PartidosPK)) {
return false;
}
PartidosPK other = (PartidosPK) object;
if (this.idCampeonato != other.idCampeonato) {
return false;
}
if (this.idEquipo != other.idEquipo) {
return false;
}
if (this.idPartido != other.idPartido) {
return false;
}
return true;
}
#Override
public String toString() {
return "" + idCampeonato + ", " + idEquipo + ", " + idPartido + "";
}
}
Last but not least
#Entity
#Table(name = "equipos")
#NamedQueries({
#NamedQuery(name = "Equipos.findAll", query = "SELECT e FROM Equipos e"),
#NamedQuery(name = "Equipos.findByIdEquipo", query = "SELECT e FROM Equipos e WHERE e.idEquipo = :idEquipo"),
#NamedQuery(name = "Equipos.findByNombre", query = "SELECT e FROM Equipos e WHERE e.nombre = :nombre")})
public class Equipos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idEquipo")
private Integer idEquipo;
#Basic(optional = false)
#Column(name = "nombre")
private String nombre;
#JoinColumn(name = "idSexo", referencedColumnName = "idSexo")
#ManyToOne(optional = false)
private Sexos idSexo;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idEquipo")
private Collection<Jugadores> jugadoresCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "equipos")
private Collection<EquiposPorCampeonato> equiposPorCampeonatoCollection;
public Equipos() {
}
public Equipos(Integer idEquipo) {
this.idEquipo = idEquipo;
}
public Equipos(Integer idEquipo, String nombre) {
this.idEquipo = idEquipo;
this.nombre = nombre;
}
public Integer getIdEquipo() {
return idEquipo;
}
public void setIdEquipo(Integer idEquipo) {
this.idEquipo = idEquipo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Sexos getIdSexo() {
return idSexo;
}
public void setIdSexo(Sexos idSexo) {
this.idSexo = idSexo;
}
public Collection<Jugadores> getJugadoresCollection() {
return jugadoresCollection;
}
public void setJugadoresCollection(Collection<Jugadores> jugadoresCollection) {
this.jugadoresCollection = jugadoresCollection;
}
public Collection<EquiposPorCampeonato> getEquiposPorCampeonatoCollection() {
return equiposPorCampeonatoCollection;
}
public void setEquiposPorCampeonatoCollection(Collection<EquiposPorCampeonato> equiposPorCampeonatoCollection) {
this.equiposPorCampeonatoCollection = equiposPorCampeonatoCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idEquipo != null ? idEquipo.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 Equipos)) {
return false;
}
Equipos other = (Equipos) object;
if ((this.idEquipo == null && other.idEquipo != null) || (this.idEquipo != null && !this.idEquipo.equals(other.idEquipo))) {
return false;
}
return true;
}
#Override
public String toString() {
return "" + nombre + "";
}
}
Table scripts available if needed
Thank you very much.
Yes its spanish please bear with me!
Equipos == Teams;
Partidos == Matches;
Campeonatos == Championships;
This exception is related to the view, not to the model. The exception is telling that you've set a component ID with the value partidosPK.idEquipo like as follows:
<h:someComponent id="partidosPK.idEquipo">
However, this ID is illegal as per the rules. It contains a dot .. Remove it or replace by _ or -. The rules are the same as for the HTML/CSS identifiers.
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit.

Resources