JPQL joining two tables and adding parameter generates eclipseLink error - jpa

So .. I have two tables Utilisateur and ReponsesTickets ( there's no trouble inserting selecting updating deleting from each table by itself) to make a join between these two tables i had to create a new Entity here's its code.
package projet.helpdesk.beans;
import java.sql.Timestamp;
//TEXTE - DATE_POST - NOM - PRENOM - AGENCE - POSTE - DEPARTEMENT - ID_EMPLOYE
public class Jointure1 {
private String texte;
private String nom;
private String prenom;
private String Agence;
private String poste;
private String departement;
private int id_employe;
private Timestamp date_post;
public String getTexte() {
return texte;
}
public void setTexte(String texte) {
this.texte = texte;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getAgence() {
return Agence;
}
public void setAgence(String agence) {
Agence = agence;
}
public String getPoste() {
return poste;
}
public void setPoste(String poste) {
this.poste = poste;
}
public String getDepartement() {
return departement;
}
public void setDepartement(String departement) {
this.departement = departement;
}
public int getId_employe() {
return id_employe;
}
public void setId_employe(int id_employe) {
this.id_employe = id_employe;
}
public Timestamp getDate_post() {
return date_post;
}
public void setDate_post(Timestamp date_post) {
this.date_post = date_post;
}
}
That's the SQL instruction i'm trying to translate into JPQL.
SELECT u.nom, u.prenom, r.texte, r.date_post
FROM Utilisateur u, ReponseTicket r
WHERE u.id_emp = r.id_employe
AND r.id_ticket = ? ( parameter here )
This is the method in the DAO pattern.
private static final String PARAM_TICKET = "id_ticket";
private static final String JPQL_SELECT ="SELECT u.nom, u.prenom, r.texte, r.date_post FROM Utilisateur u JOIN ReponseTicket r ON u.id_emp = r.id_employe AND r.id_ticket=:id_ticket";
//^ Above is the JPQL instruction, not sure if it's correct.
#PersistenceContext( unitName = "bdd_helpdesk_PU" )
private EntityManager em;
public List<Jointure1> trouverJointure( int id_ticket ) throws DAOException {
List<Jointure1> liste;
TypedQuery<Jointure1> query = em.createQuery(JPQL_SELECT, Jointure1.class);
query.setParameter(PARAM_TICKET, id_ticket);
try {
liste = (List<Jointure1>) query.getResultList();
} catch ( NoResultException e ) {
return null;
} catch(Exception e) {
throw new DAOException(e);
}
return liste;
}
Then goes the ResponseForm that communicates with the DAO method.
this method collects the ticket id from the request and passes it to the DAOmethod to insert it into the JPQL instruction.
public List<Jointure1> recupererJointure(HttpServletRequest request)
{
List<Jointure1> ljointure;
int id = getId_ticket(request);
if(id!=0){
ljointure = reponseDao.trouverJointure(id);
}else ljointure=null;
return ljointure;
}
Stacktrace:
Caused by: Exception [EclipseLink-6168] (Eclipse Persistence Services - 2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.QueryException
Exception Description: Query failed to prepare, unexpected error occurred: [java.lang.NullPointerException].
Internal Exception: java.lang.NullPointerException
Query: ReportQuery(referenceClass=Utilisateur jpql="SELECT u.nom, u.prenom, r.texte, r.date_post FROM Utilisateur u JOIN ReponseTicket r ON u.id_emp = r.id_employe AND r.id_ticket=:id_ticket")
I don't know about the null pointer exception, the parameter id_ticket is visible in the URL.
However i didn't add the new Entity in the persistence.xml
http://localhost:4040/monprojet2/reponsesticket?id_ticket=62
This is the servlet.
package projet.helpdesk.servlets;
#WebServlet(urlPatterns={"/reponsesticket"})
public class Reponsestickets extends HttpServlet {
#EJB
private TicketDao ticketDao;
#EJB
private ReponseTicketDao reponseDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CreationTicketForm ticketform = new CreationTicketForm(ticketDao);
Ticket ticket = ticketform.recupererTicket(request);
CreationReponseForm reponse = new CreationReponseForm(reponseDao);
List<Jointure1> listereponse = reponse.recupererJointure(request);
if(ticket==null)
{
response.sendRedirect("/connexion");
} else {
request.setAttribute("lreponse", listereponse);
request.setAttribute("ticket", ticket);
this.getServletContext().getRequestDispatcher("/WEB-INF/ReponsesTickets.jsp").forward(request, response);
}
}
}
EDIT:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Réponses ticket</title>
<meta http-equiv="Content-Type" content="text/html">
<link type="text/css" rel="stylesheet" href="inc/style.css" />
</head>
<body>
<p>Test---> <br>votre id:${masession.idemp}<br>
Type:${masession.type}<br>
</p>
<fieldset>
<legend>Réponses pour ticket id: ${ticket.id_ticket}</legend><br>
<p>Sujet:</p> ${ticket.sujet} <br>
<p>Description:</p> ${ticket.description}<br>
</fieldset>
<br>
<c:forEach items="${lreponse}" var="reponse">
<p>Nom: ${reponse.nom}</p>
<p>Prenom: ${reponse.prenom }</p>
<p>Réponse: ${reponse.texte }</p>
<p>Date: ${reponse.date_post }</p>
<br><br>
</c:forEach>
<br><br><br>
<fieldset>
<legend>Répondre:</legend>
<form method="post" action="creerreponse" enctype="application/x-www-form-urlencoded">
<textarea rows="5" cols="36" name="texte"></textarea>${erreurs['texte']}<br/>
<input type="hidden" name="id_employe" value="${masession.idemp}">
<input type="hidden" name="id_ticket" value="${ticket.id_ticket}">
<input type="hidden" name="type" value="${masession.type}">
<input type="submit" value="Valider"><br/>
</form>
<p></p>
</fieldset>
</body>
</html>
Stacktrace:
[2017-05-03T16:47:49.790+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-listener-1(4)] [timeMillis: 1493826469790] [levelValue: 900] [[
StandardWrapperValve[projet.helpdesk.servlets.Reponsestickets]: Servlet.service() for servlet projet.helpdesk.servlets.Reponsestickets threw exception
java.lang.NumberFormatException: For input string: "nom"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at javax.el.ArrayELResolver.toInteger(ArrayELResolver.java:378)
at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:198)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
at com.sun.el.parser.AstValue.getValue(AstValue.java:140)
at com.sun.el.parser.AstValue.getValue(AstValue.java:204)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at org.apache.jasper.runtime.PageContextImpl.evaluateExpression(PageContextImpl.java:1016)
at org.apache.jsp.WEB_002dINF.ReponsesTickets_jsp._jspx_meth_c_forEach_0(ReponsesTickets_jsp.java:143)
at org.apache.jsp.WEB_002dINF.ReponsesTickets_jsp._jspService(ReponsesTickets_jsp.java:85)

Related

How to get query parameters in JSTL instead of scriplets

I have been trying to display a table in JSP for which I am using this while loop code as given below, the problem is that it is difficult for me to convert my scriptlets into JSTL especially the rs.getInt("id") and I am using JSTL so that I can encode the URL together.
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/login";
String username = "root";
String password = "your-password";
String query = "select * from employeesloginaccount";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
%>
<tr>
<td><%=rs.getInt("id")%></td>
<td><%=rs.getString("first_name")%></td>
<td><%=rs.getString("last_name")%></td>
<td>
<c:url value ="${pageContext.request.contextPath}/downloadFileServlet" var = "myURL">
<c:param name = "id" value = "<%=rs.getInt(id)%>"/>
</c:url>
<form method="get"
action="<c:import url = "${myURL}"/>">
<input style="text-align: center" type="submit" value="Save">
</form>
</td>
</tr>
<%
}
I think it might be worth considering this answer from BalusC on the question, "How to avoid Java code in JSP files?"
The use of scriptlets (those <% %> things) in JSP is indeed
highly discouraged since the birth of taglibs (like JSTL) and
EL (Expression Language, those ${} things) over a decade ago.
The major disadvantages of scriptlets are:
Reusability: you can't reuse scriptlets.
Replaceability: you can't make scriptlets abstract.
OO-ability: you can't make use of inheritance/composition.
Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.
Testability: scriptlets are not unit-testable.
Maintainability: per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.
Your specific problem here is Maintainability.
What you should be doing is seperating the logic of your application so that you can have a high level of reusability/testability/debuggability/maintainability etc.. Let's start by creating a java class for your database connection, maybe something like this:
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/login";
conn = DriverManager.getConnection(url,"root","your-password");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
Then you can use this class whenever you want to connect to your database and do something from other classes, in the examples below we will create an object to handle your employee data and then use that to get information from your database:
public class EmployeeObject {
int id;
String firstname;
String lastname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
Now that we have this object class, let's say you have another class called Employees, and in this class you have a method which gets employee info from the employeesloginaccount table:
public class Employees {
public List<EmployeeObject> getEmployeeInfo(){
//this class will return a list of EmployeeObjects from the database.
ArrayList<EmployeeObject> employees = new ArrayList<EmployeeObject>();
//get connection from our DBConneciton class we created earlier
try(Connection conn= DBConnection.getConnection()){
PreparedStatement pst = conn.prepareStatement("select * from employeesloginaccount;");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
//for each result in database, create an EmployeeObject
EmployeeObject employee = new EmployeeObject();
int id = rs.getInt("id");
employee.setId(id);
String fname = rs.getString("first_name");
employee.setFirstname(fname);
String lname = rs.getString("last_name");
employee.setLastname(lname);
employees.add(employee); // add each EmployeeObject to the arrayList of EmployeeObject's
}
} catch (SQLException e) {
e.printStackTrace();
}
return employees; //return all the results
}
}
Then you create a Servlet which will get this information, let's make it easy and put our code in the doGet method of the servlet so that whenever we visit the URL for this Servlet we will call this code (in this case i called my Servlet Test, with url mapping /Test:
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Employees e = new Employees(); //instantiate the Employees class
List<EmployeeObject> employees = e.getEmployeeInfo(); //get employee info from database
request.setAttribute("employees", employees); //set this list of employees to the request so we can access it in our jsp
RequestDispatcher rd = request.getRequestDispatcher("example.jsp"); //change to whatever your jsp is that you want to view the information
rd.forward(request, response);
}
}
And finally in our jsp page where we can view this information:
<!DOCTYPE HTML>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<table style="width:100%;">
<thead>
<tr>
<td>id</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
</thead>
<tbody>
<!-- for each item in our employees list create a variable called "employee" -->
<c:forEach items="${employees}" var="employee">
<tr>
<td>${employee.id}</td>
<td>${employee.firstname}</td>
<td>${employee.lastname}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
Let me know if that helps you or if you have any questions. :)

