Primefaces grouping issue - primefaces

I am facing an issue while tryin to group data with primefaces subtale component. My columns are grouped but the first result still the same row as shown in the screen shot below :
Normaly I should have other apart from AIR. But this is the result I have got.
Can some one help me understand what happening. I have followed the PrimeFaces show case and develop classes to produce this subtable:
This is the managed bean:
package tg.moov.imereport.mbean;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;
import tg.moov.imereport.service.DownStream;
import tg.moov.imereport.service.DownStreamTotal;
#Named
#Stateless
public class GroupedDataMBean {
#EJB private DownStreamMBean ds;
#EJB private DownStreamTotalMBean dst;
private Period period = new Period();
private List<GroupedDownStream> downStreams;
/**
* #return the period
*/
public Period getPeriod() {
return period;
}
/**
* #param period the period to set
*/
public void setPeriod(Period period) {
this.period = period;
}
public GroupedDataMBean() {
}
/**
*
*/
public void populateDownStreams() {
downStreams = new ArrayList<GroupedDownStream>();
for (DownStream d : ds.getDownStreamsService()) {
GroupedDownStream gds = new GroupedDownStream();
gds.setDownStream(d.getIDDownStream());
dst.setPeriod(period);
for(DownStreamTotal dt : dst.displayGroupedDataByDownStream(d)) {
gds.getDownStreamsDetails().add(dt);
}
downStreams.add(gds);
}
}
/**
*
* #return a List of GroupedDownStream
*/
public List<GroupedDownStream> getGroupedDownStreams() {
return downStreams;
}
}
this is the Master class :
package tg.moov.imereport.mbean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import tg.moov.imereport.service.DownStreamTotal;
public class GroupedDownStream implements Serializable {
private String downStream;
private List<DownStreamTotal> downStreamsDetails;
/**
* #return the downStream
*/
public String getDownStream() {
return downStream;
}
/**
* #param downStream the downStream to set
*/
public void setDownStream(String downStream) {
this.downStream = downStream;
}
/**
* #return the downStreamsDetails
*/
public List<DownStreamTotal> getDownStreamsDetails() {
return downStreamsDetails;
}
/**
* #param downStreamsDetails the downStreamsDetails to set
*/
public void setDownStreamsDetails(List<DownStreamTotal> downStreamsDetails) {
this.downStreamsDetails = downStreamsDetails;
}
public GroupedDownStream() {
downStreamsDetails = new ArrayList<DownStreamTotal>();
}
}
The detail to display :
package tg.moov.imereport.dao;
import java.io.Serializable;
import java.util.Date;
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.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "DownStreamTotal")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "DownStreamTotal.findAll", query = "SELECT d FROM DownStreamTotal d"),
#NamedQuery(name = "DownStreamTotal.findByDownStream", query = "SELECT d FROM DownStreamTotal d WHERE d.downStream = :downStream"),
#NamedQuery(name = "DownStreamTotal.findByNode", query = "SELECT d FROM DownStreamTotal d WHERE d.node = :node"),
#NamedQuery(name = "DownStreamTotal.findByTotalFiles", query = "SELECT d FROM DownStreamTotal d WHERE d.totalFiles = :totalFiles"),
#NamedQuery(name = "DownStreamTotal.findByMinDate", query = "SELECT d FROM DownStreamTotal d WHERE d.minDate = :minDate"),
#NamedQuery(name = "DownStreamTotal.findByMaxDate", query = "SELECT d FROM DownStreamTotal d WHERE d.maxDate = :maxDate")})
public class DownStreamTotal implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "DownStream")
private String downStream;
#Size(max = 15)
#Column(name = "Node")
private String node;
#Column(name = "TotalFiles")
private Integer totalFiles;
#Column(name = "MinDate")
#Temporal(TemporalType.DATE)
private Date minDate;
#Column(name = "MaxDate")
#Temporal(TemporalType.DATE)
private Date maxDate;
public DownStreamTotal() {
}
public DownStreamTotal(String downStream) {
this.downStream = downStream;
}
public String getDownStream() {
return downStream;
}
public void setDownStream(String downStream) {
this.downStream = downStream;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public Integer getTotalFiles() {
return totalFiles;
}
public void setTotalFiles(Integer totalFiles) {
this.totalFiles = totalFiles;
}
public Date getMinDate() {
return minDate;
}
public void setMinDate(Date minDate) {
this.minDate = minDate;
}
public Date getMaxDate() {
return maxDate;
}
public void setMaxDate(Date maxDate) {
this.maxDate = maxDate;
}
#Override
public int hashCode() {
int hash = 0;
hash += (downStream != null ? downStream.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 DownStreamTotal)) {
return false;
}
DownStreamTotal other = (DownStreamTotal) object;
if ((this.downStream == null && other.downStream != null) || (this.downStream != null && !this.downStream.equals(other.downStream))) {
return false;
}
return true;
}
#Override
public String toString() {
return "tg.moov.imereport.dao.DownStreamTotal[ downStream=" + downStream + " ]";
}
}
The primefaces code :
<p:commandButton action="#{groupedDataMBean.populateDownStreams}" value="search" ajax="false" update="downStreamTable" />
<p:dataTable id="downStreamTable" var="dwnStr" value="#{groupedDataMBean.groupedDownStreams}">
<f:facet name="header">
ImE Distribution Report
</f:facet>
<p:columnGroup type="header">
<p:row>
<p:column headerText="DownStream" />
<p:column headerText="#Files" />
<p:column headerText="MinDate" />
<p:column headerText="MaxDate" />
</p:row>
</p:columnGroup>
<p:subTable var="details" value="#{dwnStr.downStreamsDetails}">
<f:facet name="header">
#{dwnStr.downStream}
</f:facet>
<p:column>
#{details.node}
</p:column>
<p:column>
#{details.totalFiles}
</p:column>
<p:column>
#{details.minDate}
</p:column>
<p:column>
#{details.maxDate}
</p:column>
<p:columnGroup type="footer">
</p:columnGroup>
</p:subTable>
</p:dataTable>
Thank you in advance!

