JPQL subquery with multiple value return - jpql

I'm a little confused to convert my SQL to criteria query which needs me to get last actual status.
select r.id, s.CODE, rs.CREATE_DATE
from request r
join request_status rs on r.id = rs.request_id
join status s on rs.STATUS_ID = s.ID
join (SELECT rss.REQUEST_ID, max(rss.CREATE_DATE) lastDate
FROM REQUEST_STATUS rss GROUP BY rss.REQUEST_ID) lastStatus ON r.ID = lastStatus.REQUEST_ID AND rs.CREATE_DATE = lastStatus.lastDate;
#Entity
public class Request {
#Id
private UUID id;
#OneToMany(mappedBy = "request", fetch = LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<RequestStatus> requestStatuses = new ArrayList<>();
}
#Entity
public class RequestStatus {
#Id
private UUID id;
#ManyToOne(fetch = LAZY, optional = false)
private Request request;
#ManyToOne(fetch = LAZY, optional = false)
private Status status;
private OffsetDateTime createDate;
}
#Data
#AllArgsConstructor
public class LastRow {
private UUID id;
private OffsetDateTime date;
}
So, I do like:
public void run() {
var builder = entityManager.getCriteriaBuilder();
var query = builder.createQuery(RequestAsCreatedEvent.class);
var root = query.from(Request.class);
query.select(builder.construct(RequestAsCreatedEvent.class,
root.get(Request_.id),
root.get(Request_.template).get(Template_.id)));
var subQuery = query.subquery(LastRow.class);
subQuery.correlate(root);
var subRoot = subQuery.from(RequestStatus.class);
subQuery.groupBy(subRoot.get(RequestStatus_.id));
subQuery.select(builder.construct(LastRow.class, subRoot.get(RequestStatus_.request).get(Request_.id),
builder.greatest(subRoot.get(RequestStatus_.createDate))));
entityManager.createQuery(query).getResultList();
}
And I can't do that because subQuery.select expect Expression, but I need to select multiple values, and I try to do it like root query via object constructor (but it return CompoundSelection)

Related

hazelcast not equals predicate searching a collection attribute

I am using a hazelcast map to store an object very similar to the following:
#Entity
#Table(name = "organization")
public class Organization
{
public static final String MAP_NAME = "organizations";
#Id
#Column(name = "organizationId", unique = true, nullable = false, columnDefinition = "VARCHAR(36)")
protected String organizationId = UUID.randomUUID().toString();
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "organizationId")
private Set<RecordKeeperConfig> recordKeeperConfigs;
}
And RecordKeeperConfig is defined like:
#Entity
#Table(name = "recordKeeperConfig")
public class RecordKeeperConfig
{
public static final String MAP_NAME = "recordKeeperConfig";
#Id
#Column(name = "recordKeeperConfigId", unique = true, nullable = false, columnDefinition = "VARCHAR(36)")
protected String recordKeeperConfigId = UUID.randomUUID().toString();
#Column(name = "organizationId", columnDefinition = "VARCHAR(36)")
protected String organizationId;
#Enumerated(EnumType.STRING)
#Column(name = "type", length = 8)
protected RecordKeeperType type;
}
Ultimately I want to get back a Set of all of the Organization objects where there is at least one RecordKeeperConfig. I tried using Predicate.notEqual("recordKeeperConfigs", null) but it produces the following exception:
java.lang.IllegalArgumentException: Cannot use NotEqualPredicate predicate with an array or a collection attribute
Try implementing the logical operation as a transient method in your entity class. Then instead of the collection, construct the Hazelcast predicate on that:
Method:
#javax.persistence.Transient
public boolean isRecordKeeperConfigsNotEmpty() {
return getRecordKeeperConfigs() != null && !getRecordKeeperConfigs().isEmpty();
}
Predicate:
EntryObject e = new PredicateBuilder().getEntryObject();
PredicateBuilder predicate = e.is("recordKeeperConfigsNotEmpty");
Collection<Organization> filteredOrganizations = organizationMap.values(predicate);

Managed Bean injection failure?

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

PrimeFaces Chart From Database

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.

jpql Join query

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

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

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

Resources