I already have a CRUD webApp (JSF+EJB+JPA) and I'm trying to develop a chartBean class so I can use it in the View layer.
The data to be rendered (through Primefaces-4 BarChart) should be read from a database.
In the Chart, I have 2 chartSeries to be displayed:
chartSeries1: the employeeGoal -> the 'valor' float column mapped in the Orc entity class below;
chartSeries2: the employeeAccomplished -> the 'Realizado' integer column mapped in the hr_capacit30h entity class below.
The X-Axis should display the Hours (based on the 'chartSeries2' values above).
The Y-axis should display the employeeName (the 'nome' string field in the hr_capacit30h entity class below).
Does anyone knows how to develop the createCartesianChartModel() method below to be used in a jsf page?
The ChartBean class:
//imports ommited
#ManagedBean
#RequestScoped
public class hrCapacitChart {
private Map<Integer, Map<String, Number>> HrCapacitFuncis = new HashMap<Integer, Map<String, Number>>();
private double totalHoras;
private CartesianChartModel cartesianChartModel;
#EJB
private HrCapacit30hFacade hcf;
public hrCapacitChart() {
}
#PostConstruct
private void initialize() {
cartesianChartModel = new CartesianChartModel();
createCartesianChartModel();
}
public CartesianChartModel getCartesianChartModel() {
return cartesianChartModel;
}
private void createCartesianChartModel() {
List<HrCapacit30h> hrCapacit30h = hcf.findAll();
// THIS IS THE METHOD/(Managed Bean property) TO BE DEVELOPED
}
}
The HrCapacit30h entity class (related to chartSeries2 an Y-axis / see description above):
#Entity
#Table(name = "hr_capacit30h", catalog = "DIAGE", schema = "atb")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "HrCapacit30h.findAll", query = "SELECT h FROM HrCapacit30h h"),
#NamedQuery(name = "HrCapacit30h.findByMatricula", query = "SELECT h FROM HrCapacit30h h WHERE h.hrCapacit30hPK.matricula = :matricula"),
#NamedQuery(name = "HrCapacit30h.findByNome", query = "SELECT h FROM HrCapacit30h h WHERE h.nome = :nome"),
#NamedQuery(name = "HrCapacit30h.findByRealizado", query = "SELECT h FROM HrCapacit30h h WHERE h.realizado = :realizado"),
#NamedQuery(name = "HrCapacit30h.findByDtMov", query = "SELECT h FROM HrCapacit30h h WHERE h.hrCapacit30hPK.dtMov = :dtMov")})
public class HrCapacit30h implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected HrCapacit30hPK hrCapacit30hPK;
#Size(max = 100)
#Column(name = "Nome")
private String nome;
#Column(name = "Realizado")
private Integer realizado;
#JoinColumn(name = "codUOR", referencedColumnName = "cod_UOR")
#ManyToOne(optional = false)
private UpbDeps codUOR;
#JoinColumn(name = "status", referencedColumnName = "id")
#ManyToOne(optional = false)
private Status status;
#JoinColumn(name = "idOrc", referencedColumnName = "id")
#ManyToOne
private Orc idOrc;
#JoinColumn(name = "idDiv", referencedColumnName = "id")
#ManyToOne(optional = false)
private DivDeps idDiv;
public HrCapacit30h() {
}
//getters/setters/equals/hashCode ommited
}
The Entity Orc class (related to chartSeries1 / see description above)::
//imports ommited
#Entity
#Table(name = "orc", catalog = "DIAGE", schema = "atb")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Orc.findAll", query = "SELECT o FROM Orc o"),
#NamedQuery(name = "Orc.findById", query = "SELECT o FROM Orc o WHERE o.id = :id"),
#NamedQuery(name = "Orc.findByNomeItem", query = "SELECT o FROM Orc o WHERE o.nomeItem = :nomeItem"),
#NamedQuery(name = "Orc.findByDescItem", query = "SELECT o FROM Orc o WHERE o.descItem = :descItem"),
#NamedQuery(name = "Orc.findByValor", query = "SELECT o FROM Orc o WHERE o.valor = :valor"),
#NamedQuery(name = "Orc.findByDtRef", query = "SELECT o FROM Orc o WHERE o.dtRef = :dtRef")})
public class Orc implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 100)
#Column(name = "NomeItem")
private String nomeItem;
#Size(max = 255)
#Column(name = "DescItem")
private String descItem;
// #Max(value=?) #Min(value=?)//to enforce field validation to known decimal range values
#Column(name = "valor")
private Double valor;
#Column(name = "DtRef")
#Temporal(TemporalType.TIMESTAMP)
private Date dtRef;
#OneToMany(mappedBy = "idOrc")
private Collection<HrCapacit30h> hrCapacit30hCollection;
//getters/setters/equals/hashCode ommited
}
The EJB (an abstract facade):
//imports ommited
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] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
The hr_capacit30h EJB facade:
//imports ommited
#Stateless
public class HrCapacit30hFacade extends AbstractFacade<HrCapacit30h> {
#PersistenceContext(unitName = "atb-hrCapacit30PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public HrCapacit30hFacade() {
super(HrCapacit30h.class);
}
}
The Orc EJB facade:
//imports ommited
#Stateless
public class OrcFacade extends AbstractFacade<Orc> {
#PersistenceContext(unitName = "atb-hrCapacit30PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public OrcFacade() {
super(Orc.class);
}
}
Thanks in advance.
After a long way studying it:
/**
*
* #author jMarcel
*/
#ManagedBean
#RequestScoped
public class ChartBean {
public ChartBean() {
}
private final Map<Integer, Map<String, Number>> HorasRealizadasPorFunci = new HashMap<>();
private final Map<Integer, Map<String, Number>> HorasOrcadasPorFunci = new HashMap<>();
private CartesianChartModel cartesianChartModel;
#EJB
private OrcFacade of;
#PostConstruct
private void initialize() {
cartesianChartModel = new CartesianChartModel();
createCartesianChartModel();
}
private void createCartesianChartModel() {
List<Orc> orcado = of.findAll();
List<Integer> orcadoList = new ArrayList<>();
List<Integer> realizadoList = new ArrayList<>();
//rlz Series
for (Orc o : orcado) {
int horasRlz = 0;
for (HrCapacit30h r : o.getHrCapacit30hCollection()) {
horasRlz = r.getRealizado();
addOrUpdateRlz(r.getHrCapacit30hPK().getMatricula(), r.getNome(), horasRlz);
realizadoList.add(r.getHrCapacit30hPK().getMatricula());
}
}
//orc Series
for (Orc o : orcado) {
int horasOrc = 0;
for (HrCapacit30h r : o.getHrCapacit30hCollection()) {
horasOrc = r.getIdOrc().getValor().intValue();
addOrUpdateOrc(r.getHrCapacit30hPK().getMatricula(), r.getNome(), horasOrc);
orcadoList.add(r.getHrCapacit30hPK().getMatricula());
}
}
Map<Object, Number> orcMap = new HashMap<>();
Map<Object, Number> rlzMap = new HashMap<>();
for (Integer i : realizadoList) {
populateMap(rlzMap, HorasRealizadasPorFunci.get(i));
}
for (Integer i : orcadoList) {
populateMap(orcMap, HorasOrcadasPorFunci.get(i));
}
ChartSeries orcadoSeries = new ChartSeries("Orçado");
orcadoSeries.setData(orcMap);
ChartSeries realizadoSeries = new ChartSeries("Realizado");
realizadoSeries.setData(rlzMap);
cartesianChartModel.addSeries(orcadoSeries);
cartesianChartModel.addSeries(realizadoSeries);
}
private void addOrUpdateRlz(Integer matricula, String funci, Number horas) {
Map<String, Number> map = HorasRealizadasPorFunci.get(matricula);
if (map == null) {
map = new HashMap<>();
HorasRealizadasPorFunci.put(matricula, map);
}
Number n = map.get(funci);
if (n == null) {
map.put(funci.toUpperCase(), horas);
} else {
map.put(funci.toUpperCase(), horas.intValue());
}
}
private void addOrUpdateOrc(Integer matricula, String funci, Number horas) {
Map<String, Number> map = HorasOrcadasPorFunci.get(matricula);
if (map == null) {
map = new HashMap<>();
HorasOrcadasPorFunci.put(matricula, map);
}
Number n = map.get(funci);
if (n == null) {
map.put(funci.toUpperCase(), horas);
} else {
map.put(funci.toUpperCase(), horas.intValue());
}
}
private void populateMap(Map<Object, Number> map, Map<String, Number> data) {
if (data == null) {
return;
}
for (String key : data.keySet()) {
Number n = map.get((Object) key);
if (n == null) {
map.put((Object) key, data.get(key));
} else {
map.put((Object) key, n.intValue() + data.get(key).intValue());
}
}
}
public CartesianChartModel getCartesianChartModel() {
return cartesianChartModel;
}
public void setCartesianChartModel(CartesianChartModel cartesianChartModel) {
this.cartesianChartModel = cartesianChartModel;
}
}
You need to create a ChartSeries (for category chart) or LineChartSeries (for linear chart) object, fill it with your values, and finally add the object to the Cartesian Model. That's all.
Have a look at the official example
private void createCategoryModel() { // category chart
categoryModel = new CartesianChartModel();
ChartSeries boys = new ChartSeries();
boys.setLabel("Boys");
boys.set("2004", 120);
boys.set("2005", 100);
boys.set("2006", 44);
boys.set("2007", 150);
boys.set("2008", 25);
ChartSeries girls = new ChartSeries();
girls.setLabel("Girls");
girls.set("2004", 52);
girls.set("2005", 60);
girls.set("2006", 110);
girls.set("2007", 135);
girls.set("2008", 120);
categoryModel.addSeries(boys);
categoryModel.addSeries(girls);
}
private void createLinearModel() { //linear chart
linearModel = new CartesianChartModel();
LineChartSeries series1 = new LineChartSeries();
series1.setLabel("Series 1");
series1.set(1, 2);
series1.set(2, 1);
series1.set(3, 3);
series1.set(4, 6);
series1.set(5, 8);
LineChartSeries series2 = new LineChartSeries();
series2.setLabel("Series 2");
series2.setMarkerStyle("diamond");
series2.set(1, 6);
series2.set(2, 3);
series2.set(3, 2);
series2.set(4, 7);
series2.set(5, 9);
linearModel.addSeries(series1);
linearModel.addSeries(series2);
}
Edit :
Create and initialize two ChartSeries objects. Then fill them while iterating through the list. Something like this should work :
ChartSeries a = new ChartSeries();
ChartSeries b = new ChartSeries();
HrCapacit30h tmp = null;
for(int i =0; i<hrCapacit30h.size();i++){
tmp=hrCapacit30h.get(i);
a.set(tmp.getRealizado(), tmp.getNome());
b.set(tmp.getOcr().getValor(), tmp.getNome());
}
cartesianChartModel.addSeries(a);
cartesianChartModel.addSeries(b);
Hope it helps.
Related
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.
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? ]
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
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.
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.