I found, something here about it. It is a Primefaces bug. They recommand to use nested datable instead.

Related

Open details of a single row in a datatable in a new page

I have a datatable from database and I would like details of one of the rows appear in a new table when I click on the "OPEN" button as in the screenshot below.
When I click on the OPEN button I get "No records found " as in the next screenshot below
Here is part of the index.xhtml
//
APP WEB
<p:ajax event="rowEdit" listener="#{transaction.onRowEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{transaction.onRowCancel}" update=":form1:messages" />
<p:column headerText="Reference">
<p:commandLink value="#{c.reference}" action="/faces/global/SingleTx.xhtml" target="_blank" >
<f:setPropertyActionListener target="#{transaction.showSelectedTx(reference)}" value="#{c}" />
</p:commandLink>
</p:column>
<p:column headerText="Rartner">
#{c.pname}
</p:column>
<p:column headerText="Status">
#{c.fk_status}
</p:column>
<p:column headerText="Sender">
#{c.sendername}
</p:column>
<p:column headerText="Beneficiary">
#{c.beneficiaryname}
</p:column>
<p:column headerText="Amounts">
#{c.beneficiary_currency} #{c.beneficiary_amount}
</p:column>
<p:column headerText="Action">
<p:commandButton style="float:right" value="Print" >
<p:confirm header="#{cd.reference}" message="Are you sure?" icon="ui-icon-alert" />
<p:button value="Open" href="/faces/global/SingleTx.xhtml" target="_self" />
</p:commandButton>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:dialog modal="true" width="800px" height="400px" widgetVar="singletx"
id="dialog">
Name :#{transaction.showSelectedTx(reference)}
</p:dialog>
</h:form>
Here is the backing bean:
package com.mycompany.data;
/**
*
* #author bryan
*/
import conn.DBConnector;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "transaction")
#SessionScoped
public class TransactionBean implements Serializable {
//added
private static final long serialVersionUID = 1L;
public String reference;
public String fk_status;
public String sendername;
public String beneficiaryname;
public String beneficiary_currency;
public double beneficiary_amount;
public String pname;
Transaction user;
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getFk_status() {
return fk_status;
}
public void setFk_status(String fk_status) {
this.fk_status = fk_status;
}
public String getSendername() {
return sendername;
}
public void setSendername(String sendername) {
this.sendername = sendername;
}
public String getBeneficiaryname() {
return beneficiaryname;
}
public void setBeneficiaryname(String beneficiaryname) {
this.beneficiaryname = beneficiaryname;
}
public String getBeneficiary_currency() {
return beneficiary_currency;
}
public void setBeneficiary_currency(String beneficiary_currency) {
this.beneficiary_currency = beneficiary_currency;
}
public double getBeneficiary_amount() {
return beneficiary_amount;
}
public void setBeneficiary_amount(double beneficiary_amount) {
this.beneficiary_amount = beneficiary_amount;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
//resource injection
#Resource(name = "jdbc/primefaces")
//connect to DB and get customer list
public List<Transaction> getTransactionList() throws SQLException, ClassNotFoundException {
Connection con = null;
con = DBConnector.getDBConnection();
if (con == null) {
throw new SQLException("Can't get database connection");
}
PreparedStatement ps
= con.prepareStatement(
"select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id");
//get customer data from database
ResultSet result = ps.executeQuery();
List<Transaction> list = new ArrayList<Transaction>();
while (result.next()) {
Transaction cust = new Transaction();
cust.setReference(result.getString("reference"));
cust.setFk_status(result.getString("name"));
cust.setSendername(result.getString("sendername"));
cust.setBeneficiaryname(result.getString("beneficiaryname"));
cust.setBeneficiary_currency(result.getString("beneficiary_currency"));
cust.setBeneficiary_amount(result.getDouble("beneficiary_amount"));
cust.setPname(result.getString("pname"));
//store all data into a List
list.add(cust);
}
return list;
//added
}
//view single transaction
private List<Transaction> selectSingleTx;
public Transaction getUser() {
return user;
}
public void setUser(Transaction user) {
this.user = user;
}
public List<Transaction> getSelectSingleTx() {
return selectSingleTx;
}
public void setSelectSingleTx(List<Transaction> selectSingleTx) {
this.selectSingleTx = selectSingleTx;
}
public void showSelectedTx(String reference){
Connection con=DBConnector.getDBConnection();
if(con==null){
System.out.println("No db connection");
}
String ref=getReference();
try {
String q="select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id where tx.reference="+ref+"";
PreparedStatement ps=null;
ResultSet rs=null;
ps.setString(1, reference);
rs=ps.executeQuery();
display(rs);
} catch (Exception e) {
}
}
public void selectTx(String reference){
showSelectedTx(reference);
}
// to be implemented later
private static void display(ResultSet myRs) throws SQLException {
while (myRs.next()) {
String sendername = myRs.getString("sendername");
String beneficiaryname = myRs.getString("beneficiaryname");
//double salary = myRs.getDouble("salary");
String department = myRs.getString("department");
System.out.printf("%s, %s \n", sendername, beneficiaryname);
}
}
}
//
As per the Reference link, you need to include the value of c.reference in the link
value="#{c.reference}"
See JSF ViewParam from CommandButton
or
How to pass a parameter along with h:commandButton

Primefaces 6 & Content Flow Error

I get java.io.IOException: java.lang.NullPointerException: Argument Error: Parameter url is null.
xhtml file:
<p:dataTable var="vehicleTransactionList" value="#{viewCompanyManagedBean.vehicleTransactionList}">
<p:column headerText="#{messages.saptrn}">
<h:outputText value="#{vehicleTransactionList.vehicleTransactionId}" />
</p:column>
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>
</p:contentFlow>
</p:column>
</p:dataTable>
The error is on the 2nd column #{newimage.imageLocations}
Managed Bean:
package com.company.beans;
import com.company.entities.Company;
import com.company.entities.Scale;
import com.company.entities.ScaleMeasurement;
import com.company.entities.VehicleTransaction;
import com.company.services.db.ScaleMeasurementService;
import com.company.services.db.ScaleService;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.primefaces.event.SelectEvent;
import sunw.io.Serializable;
#SuppressWarnings("deprecation")
#ManagedBean
#ViewScoped
public class ViewCompanyManagedBean implements Serializable {
static Logger webRecySys = null;
static {
webRecySys = Logger.getLogger("com.company.webRecySys");
}
public ViewCompanyManagedBean() {
}
#PostConstruct
public void populateCompanyData() {
prepareData(new Date());
images = new ArrayList<String>();
for (int i = 1; i <= 7; i++) {
images.add("file_" + i + ".jpg");
}
}
#PostConstruct
public void onDateSelect(SelectEvent event) throws UnknownHostException {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String date = format.format(event.getObject());
try {
Date selectedDate = format.parse(date);
prepareData(selectedDate);
} catch (ParseException e) {
e.printStackTrace();
}
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected",format.format(event.getObject())));
}
private void prepareData(Date forData) {
ScaleService ss = new ScaleService();
ScaleMeasurementService sms = new ScaleMeasurementService();
Scale right = ss.find(getRightScale());
Scale left = ss.find(getLeftScale());
this.measurements = sms.getMeasurementForScale(right,forData);
this.measurements.addAll(sms.getMeasurementForScale(left,forData));
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
this.fileName = "Shredder_Measurements_"+ sdf.format(forData);
for ( ScaleMeasurement s : measurements ) {
if ( s.getScale().getScaleId().equalsIgnoreCase(rightScale) ) {
this.rightScaleMeasurementSum += s.getMeasurement();
}
if ( s.getScale().getScaleId().equalsIgnoreCase(leftScale) ) {
this.leftScaleMeasurementSum += s.getMeasurement();
}
}
vehicleTransactionList = getVehicleTransactionList( sdf.format(forData) , (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest() );
}
private ArrayList<VehicleTransaction> getVehicleTransactionList(String fileDateFormat,HttpServletRequest request) {
ResourceBundle resourceb = ResourceBundle.getBundle("com.company.messages.image");
String imgRootPath = resourceb.getString("imagerootpath");
ArrayList<VehicleTransaction> images = new ArrayList<VehicleTransaction>();
String name = request.getLocalName();
if ( name != null ) {
if ( name.startsWith("0") ) {
name = "localhost";
}
}
else {
name = "localhost";
}
Scale scale = new ScaleService().find("01");
Company c = new ScaleService().getCompanyFromScale(scale);
String companyName = c.getCompanyName().trim().replace(" ", "_");
String URL = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/";
ArrayList<String> picUrls = new ArrayList<String>();
Document doc;
try {
doc = Jsoup.connect(URL).get();
for (Element file : doc.select("a")) {
String urlPathToFile = file.attr("href");
String fileName = file.text();
if ( urlPathToFile.endsWith(".jpg") && fileName.endsWith(".jpg") ) {
String picUrl = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/"+fileName;
picUrls.add(picUrl);
}
}
} catch (IOException e) {
webRecySys.logp(Level.WARNING, this.getClass().getCanonicalName() , "getAllImagesList", "Cannot get list of Images: "+e.getMessage() );
}
ArrayList<String> vehicleTransactionIdList = getVehicleTransactionIds(picUrls);
for ( String vehicleTransactionId : vehicleTransactionIdList) {
ArrayList<String> imagesForTransaction = getVehicleTransaction(vehicleTransactionId,picUrls);
VehicleTransaction s = new VehicleTransaction(imagesForTransaction, vehicleTransactionId);
images.add(s);
}
return images;
}
private ArrayList<String> getVehicleTransaction(String vehicleTransactionId,ArrayList<String> picUrls) {
ArrayList<String> imagesForTransaction = new ArrayList<String>();
for (String url : picUrls) {
if ( url.contains(vehicleTransactionId)) {
imagesForTransaction.add(url);
}
}
return imagesForTransaction;
}
private ArrayList<String> getVehicleTransactionIds(ArrayList<String> picUrls) {
ArrayList<String> vehicleTransactionIds = new ArrayList<String>();
for ( String pic : picUrls ) {
String vehicleTransactionId = pic.substring(pic.lastIndexOf("/")+1);
vehicleTransactionId = vehicleTransactionId.substring(0,vehicleTransactionId.indexOf("_"));
if ( !existsInArl(vehicleTransactionId,vehicleTransactionIds) ) {
vehicleTransactionIds.add(vehicleTransactionId);
}
}
return vehicleTransactionIds;
}
private boolean existsInArl (String s , ArrayList<String> arl) {
boolean exists = false;
for ( String c : arl ) {
if ( c.equalsIgnoreCase(s) ) {
exists = true;
}
}
return exists;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<ScaleMeasurement> getMeasurements() {
return measurements;
}
public void setMeasurements(List<ScaleMeasurement> measurements) {
this.measurements = measurements;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getRightScale() {
return rightScale;
}
public void setRightScale(String rightScale) {
this.rightScale = rightScale;
}
public String getLeftScale() {
return leftScale;
}
public void setLeftScale(String leftScale) {
this.leftScale = leftScale;
}
public int getRightScaleMeasurementSum() {
return rightScaleMeasurementSum;
}
public void setRightScaleMeasurementSum(int rightScaleMeasurementSum) {
this.rightScaleMeasurementSum = rightScaleMeasurementSum;
}
public int getLeftScaleMeasurementSum() {
return leftScaleMeasurementSum;
}
public void setLeftScaleMeasurementSum(int leftScaleMeasurementSum) {
this.leftScaleMeasurementSum = leftScaleMeasurementSum;
}
public ArrayList<VehicleTransaction> getVehicleTransactionList() {
return vehicleTransactionList;
}
public void setVehicleTransactionList(
ArrayList<VehicleTransaction> vehicleTransactionList) {
this.vehicleTransactionList = vehicleTransactionList;
}
// Used for Calendar
private Date date;
// Used for Shredder Measurements
private List<ScaleMeasurement> measurements = new ArrayList<ScaleMeasurement>();
private String fileName;
private String rightScale = "02";
private String leftScale = "03";
private int rightScaleMeasurementSum;
private int leftScaleMeasurementSum;
// Used for Pictures
private List<String> images;
private ArrayList<VehicleTransaction> vehicleTransactionList = new ArrayList<VehicleTransaction>();
private static final long serialVersionUID = 7449888248791054139L;
}
VehicleTransaction Pojo:
package com.company.entities;
import java.util.ArrayList;
public class VehicleTransaction {
public VehicleTransaction() {
}
public VehicleTransaction(ArrayList<String> imageLocations, String vehicleTransactionId) {
super();
this.imageLocations = imageLocations;
this.vehicleTransactionId = vehicleTransactionId;
}
public ArrayList<String> getImageLocations() {
return imageLocations;
}
public void setImageLocations(ArrayList<String> imageLocations) {
this.imageLocations = imageLocations;
}
public String getVehicleTransactionId() {
return vehicleTransactionId;
}
public void setVehicleTransactionId(String vehicleTransactionId) {
this.vehicleTransactionId = vehicleTransactionId;
}
private ArrayList<String> imageLocations;
private String vehicleTransactionId;
}
What's my mistake?
resolved - the right xhtml code is:
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{vehicleTransactionList.imageLocations}" var="images">
<p:graphicImage value="#{images}" styleClass="content" />
<div class="caption">#{images}</div>
</p:contentFlow>
</p:column>
Whereas the wrong code was:
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>

How to fix "Coult not find Id property. Be sure the accessor method name matches the veriable name" error

I creating "New JPA Controller Classes from Entity Classes" when I press the "FINISH" button and then I get the following error.
Users.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.mavenproject1.exceptions.exceptions.exceptions;
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.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;
/**
*
* #author OZGUR-PC
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findById", query = "SELECT u FROM Users u WHERE u.id = :id"),
#NamedQuery(name = "Users.findByUserName", query = "SELECT u FROM Users u WHERE u.userName = :userName")})
public class Users 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 = 50)
#Column(name = "user_name")
private String userName;
public Users() {
}
public Users(Integer id) {
this.id = id;
}
public Users(Integer id, String userName) {
this.id = id;
this.userName = userName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#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 Users)) {
return false;
}
Users other = (Users) 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.mycompany.mavenproject1.exceptions.exceptions.exceptions.Users[ id=" + id + " ]";
}
}
I need ideas on how I can solve it. Thank you in advance for your help.
Make sure you have declared an identifier for your entity. For example let's say there is an entity called Student with identifier as studentId and property name then the entity should be like this, it should have setter and getter methods for your fields:
#Entity
public class Student {
#Id
#GeneratedValue
private int studentId;
private String name;
public String getName() {
return name;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public void setName(String name) {
this.name = name;
}
}

TomEE and MySql - query don't returns any results

I am using TomeEE + MySql and i have problem because function createNamedQuery don't returns any results. I thought that problem is with my
entityManager but i checked in debugMode and is injected.
This is my code:
User Entity:
package pl.gsite.db.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;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.loginAndPassword", query = "SELECT u FROM User u WHERE u.login = :login and u.password = :password"),
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByLogin", query = "SELECT u FROM User u WHERE u.login = :login"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 100)
#Column(name = "login")
private String login;
#Size(max = 100)
#Column(name = "password")
private String password;
public User() {
}
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#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 User)) {
return false;
}
User other = (User) 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 "pl.gsite.db.model.User[ id=" + id + " ]";
}
}
My ManagedBean:
package pl.gsite.bean.request;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import pl.gsite.bean.session.LoggedUserBean;
import pl.gsite.db.model.User;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
#Named(value = "loginRequest")
#RequestScoped
public class LoginRequest {
#PersistenceContext(unitName = "gsitePU")
private EntityManager em;
#Inject
private LoggedUserBean loggedUserBean;
private String login;
private String password;
public LoginRequest() {
}
public String authentication() {
try {
List<User> uList = new ArrayList<User>();
TypedQuery qq = em.createNamedQuery("User.findAll", User.class);
uList = qq.getResultList(); // <-- returns empty list
TypedQuery<User> query = em.createNamedQuery("User.loginAndPassword", User.class).setParameter("login", login).setParameter("password", password);
User u = query.getSingleResult(); // <-- throws an NoResultException
this.loggedUserBean.setLoggedUser(u);
}
catch(NoResultException e) {
e.printStackTrace();
}
return "index";
}
/**
* #return the login
*/
public String getLogin() {
return login;
}
/**
* #param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
persistance.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="gsitePU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>gsite_mysql</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(foreignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
I had the same issue. I changed the jpa persistence from openJPA to eclipseLink. The problem resolved.

How to increment primary key without check AUTOINCREMENT in MySQL

How to increment primary key without check AUTOINCREMENT in MySQL?
My Example:
Tax.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package newpackage;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.*;
import javax.transaction.UserTransaction;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author gile
*/
#Entity
#Table(name = "tax", catalog = "invoicedb", schema = "")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tax.findAll", query = "SELECT t FROM Tax t"),
#NamedQuery(name = "Tax.findByIdtax", query = "SELECT t FROM Tax t WHERE t.idtax = :idtax"),
#NamedQuery(name = "Tax.findByValue", query = "SELECT t FROM Tax t WHERE t.value = :value"),
**#NamedQuery(name = "Tax.findMaxID", query = "SELECT MAX (t.idtax) from Tax t")})** // I write this query to find max value of primary key. how to find max ?
public class Tax implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "idtax")
private Integer idtax;
#Basic(optional = false)
#NotNull
#Column(name = "value")
private BigDecimal value;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "taxid")
private List<Invoicedetails> invoicedetailsList;
public Tax() {
}
public Tax(Integer idtax) {
this.idtax = idtax;
}
public Tax(Integer idtax, BigDecimal value) {
this.idtax = idtax;
this.value = value;
}
public Integer getIdtax() {
return idtax;
}
public void setIdtax(Integer idtax) {
this.idtax = idtax;
}
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
#XmlTransient
public List<Invoicedetails> getInvoicedetailsList() {
return invoicedetailsList;
}
public void setInvoicedetailsList(List<Invoicedetails> invoicedetailsList) {
this.invoicedetailsList = invoicedetailsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idtax != null ? idtax.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 Tax)) {
return false;
}
Tax other = (Tax) object;
if ((this.idtax == null && other.idtax != null) || (this.idtax != null && !this.idtax.equals(other.idtax))) {
return false;
}
return true;
}
#Override
public String toString() {
return String.format("%.2f %%",value);
}
#Transient
private String taxvalueString;
public String getTaxvalueString() {
return String.format(" %.2f %%",value);
}
public void setTaxvalueString(String taxvalueString) {
this.taxvalueString = taxvalueString;
}
}
You can add a method in Tax Class with PrePersit annotation for creating PK (idtax)
like
#PrePersist
private void generateID() {
// Read existing Tax record, finde new id and set pk here.
}