PropertyNotFoundException occurs even when the getter is present - java

I am working on a small messaging web application to learn jsp's and servlets. I have a MessageModel class with the following properties :
String toAddress ;
String fromAddress;
String messageSubject;
String messageContent;
Timestamp messageTime;
int messageDraft;
And their corresponding setters for a jsp to access.
I have a method which queries a database with all the messages for the messages received to a particular address to display. It then creates a new MessageModel object and stores it in a ArrayList.
public static ArrayList<MessageModel> getReceivedMessages(String toAddress) throws SQLException, ClassNotFoundException{
// creates a arraylist.
ArrayList<MessageModel> msgList = new ArrayList<MessageModel>();
// Database connection code..
// The query which gets the required messages from the database and adds them to the list.
String query = "SELECT * FROM messages WHERE msg_to='" + toAddress +"' ORDER BY msg_date DESC";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
while(rs.next()){
String msgTo = rs.getString("msg_to");
String msgFrom = rs.getString("msg_from");
String msgSub = rs.getString("msg_subject");
String msgCnt = rs.getString("msg_matter");
Timestamp msgTime = rs.getTimestamp("msg_date");
MessageModel model = new MessageModel(msgTo,msgFrom,msgSub,msgCnt,msgTime);
msgList.add(model);
}
}
return msgList;
}
I call this method from the jsp and save the list as an attribute by using
String userName = (String) session.getAttribute("userId");
ArrayList<MessageModel> list = MessageModel.getReceivedMessages(userName);
pageContext.setAttribute("messageList", list);
But when I access the fromAddress property of the MesasgeModel objects in the list through a <c:forEach> tag, I get the following error :
javax.el.PropertyNotFoundException: Property 'fromAddress' not found on type com.email.system.MessageModel
This is the part of the HTML which access prints out the contents of each MessageModel object.
<c:forEach items="${messageList}" var="message">
<li><c:out value="${message.toAddress}"/>
<c:out value="${message.messageSubject}"/> <c:out value="${message.messageTime}"/>
<c:out value="${message.messageContent}"/> <c:out value="${message.fromAddress}"/> </li>
</c:forEach>
The error occurs whenever I try to access the toAddress field. The toAddress property is being stored int the messageSubject field even though when I try the same query in the mySql console I get the proper fields in their respective columns.
An exapmle result to the query where I removed the content column,
msg_id msg_to msg_from msg_subject msg_date msg_is_draft
4 bigb remember *subject* 2014-10-07 11:01:53 0
2 bigb remember *subject* 2014-10-07 10:48:43 0
1 bigb remember *subject* 2014-10-07 10:48:31 0
EDIT: This is the MessageModel class I have.
public class MessageModel {
String toAddress ;
String fromAddress;
String messageSubject;
String messageContent;
Timestamp messageTime;
int messageDraft;
public String getToAddress() {
return toAddress;
}
public String getFromAddress() {
return fromAddress;
}
public String getMessageSubject() {
return messageSubject;
}
public String getMessageContent() {
return messageContent;
}
public Timestamp getMessageTime() {
return messageTime;
}
public int getMessageDraft() {
return messageDraft;
}
public MessageModel(String toAddress,String fromAddress, String messageSubject, String messageContent,Timestamp messageTime){
this.toAddress = toAddress;
this.messageSubject = messageSubject;
this.messageContent = messageContent;
this.messageTime = messageTime;
this.fromAddress = fromAddress;
}
public void sendMessage(MessageModel model){
//Gets the related properties from the objects and stores it in the database
}
public static ArrayList<MessageModel> getReceivedMessages(String toAddress){
//Gets the messages sent to 'toAddress'
}
}

Turns out if you make some changes to any java source file which you use in you application you have to do a full rebuild and redeploy for the changes to take place.
There wasn't anything wrong in my code when I asked my question, instead of redeploying I was just updating resources. That only updates changes made to the JSP's not the java sources.

Related

How to access a variable in mysql database from another class?