SQL not invoked when SELECTing Entity with JPQL

I have a table FAQ ( Frequently asked questions )
Here's the Bean:
package projet.helpdesk.beans;
import javax.persistence.*;
#Entity
#Table(name="faq")
public class FAQ {
#Id
private int id_qr;
private int id_technicien;
private String question;
private String reponse;
public int getId_qr() {
return id_qr;
}
public void setId_qr(int id_qr) {
this.id_qr = id_qr;
}
public int getId_technicien() {
return id_technicien;
}
public void setId_technicien(int id_technicien) {
this.id_technicien = id_technicien;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
}
This is the DAO class:
The function public List<FAQ> chargerFAQ() is supposed to return a list of FAQ.
The JPQL query is: private static final String JPQL_SELECT_ALL = "SELECT f FROM FAQ f";
`package projet.helpdesk.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import projet.helpdesk.beans.FAQ;
#Stateless
public class FAQDao {
private static final String JPQL_SELECT_ALL = "SELECT f FROM FAQ f";
private static final String JPQL_SELECT_QR = "SELECT f FROM FAQ f WHERE id_qr=:id_qr";
private static final String PARAMETER = "id_qr";
#PersistenceContext( unitName = "bdd_helpdesk_PU" )
private EntityManager em;
public void creer( FAQ faq ) throws IllegalArgumentException, DAOException {
try {
em.persist(faq);
} catch ( Exception e ) {
throw new DAOException( e );
}
}
public List<FAQ> chargerFAQ() throws DAOException {
List<FAQ> listefaq;
Query query = em.createQuery(JPQL_SELECT_ALL);
try {
listefaq = (List<FAQ>) query.getResultList();
} catch ( NoResultException e ) {
return null;
} catch(Exception e) {
throw new DAOException(e);
}
return listefaq;
}
public FAQ trouverQR(int id_qr) throws DAOException{
FAQ qr;
Query query = em.createQuery(JPQL_SELECT_QR);
query.setParameter(PARAMETER, id_qr);
try {
qr = (FAQ) query.getSingleResult();
} catch ( NoResultException e ) {
return null;
} catch(Exception e) {
throw new DAOException(e);
}
return qr;
}
}
`
Persisting the FAQ entity was successful, but loading the data does'nt return anything, maybe the query instruction is wrong?
Here's the servlet:
`#WebServlet ( urlPatterns = { "/afficherfaq" })
public class AfficherFaq extends HttpServlet {
#EJB
private FAQDao faqDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher("/WEB-INF/ChargerFaq.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FAQ> lfaq = faqDao.chargerFAQ();
request.setAttribute("lfaq", lfaq);
this.getServletContext().getRequestDispatcher("/WEB-INF/ChargerFaq.jsp").forward(request, response);
}
}
`
And the Entity's path is included in the persistence.xml file.
EDIT: Added JSP code.
JSP file to show the result:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="inc/style.css" />
<title>Foire aux questions</title>
</head>
<body>
Test
<c:forEach items="${lfaq}" var="faq" varStatus="boucle">
<fieldset>
<p><span class="info">Question:</span></p><br>
<p>${faq.question}</p><br>
<p><span class="info">Reponse:</span></p><br>
<p>${faq.reponse}</p><br>
</fieldset><br><br>
</c:forEach>
</body>
</html>

Spring form submit validation for foreign key

My project is a spring mvc project.In my project i have a domain Technology which has foreign key reference.When i validating on form submit it threw error....For view part(jsp),i using form:select for viewing department in technology.
How can i validate a foreign reference?????
i tried below code
domain
#Entity
#Table(name = "technology")
public class Technology {
private int id;
#NotEmpty
private String name;
#NotEmpty
private Department department;
private Date createdDate;
private boolean isDelete;
}
message.properties
NotEmpty.technology.department=Required!
Technology.jsp
<form:form method="post" action="add-technology"
commandName="technology" id="technologyForm">
<label>Technology Name</label>
<form:input path="name" /><form:errors path="name" class="error"></form:errors>
<br />
<label>Department</label>
<form:select path="department.id">
<form:option value="0" label="Select" />
<form:options items="${departments}" itemValue="id" itemLabel="name" />
</form:select><form:errors path="department" class="error"></form:errors>
<%-- <form:select path="department.id" items="${departments}" /> --%>
<input type="submit" class="btn btn-primary"/>
</form:form>
controller
#RequestMapping(value = "/add-technology")
public String addTechnology(
#ModelAttribute(value = "technology")#Valid Technology technology,
BindingResult result) {
if(result.hasErrors()){
return "/secure/admin/technology";
}
java.util.Date utilDate = new java.util.Date();
Date sqlDate = new Date(utilDate.getTime());
technology.setCreatedDate(sqlDate);
technologyService.saveTechnology(technology);
return "redirect:/technologies";
}
ERROR
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.UnexpectedTypeException: No validator could be found for type: com.company.product.domain.Department
How can i resolve this problem???
Here you have to implement validator for Technology object
class TechnologyValidator extends Validator {
public boolean supports(Class<?> cls) {
return Technology .class.equals(cls);
}
public void validate(Object target, Errors errors) {
super.validate(target, errors);
Technology tecObj= (Technology ) target;
//here i am assuming Technology name is REQUIRED and
//NotEmpty.technology.name is in message.properties
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name",
"NotEmpty.technology.name");
Department dept = tecObj.getDepartment();
//as from from your are binding department ID
if (dept==null || dept.getId()==null || dept.getId()==0L ) {
errors.rejectValue("department.id", "NotEmpty.technology.department");
}
}
}
And create bean of this class in Spring-context
#Autowired
TechnologyValidator techValid;
And call this validator in your controller like
#RequestMapping(value = "/add-technology")
public String addTechnology(
#ModelAttribute(value = "technology") Technology technology,
BindingResult result) {
//call validator
techValid.validate(technology, result);
if(result.hasErrors()){
return "/secure/admin/technology";
}
java.util.Date utilDate = new java.util.Date();
Date sqlDate = new Date(utilDate.getTime());
technology.setCreatedDate(sqlDate);
technologyService.saveTechnology(technology);
return "redirect:/technologies";
}