I am trying to access a variable from one class in another.
In my example below, I have 2 files, one called login.java and usermainpage.java.
I want to access a variable called sessionId that is in login.java from usermainpage class file.
I tried several methods but it is not working at all, in login class file, I declared sessionId as a public string and in the file I define it as equals to a data that I retrieved from my database. (If you see the code I am doing a database connection also).
I thought by returning sessionId at the end of the function I can now access this variable from all other java files but no, in my usermainpage.java file, I tried printing out sessionId and it displays nothing. Let me know of a solution, thank you.
// login.java file
public class login extends javax.swing.JFrame {
public String sessionId;
Connection con;
PreparedStatement pst;
ResultSet rs;
private String LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {
try{
String query = "SELECT * FROM `accounts` WHERE username=? and password=?";
con = DriverManager.getConnection("jdbc:mysql://localhost/restock", "root", "password");
pst = con.prepareStatement(query);
pst.setString(1, txtUsername.getText());
pst.setString(2, txtPassword.getText());
rs = pst.executeQuery();
if(rs.next()){
String userType = rs.getString("usertype");
sessionId = rs.getString("id");
System.out.print("##########" + sessionId + "##########"); //this prints out the id I want
if(userType.equals("Admin")){
JOptionPane.showMessageDialog(this, "Login is successful as admin");
mainpage admin = new mainpage();
admin.setVisible(true);
dispose();
} else{
JOptionPane.showMessageDialog(this, "Login is successful as user");
usermainpage user = new usermainpage();
user.setVisible(true);
dispose();
}
}
else{
JOptionPane.showMessageDialog(this, "Incorrect username or password");
txtUsername.setText("");
txtPassword.setText("");
}
} catch(HeadlessException | SQLException ex){
JOptionPane.showMessageDialog(this, ex.getMessage());
}
return sessionId;
}
}
//usermainpage.java file
public class usermainpage extends javax.swing.JFrame {
private void RequestButtonActionPerformed(java.awt.event.ActionEvent evt) {
String type = txttype.getSelectedItem().toString();
String name = txtname.getText();
String quantity = txtquantity.getText();
String status = "Pending";
String userId;
//Create new class object from login.java
login testing = new login();
userId = testing.sessionId;
System.out.print("########## " + userId + "########## "); //this prints out null value
}
}
EDIT: These are some of the problems I encountered based on the suggestions.
There are so many problems with your code:
You should always follow Java naming conventions e.g. you should name your class as Login instead of login. Similarly, the name of your method should be loginButtonActionPerformed instead of LoginButtonActionPerformed.
I do not see any use of the parameter, java.awt.event.ActionEvent evt in your method, LoginButtonActionPerformed. I would remove it from its definition and the calls.
You should avoid making variables public. You should keep sessionId as private or protected as per the requirement and create the public accessor and mutator for it as shown below:
private String sessionId;
public setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getSessionId() {
return sessionId;
}
You are returning the value of sessionId from the method, LoginButtonActionPerformed and therefore you need to call this method inside your method, RequestButtonActionPerformed as follows:
login testing = new login();
userId = testing.LoginButtonActionPerformed(evt);
However, for this, you need to declare your method, LoginButtonActionPerformed as public.
A better approach would be to declare LoginButtonActionPerformed as public void and then you can do:
login testing = new login();
testing.LoginButtonActionPerformed(evt);
userId = testing.getSessionId();

Getting an EJBTransactionRolledbackException when trying to connect to a MYSQL database