Controller Bean not picking up the username

I'm really in a grave problem with this. All of a sudden my properly working code has stopped working. I have no clue what so ever why!!!! And worst of all I have to deploy my project today :( . Don't know if it will be right to say or not but all of this started 2 days after adding PrimeFaces in build path. Can anyone please direct me to the right direction. Would be great help!
I have following configuration:
Glassfish v3
Mojara 2.1.6-FCS
JPA Eclipselink
Controller Bean
public List<Usergroupdetail> getUsergroupdetail_list() {
List<Usergroupdetail> myUserGroupDetail = new ArrayList<Usergroupdetail>(
lODBN.listUserGroupDetail(loginBean.getUsername()));
System.out.println("username found is:" + loginBean.getUsername());
return myUserGroupDetail;
}
For getting complete list of data from the JPA PoJO UserGroupReport
public List<Usergroupreport> getGroupId_list() {
List<Usergroupreport> myAllgroupIds = new ArrayList<Usergroupreport>(
lODBN.findAllGroupIdByUser(loginBean.getUsername()));
return myAllgroupIds;
}
Stack Trace
WARNING: PWC4011: Unable to set request character encoding to ISO-8859-1 from context /WebApp, because request parameters have already been read, or ServletRequest.getReader() has already been called
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
Login Bean
package bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
//import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import ejb.UserDaoBean;
import ejb.UserGroupDaoBean;
import model.User;
#ManagedBean(name = "loginBean")
#SessionScoped
public class LoginBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private UserDaoBean uDB;
#EJB
private UserGroupDaoBean uGDB;
private User userId;
public List<User> usernameFirstLastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String firstName;
public String lastName;
public String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<User> getUsernameFirstLastName() {
List<User> myName = new ArrayList<User>(uDB.findFirtLastNames(username));
return myName;
}
public void setUsernameFirstLastName(List<User> usernameFirstLastName) {
this.usernameFirstLastName = usernameFirstLastName;
}
private String username;
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
if (uDB.validateUser(username,password)) {
userId = uDB.findUser(username);
context.getExternalContext().getSessionMap().put("userId", userId);
if (uGDB.validateGroup(userId)) {
return "home.jsf?faces-redirect=true&includeViewParams=true";
}
return "normalHome.jsf?faces-redirect=true&includeViewParams=true";
} else {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Username doesn't exists! OR User is trying to login from someone else's account");
context.addMessage("", message);
return "newloginerror.jsf?faces-redirect=true";
}
}
public String logout() {
FacesContext.getCurrentInstance().getExternalContext()
.invalidateSession();
return "logout.jsf?faces-redirect=true";
}
}
Login Page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link href="./css/PageLayout.css" rel="stylesheet" type="text/css" />
<title>Login</title>
</h:head>
<h:body>
<f:view>
<div style="background-color: #205a8c; width: auto; height: 60px">
<h3 style="font-size: large; position: relative;" align="left">Lord
Of Data Web App</h3>
</div>
<div id="wrappers">
<div class="content pls centering">
<h:form>
<table class="form_table" style="background-color: silver;">
<tbody>
<tr>
<td>Username</td>
<td><h:inputText id="inputusername"
value="#{loginBean.username}" required="true"
requiredMessage="Username is required!"></h:inputText> <h:message
for="inputusername"></h:message></td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret id="inputpassword"
value="#{loginBean.password}" required="true"
requiredMessage="Password is required!"></h:inputSecret> <h:message
for="inputpassword"></h:message></td>
</tr>
</tbody>
</table>
<div id="buttonsoptions" align="center" style="padding-top: 10px;">
<h:panelGroup>
<tr>
<td><h:commandButton id="login" value="Login"
action="#{loginBean.login}"></h:commandButton></td>
</tr>
</h:panelGroup>
</div>
</h:form>
</div>
</div>
</f:view>
</h:body>
</html>
EJB Code Snippet for Login Authentication
public boolean validateUser(String username, String password) {
try {
Query myQuery = entityManager.createNamedQuery("userverification")
.setParameter("username", username)
.setParameter("password", password);
User result = (User) myQuery.getSingleResult();
if (result != null) {
System.out.println("Loggin sucessful!");
return true;
} else {
System.out.println("User does not exists in the system");
return false;
}
} catch (NoResultException e) {
return false;
}
}
And I tried to use the username to my other session bean which was working perfectly fine until two days back. Here is the code for this bean where I am trying to call the Username picked from login bean
Bean
package bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import ejb.LODReportDaoBean;
import ejb.LordOfDataDaoBeanNormal;
import ejb.UserDaoBean;
import model.Lodreport;
import model.Usergroupdetail;
import model.Usergroupreport;
#ManagedBean(name = "lordOfDataNormalUserBean")
#SessionScoped
public class LordOfDataNormalUserBean implements Serializable {
/**
* #author Sushant Pandey
*/
private static final long serialVersionUID = 1L;
#EJB
private LordOfDataDaoBeanNormal lODBN;
#EJB
private UserDaoBean uDB;
#EJB
private LODReportDaoBean lONRDB;
#ManagedProperty(value = "#{loginBean}")
private LoginBean loginBean;
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
public List<Lodreport> lodnormal_list;
public List<Usergroupreport> usergroup_list;
public List<Usergroupdetail> usergroupdetail_list;
public List<Lodreport> findDataByRowId;
private Lodreport myreport = new Lodreport();
public Lodreport getMyreport() {
return myreport;
}
public void setMyreport(Lodreport myreport) {
this.myreport = myreport;
}
public void setFindDataByRowId(List<Lodreport> findDataByRowId) {
this.findDataByRowId = findDataByRowId;
}
public int security;
public String username;
public String access;
public String authentifizierteBenutzer;
public String auto;
public String comment;
public String comment1;
public String comment2;
public String comment3;
public String domain1;
public String domain2;
public String emailFeedback;
public String emailSendStatus;
public String lOD1CostCenter;
public String lOD1DisplayName;
public String lOD1Domain;
public String lOD1Mail;
public String lOD1User;
public String lOD2CostCenter;
public String lOD2DisplayName;
public String lOD2Domain;
public String lOD2Mail;
public String lOD2User;
public String rechteGruppeChange;
public String rechteGruppeRead;
public String type;
public int rowId;
public List<Usergroupreport> groupId_list;
public boolean edit;
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public void setGroupId_list(List<Usergroupreport> groupId_list) {
this.groupId_list = groupId_list;
}
public void setLodnormal_list(List<Lodreport> lodnormal_list) {
this.lodnormal_list = lodnormal_list;
}
public int getSecurity() {
return security;
}
public void setSecurity(int security) {
this.security = security;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
public String getAuthentifizierteBenutzer() {
return authentifizierteBenutzer;
}
public void setAuthentifizierteBenutzer(String authentifizierteBenutzer) {
this.authentifizierteBenutzer = authentifizierteBenutzer;
}
public String getAuto() {
return auto;
}
public void setAuto(String auto) {
this.auto = auto;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getComment1() {
return comment1;
}
public void setComment1(String comment1) {
this.comment1 = comment1;
}
public String getComment2() {
return comment2;
}
public void setComment2(String comment2) {
this.comment2 = comment2;
}
public String getComment3() {
return comment3;
}
public void setComment3(String comment3) {
this.comment3 = comment3;
}
public String getDomain1() {
return domain1;
}
public void setDomain1(String domain1) {
this.domain1 = domain1;
}
public String getDomain2() {
return domain2;
}
public void setDomain2(String domain2) {
this.domain2 = domain2;
}
public String getEmailFeedback() {
return emailFeedback;
}
public void setEmailFeedback(String emailFeedback) {
this.emailFeedback = emailFeedback;
}
public String getEmailSendStatus() {
return emailSendStatus;
}
public void setEmailSendStatus(String emailSendStatus) {
this.emailSendStatus = emailSendStatus;
}
public String getlOD1CostCenter() {
return lOD1CostCenter;
}
public void setlOD1CostCenter(String lOD1CostCenter) {
this.lOD1CostCenter = lOD1CostCenter;
}
public String getlOD1DisplayName() {
return lOD1DisplayName;
}
public void setlOD1DisplayName(String lOD1DisplayName) {
this.lOD1DisplayName = lOD1DisplayName;
}
public String getlOD1Domain() {
return lOD1Domain;
}
public void setlOD1Domain(String lOD1Domain) {
this.lOD1Domain = lOD1Domain;
}
public String getlOD1Mail() {
return lOD1Mail;
}
public void setlOD1Mail(String lOD1Mail) {
this.lOD1Mail = lOD1Mail;
}
public String getlOD1User() {
return lOD1User;
}
public void setlOD1User(String lOD1User) {
this.lOD1User = lOD1User;
}
public String getlOD2CostCenter() {
return lOD2CostCenter;
}
public void setlOD2CostCenter(String lOD2CostCenter) {
this.lOD2CostCenter = lOD2CostCenter;
}
public String getlOD2DisplayName() {
return lOD2DisplayName;
}
public void setlOD2DisplayName(String lOD2DisplayName) {
this.lOD2DisplayName = lOD2DisplayName;
}
public String getlOD2Domain() {
return lOD2Domain;
}
public void setlOD2Domain(String lOD2Domain) {
this.lOD2Domain = lOD2Domain;
}
public String getlOD2Mail() {
return lOD2Mail;
}
public void setlOD2Mail(String lOD2Mail) {
this.lOD2Mail = lOD2Mail;
}
public String getlOD2User() {
return lOD2User;
}
public void setlOD2User(String lOD2User) {
this.lOD2User = lOD2User;
}
public String getRechteGruppeChange() {
return rechteGruppeChange;
}
public void setRechteGruppeChange(String rechteGruppeChange) {
this.rechteGruppeChange = rechteGruppeChange;
}
public String getRechteGruppeRead() {
return rechteGruppeRead;
}
public void setRechteGruppeRead(String rechteGruppeRead) {
this.rechteGruppeRead = rechteGruppeRead;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getRowId() {
return rowId;
}
public void setRowId(int rowId) {
this.rowId = rowId;
}
public void setUsergroup_list(List<Usergroupreport> usergroup_list) {
this.usergroup_list = usergroup_list;
}
public void setUsergroupdetail_list(
List<Usergroupdetail> usergroupdetail_list) {
this.usergroupdetail_list = usergroupdetail_list;
}
#PostConstruct
public void init() {
// getLodnormal_list();
getUsergroupdetail_list();
// getGroupId_list();
getUsername();
}
public String displayReport() {
getLodnormal_list();
return "reportLordOfDataNormal.jsf?faces-redirect=true";
}
public List<Lodreport> getLodnormal_list() {
List<Lodreport> myLodreport = new ArrayList<Lodreport>(
lODBN.reportLODNormal(loginBean.getUsername()));
System.out.println("LOD list for Username :" + loginBean.getUsername() );
return myLodreport;
}
public List<Usergroupreport> getUsergroup_list() {
return usergroup_list;
}
public List<Usergroupdetail> getUsergroupdetail_list() {
List<Usergroupdetail> myUserGroupDetail = new ArrayList<Usergroupdetail>(
lODBN.listUserGroupDetail(loginBean.getUsername()));
System.out.println("username found is:" + loginBean.getUsername());
return myUserGroupDetail;
}
public String editLODDataNormal() {
lODBN.updateExistingLODDataNormal(security, loginBean.getUsername(),
access, authentifizierteBenutzer, auto, comment, comment1,
comment2, comment3, domain1, domain2, emailFeedback,
emailSendStatus, lOD1CostCenter, lOD1DisplayName, lOD1Domain,
lOD1Mail, lOD1User, lOD2CostCenter, lOD2DisplayName,
lOD2Domain, lOD2Mail, lOD2User, rechteGruppeChange,
rechteGruppeRead, type, rowId);
return "reportLordOfDataNormal.jsf?faces-redirect=true";
}
public List<Usergroupreport> getGroupId_list() {
List<Usergroupreport> myAllgroupIds = new ArrayList<Usergroupreport>(
lODBN.findAllGroupIdByUser(loginBean.getUsername()));
return myAllgroupIds;
}
public void edit(Lodreport myreport) {
this.myreport = myreport;
edit = true;
}
public void saveMyReport(){
lONRDB.updateReport(myreport);
}
}

Avoiding entity update directly on form submit

I have an entity which is showed on the screen as text in input boxes which can be modified. When i submit the form hitting save, i would like my ejb3 component to handle the data and persist or merge it using the entity manager. But for some reason, when i modify the data and hit save the data directly gets updated in the database by-pasing my ejb3, which is certainly undesirable. My code looks like the following
#Entity
#Table(name = "EMP")
public class Emp implements java.io.Serializable {
private short empno;
private Dept dept;
private String ename;
private String job;
private Short mgr;
private Date hiredate;
private BigDecimal sal;
private BigDecimal comm;
public Emp() {
}
public Emp(short empno) {
this.empno = empno;
}
public Emp(short empno, Dept dept, String ename, String job, Short mgr,
Date hiredate, BigDecimal sal, BigDecimal comm) {
this.empno = empno;
this.dept = dept;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
}
#Id
#Column(name = "EMPNO", unique = true, nullable = false, precision = 4, scale = 0)
public short getEmpno() {
return this.empno;
}
public void setEmpno(short empno) {
this.empno = empno;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "DEPTNO")
public Dept getDept() {
return this.dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
#Column(name = "ENAME", length = 10)
#Length(max = 10)
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
#Column(name = "JOB", length = 9)
#Length(max = 9)
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
#Column(name = "MGR", precision = 4, scale = 0)
public Short getMgr() {
return this.mgr;
}
public void setMgr(Short mgr) {
this.mgr = mgr;
}
#Temporal(TemporalType.DATE)
#Column(name = "HIREDATE", length = 7)
public Date getHiredate() {
return this.hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
#Column(name = "SAL", precision = 7)
public BigDecimal getSal() {
return this.sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
#Column(name = "COMM", precision = 7)
public BigDecimal getComm() {
return this.comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
}
#Stateful
#Name("workflow")
#Scope(ScopeType.CONVERSATION)
public class WorkflowBean implements Workflow
{
#Logger private Log log;
#In StatusMessages statusMessages;
#PersistenceContext(type=PersistenceContextType.EXTENDED)
EntityManager entityManager;
#Out(required=false)
Emp employee = new Emp();
#RequestParameter("empEmpno")
String empNo;
public void workflow()
{
log.info("workflow.workflow() action called");
statusMessages.add("workflow");
}
#End
public boolean save(){
entityManager.merge(emp);
entityManger.flush();
}
#Begin(join=true)
public boolean populateEmp(){
entityManager.setFlushMode(FlushModeType.COMMIT);
System.out.println("The Emp No. is---"+empNo);
int no = Integer.parseInt(empNo);
short emp =(short)no;
employee = entityManager.find(Emp.class, emp);
entityManager.flush();
return true;
}
public Emp getEmployee() {
return employee;
}
public void setEmployee(Emp employee) {
this.employee = employee;
}
// add additional action methods
public String getEmpNo() {
return empNo;
}
public void setEmpNo(String empNo) {
this.empNo = empNo;
}
#Remove
#Destroy
public void destroy() {
}
}
My view looks like
<h:form id="emp" styleClass="edit">
<rich:panel>
<f:facet name="header">Edit Emp</f:facet>
<s:decorate id="empnoField" template="layout/edit.xhtml">
<ui:define name="label">Empno</ui:define>
<h:inputText id="empno"
required="true"
value="#{workflow.employee.empno}">
</h:inputText>
</s:decorate>
<s:decorate id="commField" template="layout/edit.xhtml">
<ui:define name="label">Comm</ui:define>
<h:inputText id="comm"
value="#{workflow.employee.comm}"
size="14">
</h:inputText>
</s:decorate>
<s:decorate id="enameField" template="layout/edit.xhtml">
<ui:define name="label">Ename</ui:define>
<h:inputText id="ename"
size="10"
maxlength="10"
value="#{workflow.employee.ename}">
</h:inputText>
</s:decorate>
<s:decorate id="hiredateField" template="layout/edit.xhtml">
<ui:define name="label">Hiredate</ui:define>
<rich:calendar id="hiredate"
value="#{workflow.employee.hiredate}" datePattern="MM/dd/yyyy" />
</s:decorate>
<s:decorate id="jobField" template="layout/edit.xhtml">
<ui:define name="label">Job</ui:define>
<h:inputText id="job"
size="9"
maxlength="9"
value="#{workflow.employee.job}">
</h:inputText>
</s:decorate>
<s:decorate id="mgrField" template="layout/edit.xhtml">
<ui:define name="label">Mgr</ui:define>
<h:inputText id="mgr"
value="#{workflow.employee.mgr}">
</h:inputText>
</s:decorate>
<s:decorate id="salField" template="layout/edit.xhtml">
<ui:define name="label">Sal</ui:define>
<h:inputText id="sal"
value="#{workflow.employee.sal}"
size="14">
</h:inputText>
</s:decorate>
<s:decorate id="deptField" template="layout/edit.xhtml">
<ui:define name="label">Department</ui:define>
<h:inputText id="dname"
value="#{workflow.deptName}">
</h:inputText>
</s:decorate>
<div style="clear:both">
<span class="required">*</span>
required fields
</div>
</rich:panel>
<div class="actionButtons">
<h:commandButton id="save"
value="Save"
action="#{workflow.save}"
rendered="true"/>
</div>
</h:form>
[It was difficult to address issue in comments for your response.]
There are few things which I haven't understand & why it's done that way.
Using transient fields, it will add overhead of adding those to entity object while persisting.
Why is auto-commit causes issue & can't be implemented.
Regardless of these things, you can try
Making the entity detached with entityManager.detach(entity) or clearing the persistence context with entityManager.clear(), detaching all the underlying entities. But prior one is more favourible.
Can manage transaction manually instead of container. Use BMT where you can have control over the operations.