I'm trying to functionality to login with credentials from the database. So far I've just been getting an EJBTransactionRolledbackException. The stack trace is huge and so far I have not been able to find anything online related to my specific issue.
So the MySQL database I have set up has tables divided up into logical data. I have a user_info table with a memberID, addressID, loginID, firstName, lastName, email, phoneNumber, and isModerator. My user_login table has loginID, username, and password. The user_address table is not necessary at this point in the program. The loginID from the user_login table is a foreign key in the user_info table. So I essentially do an inner join to get all the info from bot tables and then try to create a new user object and return it. I've tried just pulling data from one table but the same issue persists. The query being used in the Java code works just fine in MySQL workbench.
Here is the method in question, it's the findEntry method:
#Stateless
#Local(DataAccessInterface.class)
#LocalBean
public class UserDataService implements DataAccessInterface<User> {
public UserDataService() {
}
#Override
public List<User> findAll() {
return null;
}
#Override
public User findEntry(String condition) {
String query = "SELECT * FROM user_info INNER JOIN user_login WHERE username='" + condition + "';";
Connection databaseConnection = null;
Statement statement = null;
ResultSet resultSet = null;
User currentUser = null;
try {
databaseConnection = DriverManager.getConnection(url, username, password);
statement = databaseConnection.createStatement();
resultSet = statement.executeQuery(query);
currentUser = new User(resultSet.getInt("memberID"), resultSet.getInt("addressID"), resultSet.getInt("loginID"), resultSet.getString("firstName"), resultSet.getString("lastName"), resultSet.getString("email"), resultSet.getString("phoneNumber"), resultSet.getString("username"), resultSet.getString("password"), resultSet.getInt("isModerator"));
}
catch(SQLException e) {
throw new DatabaseException(e);
}
finally {
try {
if(databaseConnection != null) {
databaseConnection.close();
statement.close();
resultSet.close();
}
}
catch(SQLException e) {
throw new DatabaseException(e);
}
}
return currentUser;
}
Here is where the findEntry is being called:
#Stateless
#Local(AccountBusinessInterface.class)
#LocalBean
public class AccountBusiness implements AccountBusinessInterface {
#EJB
private DataAccessInterface<User> userDataService;
public AccountBusiness() {
}
/**
* Validates that the use who entered in their username and password entered the correct information.
*/
#Override
public int validateUser(User user) {
//Sets the login boolean to true.
//user.setLoggedIn(true);
//Sets the login text to logout.
//user.setLoginText("Logout");
User currentUser = userDataService.findEntry(user.getUsername());
if(currentUser != null) {
return 0;
}
return 1;
}
This is the onLogin method in the login controller:
#ManagedBean
#ViewScoped
public class LoginController {
/**
* This is the BusinessAccountInferface.
*/
#Inject
private AccountBusinessInterface accountBusinessInterface;
/**
* The default constructor.
*/
public LoginController() {
}
/**
* Takes in a user object and returns the product page that can only be seen by a logged in user, assuming the correct
* username and password was entered.
* #param user
* #return String
*/
public String onLogin(User user) {
//Gets the user object from the appropriate form.
FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("user", user);
//If authentication fails, returns the error page.
if(accountBusinessInterface.validateUser(user) == 0) {
//Return the products page.
return "ProductsPage.xhtml";
}
//Returns the login page by default.
return "Login.xhtml";
}
Here is my custom exception:
public class DatabaseException extends RuntimeException {
/**
* This is the default serial version id.
*/
private static final long serialVersionUID = 1L;
public DatabaseException() {
printStackTrace();
}
public DatabaseException(SQLException e) {
printMessage(e.getMessage());
}
public DatabaseException(String message) {
printMessage(message);
}
public DatabaseException(SQLException e, String message) {
printMessage(e.getMessage());
printMessage(message);
}
private void printMessage(String message) {
System.err.println(message);
}
}
The stack trace is too long, but here are the first two lines:
19:11:22,668 ERROR [stderr] (default task-18) Before start of result set
19:11:22,671 ERROR [org.jboss.as.ejb3.invocation] (default task-18) WFLYEJB0034: EJB Invocation failed on component UserDataService for method public beans.User data.UserDataService.findEntry(java.lang.String): javax.ejb.EJBTransactionRolledbackException
The rest of the stack trace is in a file here since I couldn't paste it here:
https://www.dropbox.com/s/r4ampjxr7clfzjz/log.txt?dl=0
The expected result is that a user will be returned from the findEntry method, which is checked in the validateUser method on the business logic, and if it does not return null then 0 is returned which is checked in the login controller which should log the user in. Obviously something is wring with the database being rolled back. I'm just not sure what that means or what is causing it to happen or how to fix it. Did I leave any important code or xml files out?
You have to move the curser in the result set first, this is what the error message "Before start of result set" is telling you.
So move the curser first before reading from it. ResultSet#next() will return true if it is not already at the end.
if (resultSet.next()){
currentUser = new User(resultSet.getInt("memberID")...
}

Incorrect data getting fetched from select query

Can someone review my code
This query is fetching two values address_id and postcode from table1. Here
AddressID class has two variable postcode(string) and address_id(integer) :
#Select("SELECT address_id,postcode FROM table1 WHERE custom_field_1 = #{caseid}")
public List<AddressID> getAddressIdPostCodeList(String caseid);
Here is how AddressID looks AddressID.java
private int addressId;
private String postcode;
//getters and setters of Pstcode and addressId
#Override
public String toString() {
return "PostCode : " + this.postcode;
}
while executing this query I get value of address_id as 0 and required postcode. Although DB has values of address_id which is not zero. Where my code is failing?
This is where in my main method I am calling
List<AddressID> addresses = new ArrayList<>();
addresses = mainClassObject.getAddressIdPostCodeList(address.getcaseId());
Ideally addresses object should have both address_id and postcode. I am getting both values but address_id I am getting 0 and correct values for postcode.
Since I cant comment because I dont have 50 reputation, I had to write it here, its hard to tell from the code you posted, to give you an answer I need more detail on what getAddressIdPostCodeList() does, since you said the data in the DB has no ceros the error must be in the method getAddressIdPostCodeList() and/or in how you are handling the resultset of the Query
EDIT: Solution using Oracle JDBC Driver
Since I dont know how to use Mybatis, heres a solution using JDBC.
to connect using JDBC to your Oracle DB here's a simple tutorial:
1. First you need to download de JDBC driver from Oracle depending your DB version (11g,12c,10g), the driver Its called ojdbcX.jar where X is a number of the version of the driver
2. After you have downloaded the driver you need to add the .jar to your project, if you are using Netbeans IDE you can add it like this:
if you are using Eclipse you can use the following Link to see how to add the .JAR file: How to import a jar in Eclipse
3. After adding the .JAR its pretty simple, you just need to connect to the DB using your credentials, here is an example on how to do it:
Connection connection = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system", "password"); } catch (Exception ex) {
ex.printStackTrace();
}
for more deatiled information on how to connect, you can check the oracle.jdbc
Class OracleDriver Documentation
4. After the connection has been made its pretty simple, Heres a short code example to get the result you want, you need to modify it with your connection details and as you see fit because im making a couple of assumptions, this code is just an example:
Main.Java
public class Main {
public static void main(String[] argv) {
List<AddressID> addresses;
SQLConnect conex= new SQLConnect();
String caseid="the id you want";
addresses=conex.getAddressIdPostCodeList(caseid);
}
AddressID.java
public class AddressID {
private String addressId;
private String postcode;
}
SQLConnect.Java
public class SQLConnect {
public static Connection connection;
public SQLConnect (){
createConnection();
}
public void CreateConnection(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system", "password")
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void closeConnection(){
if(connection!=null){
try {
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public ResultSet ExecuteQuery(String queryTXT) throws SQLException{
Statement query = connection.createStatement();
ResultSet table=query.executeQuery(queryTXT);
return table;
}
public List<AddressID> getAddressIdPostCodeList(String caseid) throws SQLException{
List<AddressID> addresses = new ArrayList <> ();
ResultSet table=ExecuteQuery("SELECT address_id,postcode FROM table1 WHERE custom_field_1 ='"+caseid+"';");
while (table.next()) {
AddressID aux;
aux.addressId=table.getString(1);
aux.postcode=table.getString(2);
addresses.add(aux);
}
return addresses;
}
}
I did forgot to wtite my result query which is actually binding data fetched
from select query to the AddressId class..
#Results(id = "result",
value = {
#Result(property = "addressId", column = "address_id"),
#Result(property = "postcode", column = "postcode")
}
)

How to pass value from servlet to Dao class and perform operation and return List/ Arraylist to JSP page

Hello i am new at JSP developing and i need some help about JSP MVC programming I want to pass a value from Servlet and in Dao class i want to receive it in List function and perform operation and return th array to JSP page to use ..
Servlet
String company = "ABCD";
ObsBean ComName = new ObsBean();
ComName.setCompanyName(company);
dao.getComNotify(ComName);
Bean Class (ObsBean)
private String CompanyName;
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String CompanyName) {
this.CompanyName = CompanyName;
}
**DAO Class (ObsDao) **
public List getComNotify(ObsBean ComName) {
List<ObsBean> comNotify = new ArrayList<ObsBean>();
String cname = ComName.getCompanyName();//getting from bean class by getter
try {
String sql = "SELECT * from ObsNotify where notto='"+cname+"'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
ObsBean userNotify = new ObsBean();
userNotify.setNotifyName(rs.getString("notname"));
userNotify.setNotifyBy(rs.getString("notby"));
userNotify.setNotifyTo(rs.getString("notto"));
userNotify.setNotifyDate(rs.getString("notdate"));
comNotify.add(userNotify);
}
}
catch (Exception e) {
out.print("Error for User Notification - : "+e);
}
return comNotify;
}
IN JSP Page :
<%
ObsDao dao = new ObsDao();
List<ObsBean> ComNotify = dao.getComNotify();
for (ObsBean UserNotifi : ComNotify) {
.........
.........
}
%>
This is my complete code , but it shows error , why ?
ERRORS :
HTTP Status 500 – Internal Server Error
Type Exception Report
Message javax.servlet.ServletException: java.lang.NoSuchMethodError: com.ApexCorner.ModelDao.ObsDao.getComNotify()Ljava/util/List;
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: com.ApexCorner.ModelDao.ObsDao.getComNotify()Ljava/util/List;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:565)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Based on your code I assume that "notto" in your table is a company name, so if your sql statement is correct i would rewrite your code as follows:
public List getComNotify(ObsBean Comname) {
List<ObsBean> comNotify = new ArrayList<ObsBean>();
String COM = Comname.getcompanyname();
try {
String sql = "SELECT * from ObsNotify where notto='"+COM+"'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
ObsBean userNotify = new ObsBean();
int totalRows = rs.getRow();
userNotify.setNotifyName(rs.getString("notname"));
userNotify.setNotifyBy(rs.getString("notby"));
comNotify.add(userNotify);
}
}
catch (Exception e) {
out.print("Error for User Notification - : "+e);
}
return comNotify;
}
Comname is an object of the ObsBean type, you should retrieve the company name as a string before you can apply it to the sql statement, also note that java is case sensitive.
in JSP do something like
<%
ObsDao dao = new ObsDao();
ObsDao otherdao = new ObsDao();
otherdao.setCompanyName("My company")
List<ObsBean> ComNotify = dao.getComNotify(otherdao);
for (ObsBean UserNotifi : ComNotify) {
.........
.........
}
%>
In your Dao class, there should be getter method for CompanyName. So try following code:
STRING COM = Comname; ,<-- change this line to String COM=Comname.getCompanyName();

java.sql.SQLException: Invalid value for getInt() - 'Glomindz Support'

I am not able to retrieve column values from my database table with the following coding a message has been displayed in the console:
java.sql.SQLException: Invalid value for getInt() - 'Glomindz Support'
My code is:
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public void get_all_data() {
}
public Map<Integer, String> get_all_data1() {
HashMap<Integer, String> result = new HashMap<Integer, String>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
result.put(resultSet.getInt(1), resultSet.getString("id"));
result.put(resultSet.getInt(2), resultSet.getString("name"));
result.put(resultSet.getInt(3), resultSet.getString("email"));
result.put(resultSet.getInt(4), resultSet.getString("mobile"));
result.put(resultSet.getInt(5), resultSet.getString("password"));
result.put(resultSet.getInt(6), resultSet.getString("role"));
result.put(resultSet.getInt(7), resultSet.getString("status"));
result.put(resultSet.getInt(8),
resultSet.getString("last_update"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
new UserServicesDAO().get_all_data1();
}
}
My db table schema is:
id name email mobile password role status last_update
1 Glomindz Support support#glomindz.com 9854087006 cbf91a71c11d5ec348b0c7e9b2f0055e admin 1 2013-05-02 22:05:14
2 Amarjyoti Das amarjyotidas#splcare.com 9864092598 88f2dccb02b2a20615211e5492f85204 admin 1 2013-04-26 05:44:41
You retrieve every column as an int for the key. I assume that some of these columns represent Strings or Dates.
while(resultSet.next()){
result.put(resultSet.getInt(1),resultSet.getString("id"));
result.put(resultSet.getInt(2),resultSet.getString("name")); //Most likely a String
result.put(resultSet.getInt(3),resultSet.getString("email"));
result.put(resultSet.getInt(4),resultSet.getString("mobile"));
result.put(resultSet.getInt(5),resultSet.getString("password"));
result.put(resultSet.getInt(6),resultSet.getString("role"));
result.put(resultSet.getInt(7),resultSet.getString("status"));
result.put(resultSet.getInt(8),resultSet.getString("last_update")); //Most likely a date
}
The inconsistencies between the data types and the object/value returned by the getInt() method causes the error. I would suggest building/modeling an object in your domain that stores rows from the table. Something like:
public class User{
private Integer id;
private String name;
private String email;
private String mobile;
private String password;
private String role;
private String status;
private Date lastUpdate;
/* Get and set methods for each field */
}
Then build a Map containing the object as the value and the id as the key:
//Use Map interface here, also notice generic arguments <Integer,User>
Map<Integer, User> result = new HashMap<Integer, User>();
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while(resultSet.next()){
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name");
user.setEmail(resultSet.getString("email");
//do this for each field, using appropriate method for type...
//then add to map
result.put(user.getId(), user);
}
I think you need all your data from the table as a Map. But you may have multiple rows in your DB, therefore you basically want a list of maps! Modify your method to something like this:-
public List<Map<Integer, String>> get_all_data1() {
List<Map<Integer, String>> allRows = new ArrayList<Map<Integer, String>>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
Map<Integer, String> result = new HashMap<Integer, String>();
result.put(1, resultSet.getString("id"));
result.put(2, resultSet.getString("name"));
result.put(3, resultSet.getString("email"));
result.put(4, resultSet.getString("mobile"));
result.put(5, resultSet.getString("password"));
result.put(6, resultSet.getString("role"));
result.put(7, resultSet.getString("status"));
result.put(8, resultSet.getString("last_update"));
allRows.add(result);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allRows;
}
Here, for every fetched record from the DB, the columns are put into the Map, and each map, represents a row, which is added to a List!
If you are using JPA annotations to map entity fields with db table, you need to use #Enumerated(EnumType.STRING) annotation on ENUM type entity fields.
This error is due to, while creating the table you may mentioned name column as INTEGER. So while retrieving it will get that column using getInt() method. But actually the column is of type STRING.
U should change the datatype of name column to STRING and this issue will be fixed automatically.
According to documentation, getInt() or getString() requires columnIndex or columnLabel to get value for that column in particular entry. To find the column index you need to use findColumn(name) method to get its columnIndex. So your code should be as follows:
while (resultSet.next()) {
result.put(resultSet.findColumn("id"), resultSet.getInt("id"));
result.put(resultSet.findColumn("name"), resultSet.getString("name"));
result.put(resultSet.findColumn("email"), resultSet.getString("email"));
result.put(resultSet.findColumn("mobile"), resultSet.getInt("mobile"));
result.put(resultSet.findColumn("password"), resultSet.getString("password"));
result.put(resultSet.findColumn("role"), resultSet.getString("role"));
result.put(resultSet.findColumn("status"), resultSet.getInt("status"));
result.put(resultSet.findColumn("last_update"),
resultSet.getString("last_update"));
}
Basically you need to get your values according to the datatype with which it had been saved in DB. Check available methods to retrieve values by Ctrl+Click on ResultSet class
Please check the syntax error for a small mistake for comma(,) you are added before the select statement
Example:
select id, name, mobile, address from table_name;
but you are using like
select id, name, mobile, address, from table_name;
please check and correct it

Categories

Resources