I'm trying to make a notice board and before apply paging function it showed posts well.
but after i applied paging fuction it shows only one post and paging function shows pages well.
so i think this is a sql problem.
when i try to show count it shows 1. even i tried with this shows 1.
sql = "select * from mvc_board ";
this is my sql
String sql = "SELECT ROWNUM, bId, bName, bTitle, bContent," +
"bDate, bHit, bGroup, bStep, bIndent " +
"from(select * from mvc_board order by bGroup DESC , bStep asc)";
i tried to make mine from this sql. but couldn't understand.
sql = "select *, (select u_name from user where idx = writer_fk) writer, (select idx from answer where idx = answer_fk) answer from board order by idx desc limit "+startRow+", "+endRow;
ref. http://queserasera.tistory.com/14
this is DAO
public ArrayList<BDto> getBoardList(int startRow, int endRow, String keyField, String keyWord) {
ArrayList<BDto> dtos = new ArrayList<BDto>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "SELECT ROWNUM, bId, bName, bTitle, bContent," +
"bDate, bHit, bGroup, bStep, bIndent " +
"from(select * from mvc_board order by bGroup DESC , bStep asc)";
System.out.println(sql);
try{
if(keyWord != null && !keyWord.equals("") && !keyWord.equals("null")) {
sql += " WHERE " + keyField.trim() +" LIKE '%"+keyWord.trim()+"%'";
}
connection = dataSource.getConnection();
//특정행부터 레코드를 가져오기 위해서 옵션 설정
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
int count=0;
int ROWNUM = resultSet.getInt("ROWNUM");
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
BDto dto = new BDto(ROWNUM, bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
dtos.add(dto);
count++;
System.out.println(count);
//while문끝
}//if문끝
}catch (Exception e) {
System.out.println(e+"=> getBoardList fail");
}finally {
try {
if(resultSet != null) resultSet.close();
if(preparedStatement != null) preparedStatement.close();
if(connection != null) connection.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
return dtos;
}
=============added sql on sql developer==================================
select rn, bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent
from ( select b.*, row_number() over (order by bGroup DESC, bStep asc) rn
from mvc_board b %s )
where rn between 1 and 10
order by rn;
The main problem in your getBoardList() method was the usage of if (resultSet.next()) instead of while (resultSet.next()) when iterating through the result set; that caused the code to only ever return a single DTO.
There are other things you should also consider. For example, starting from Java 7, it's preferrable to use the try-with resources statement instead of traditional try-finally for JDBC resource handling.
An important thing to note is that injecting field names like keyField from the UI is a really bad practice because it makes the query vulnerable to SQL injection.
You should at least create a static whitelist of allowed field names to sanitize the input, if you cannot use static WHERE conditions.
Finally, paging queries in Oracle 11g are traditionally done with an inline view that uses the row_number analytic function. Note that row-numbering starts from 1. Starting from Oracle 12c, the row-limiting clause can be used and the inline view is no longer needed.
An example implementation that considers the above points could look like the following:
public List<BDto> getBoardList(int startRow, int endRow, String keyField, String keyWord) {
List<BDto> dtos = new ArrayList<BDto>();
// the %s in the template will be replaced with a
// WHERE condition when a keyword is present
final String sqlTemplate = "select rn, bId, bName, bTitle, "
+ "bContent, bDate, bHit, bGroup, bStep, bIndent "
+ "from ( "
+ " select b.*, row_number() over (order by bGroup DESC, bStep asc) rn"
+ " from mvc_board b %s "
+ " ) "
+ " where rn between ? and ? "
+ "order by rn";
boolean whereCondition = false;
String sql = null;
if (keyWord != null && !keyWord.equals("") && !keyWord.equals("null")) {
sql = String.format(sqlTemplate,
" WHERE " + keyField.trim() + " LIKE '%' || ? || '%'");
whereCondition = true;
} else {
sql = String.format(sqlTemplate, "");
}
System.out.println(sql);
try (Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int parameterIndex = 1;
if (whereCondition) {
preparedStatement.setString(parameterIndex++, keyWord);
}
preparedStatement.setInt(parameterIndex++, startRow);
preparedStatement.setInt(parameterIndex, endRow);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
int count = 0;
while (resultSet.next()) {
int ROWNUM = resultSet.getInt("rn");
int bId = resultSet.getInt("bId");
String bName = resultSet.getString("bName");
String bTitle = resultSet.getString("bTitle");
String bContent = resultSet.getString("bContent");
Timestamp bDate = resultSet.getTimestamp("bDate");
int bHit = resultSet.getInt("bHit");
int bGroup = resultSet.getInt("bGroup");
int bStep = resultSet.getInt("bStep");
int bIndent = resultSet.getInt("bIndent");
dtos.add(new BDto(ROWNUM, bId, bName, bTitle,
bContent, bDate, bHit, bGroup, bStep, bIndent));
count++;
}
System.out.println(count);
}
} catch (SQLException e) {
System.out.println(e + "=> getBoardList fail");
}
return dtos;
}
In the example you gave us the paging is added by the limit clause, but ORACLEhas it's own syntax for these. Try:
String sql = "SELECT rown, bId, bName, bTitle, bContent," +
"bDate, bHit, bGroup, bStep, bIndent " +
"from(select rownum rown, mvc_board.* from mvc_board order by bGroup DESC , bStep asc) " +
"WHERE rown between ? and ? ";
Bind startRow and endRow before executing the query:
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,startRow);
preparedStatement.setInt(2,endRow);
resultSet = preparedStatement.executeQuery();
Change the WHERE to AND:
sql +=" and " + keyField.trim()+" LIKE '%"+keyWord.trim()+"%'" ;
And finally change the if(resultSet.next()){ back to a while loop to get more then one row as result.
Related
I have loaded millions of rows of data from 5 tables in database. I want to display the loaded data into a tableview. It takes a long time to load all the records(sometimes all of them don't fit into memory). I want to make it so that I can load a resultSet, display it, load a second one, and so on. Is this possible? My code as of now:
#FXML
private TableView<Vysledok_hladania> table;
#FXML
private TableColumn<Vysledok_hladania, String> Nazov_hotela, Adresa, Krajina, Mesto, Hviezdicky, Cena, Typ_izby, Pocet_izieb;
#FXML
void vyhladajInfo(ActionEvent event){
table.getItems().clear();
try {
Connection con = Runner.getConnection();
con.setAutoCommit(false);
String query = "SELECT h.\"Nazov hotela\", k.\"Nazov krajiny\", m.\"Nazov mesta\", h.\"Adresa hotela\", h.\"Hviezdicky\", p.\"Cena pobytu\", i.\"Typ izby\", h.\"Pocet izieb\" FROM hotel h " +
"inner JOIN izba i ON i.\"ID hotela\" = h.\"ID hotela\" " +
"inner JOIN krajina k ON k.\"ID krajiny\" = h.\"ID krajiny\" " +
"inner JOIN mesto m ON m.\"ID mesta\" = h.\"ID mesta\" " +
"inner JOIN pobyt p ON p.\"ID hotela\" = h.\"ID hotela\" " +
"WHERE h.\"Nazov hotela\" = ? " +
"AND k.\"Nazov krajiny\" = ? " +
"AND h.\"Hviezdicky\" = ? " +
"AND i.\"Pocet posteli\" >= ? " +
"AND p.\"Cena pobytu\" <= ? ";
//"AND p.\"Datum od\" = ? " +
//"AND p.\"Datum do\" <= ?";
int i = 1;
PreparedStatement pst = con.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
pst.setFetchSize(50);
pst.setString(1,Text_nazov.getText());
pst.setString(2,(String)krajina.getValue());
int pocet_hviezdiciek = Integer.parseInt((String)hviezdicky.getValue());
pst.setInt(3,pocet_hviezdiciek);
int pocet_osob = Integer.parseInt((String)osoby.getValue());
pst.setInt(4, pocet_osob);
double cena_pobytu = Double.parseDouble(Text_cena.getText());
pst.setDouble(5, cena_pobytu);
// Date datum_OD = Date.valueOf(date_od.getValue());
// pst.setDate(6, datum_OD);
// Date datum_DO = Date.valueOf(date_do.getValue());
// pst.setDate(7, datum_DO);
ResultSet rs = pst.executeQuery();
System.out.println(pst);
Nazov_hotela.setCellValueFactory(new PropertyValueFactory<>("Meno_hotela"));
Krajina.setCellValueFactory(new PropertyValueFactory<>("Krajina"));
Mesto.setCellValueFactory(new PropertyValueFactory<>("Mesto"));
Adresa.setCellValueFactory(new PropertyValueFactory<>("Adresa"));
Hviezdicky.setCellValueFactory(new PropertyValueFactory<>("Hviezdicky"));
Cena.setCellValueFactory(new PropertyValueFactory<>("Cena"));
Typ_izby.setCellValueFactory(new PropertyValueFactory<>("Typ_izby"));
Pocet_izieb.setCellValueFactory(new PropertyValueFactory<>("Pocet_izieb"));
while(rs.next()){
oblist.add(new Vysledok_hladania(rs.getString("Nazov hotela"),
rs.getString("Nazov krajiny"),
rs.getString("Nazov mesta"),
rs.getString("Adresa hotela"),
rs.getInt("Hviezdicky"),
rs.getDouble("Cena pobytu"),
rs.getString("Typ izby"),
rs.getInt("Pocet izieb")));
System.out.println(i++);
}
rs.close();
pst.close();
con.close();
} catch(SQLException ex){
Logger.getLogger(Result_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
table.setItems(oblist);
}
How to make this one work? Obviously I don't know some very basic staff about SQL queries inside other SQL queries in Java but searching around didn't help!
Thank you in advance
try (Connection con = L2DatabaseFactory.getInstance().getConnection())
{
PreparedStatement stm = con.prepareStatement("SELECT count,owner_id FROM items WHERE item_id=57 order by count desc limit 10");
ResultSet rSet = stm.executeQuery();
while (rSet.next())
{
int owner_id = rSet.getInt("owner_id");
int count = rSet.getInt("count");
if (count == 0)
{
continue;
}
PreparedStatement stm1 = con.prepareStatement("SELECT char_name,accesslevel,online FROM characters WHERE obj_Id=" + owner_id);
ResultSet rSet1 = stm1.executeQuery();
while (rSet1.next())
{
int accessLevel = rSet.getInt("accesslevel");
if (accessLevel > 0)
{
continue;
}
String pl = rSet.getString("char_name");
int online = rSet.getInt("online");
String status = online == 1 ? "<font color=\"00FF00\">Online</font>" : "<font color=\"FF0000\">Offline</font>";
sb.append("<tr><td>"+ pl +"</td><td>"+ count +"</td><td>"+ status +"</td></tr>");
}
}
}
catch (Exception e)
{
_log.log(Level.SEVERE, "Error", e);
}
It looks like you are trying to join two tables using Java code. This is not such a great idea and not good for performance. Let the database do the joins for you - it is an expert at that. Do not code "inner joins" in Java.
Apart from that: the prepared statements are not being closed and this will sooner or later cause you trouble with OS resources.
My suggestion would be to create one single query with an inner join or a select in statement and also close all prepared statements using try with resources. Something along these lines:
private String test() throws SQLException {
StringBuilder sb = new StringBuilder();
int count = 0;
try (Connection con = L2DatabaseFactory.getInstance().getConnection()) {
try (PreparedStatement stm1 = con.prepareStatement(
"SELECT char_name,accesslevel,online FROM characters WHERE obj_Id in (SELECT owner_id FROM items WHERE item_id=57 order by count desc limit 10)")) {
ResultSet rSet = stm1.executeQuery();
while (rSet.next()) {
count++;
int accessLevel = rSet.getInt("accesslevel");
if (accessLevel > 0) {
continue;
}
String pl = rSet.getString("char_name");
int online = rSet.getInt("online");
String status = online == 1 ? "<font color=\"00FF00\">Online</font>" : "<font color=\"FF0000\">Offline</font>";
sb.append("<tr><td>" + pl + "</td><td>" + count + "</td><td>" + status + "</td></tr>");
}
}
} catch (Exception e) {
Logger.getLogger("test").log(Level.SEVERE, "Error", e);
}
return sb.toString();
}
I have problem with SQL query in JAVA.
JAVA code:
public boolean zeKontrolaExistujiciZalohyTest(String datum) {
try {
connected();
boolean existujeZaloha = false;
int pocet;
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
rs.next();
pocet = rs.getInt(1);
rs.close();
closed();
if (pocet >= 0) {
existujeZaloha = true;
} else {
existujeZaloha = false;
}
return existujeZaloha;
} catch (Exception e) {
e.printStackTrace();
Dialogs.create()
.title("Exception Dialog")
.showException(e);
return true;
}
}
SQL query in SQL Developer:
SELECT count(id) FROM pbtest.u_zalohy_energie
WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('15.09.2014', 'dd.mm.yyyy'), 'mm.yyyy');
When I run JAVA code, so result a variable is "pocet = 0". But, when I run SQL query in any the SQL Developer, so result column COUNT(id) is "1".
When I do change the SQL query, let me run JAVA code retuns a variable "pocet = 1".
Change sql code:
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE datum = TO_DATE('"+datum+"', 'dd.mm.yyyy')");
Does anyone know where is the problem?
For information: I use an Oracle database.
Thank you.
datum is string
SELECT count(id)
FROM pbtest.u_zalohy_energie
WHERE TO_DATE(datum, 'dd.mm.yyyy') = TO_DATE('15.09.2014', 'dd.mm.yyyy');
datum is date
SELECT count(id)
FROM pbtest.u_zalohy_energie
WHERE TRUNC(datum) = TO_DATE('15.09.2014', 'dd.mm.yyyy');
If datum is date, it might contain time component too. So remove it. using TRUNC()
TRUNC(datum) = TO_DATE('15.09.2014', 'dd.mm.yyyy');
Java code:
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TRUNC(datum) = TO_DATE('"+datum+"', 'dd.mm.yyyy')");
As a side note, use PreparedStatement and bind variables to avoid SQL*Injection
Your statement has a syntax error
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
the executed query would be
SELECT count(id) FROM pbtest.u_zalohy_energie\nWHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('15.09.2014'', 'dd.mm.yyyy'), 'mm.yyyy')")
You should remove the "\n" as this will not lead in a line break.
Try it as
ResultSet rs = statement.executeQuery("SELECT count(id) FROM " + table_ze
+ " WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
Take also into consideration the comment from Maheswaran Ravisankar about: "... PreparedStatement and bind variables to avoid SQL*Injection"
Thank you for your advice, I solved the problem as follows:
public boolean zeKontrolaExistujiciZalohy(String datum, String typZalohy, String zalohaNaMesic) {
connected();
boolean existujeZaloha = false;
int pocet = 0;
ResultSet rs;
PreparedStatement pstmt = null;
try{
statement = connection.createStatement();
String SQL = "SELECT count(id) AS pocet FROM " + table_ze + " WHERE (EXTRACT(MONTH FROM datum)) = (EXTRACT(MONTH FROM to_date(?, 'dd.mm.yyyy'))) "
+ "AND (EXTRACT(YEAR FROM datum)) = (EXTRACT(YEAR FROM to_date(?, 'dd.mm.yyyy')))"
+ "AND typ_zalohy = ? "
+ "AND zaloha_na_mesic = ? ";
pstmt = connection.prepareStatement(SQL);
pstmt.setString(1, datum);
pstmt.setString(2, datum);
pstmt.setString(3, typZalohy);
pstmt.setString(4, zalohaNaMesic);
rs = pstmt.executeQuery();
while(rs.next()){
pocet = rs.getInt("pocet");
}
rs.close();
if (pocet > 0) {
existujeZaloha = true;
} else {
existujeZaloha = false;
}
return existujeZaloha;
}
catch(SQLException ex){
Dialogs.create()
.title("Exception Dialog")
.showException(ex);
return true;
}
}
I am studying Hibernate and in a exercise I must do this query
"SELECT count(id) as numero_utenti, imc
FROM Utenti
WHERE azienda = '" + id + "' GROUP BY imc"
the problem is that, I don't know as view the result and to save the result in a string.
Thanks.
This is the function
public String getStat(int id) {
String stat = "";
int count = 0;
try {
Query query = session.createQuery("SELECT count(id) as numero_utenti, imc FROM Utenti WHERE azienda = '" + id + "' GROUP BY imc");
// as I extract the values?
tx.commit();
} catch (HibernateException he) {
throw he;
}
return stat;
}
If you are looking how to execute query using hibernate session.
query = session.createQuery("semect * from temp");
and query instance
Long.valueOf(query.fetchCountOfRows()).intValue();
It'll give you no. row count.
If they are not unique, get the list.
List<String> imcs= null;
int count = 0;
Query query = session.createQuery("SELECT imc FROM Utenti WHERE azienda = '" + id + "' GROUP BY imc");
imcs = query.list();
count = imcs.size();
I have this weird problem in java when trying to fetch records from MYSql database by using the limit function in the query. Not sure what went wrong or did wrong, this query is giving me a hard time.
Issue - When I run this query through my java program it returns all the records and not limiting the records to 10 as given in the limit.
The same query when ran in MYSql command line, it execute very well and fetches me only 10 recrods.
Below is the java code and query. Any help or support is appreciated.!
Java code -
public UserVO getApplUserDetailsList(UserVO userVO) throws CAPDAOException {
List<UserVO> returnList = null;
String methodName = "getApplUserDetails()";
Session session = null;
String queryString = null;
Transaction transaction = null;
PreparedStatement ps = null;
ResultSet rs = null;
if(userVO == null)
{
logger.writeToTivoliAlertLog(className, CAPConstants.ERROR, methodName, null, "userVO returned null. Busines validation error.!", null);
throw new CAPDAOException("userVO returned null. Busines validation error.!",CAPException.BUSINESS_VALIDATION_ERROR_SECURITY);
}
try {
returnList = new ArrayList<UserVO>();
System.out.println("");
String appusr = userVO.getAppUsrNm();
session = getSession();
transaction = session.beginTransaction();
if(userVO.getAppUsrRoleCd()!=null && !userVO.getAppUsrRoleCd().trim().equalsIgnoreCase(CAPConstants.DEFAULT_DROPDOWN_VALUE)){
queryString = "SELECT " +
"APPL_USR_ID,APPL_USR_NM,APPL_USR_FRST_NM, " +
"APPL_USR_LST_NM,ACCESS_ROLE_CD " +
"FROM APPL_USR " +
"WHERE " +
"APPL_USR_NM LIKE ?"+
" AND APPL_USR_FRST_NM LIKE ?"+
" AND APPL_USR_LST_NM LIKE ?"+
" AND ACCESS_ROLE_CD = ?"+
" AND APPL_USR_ID != ?";
ps = session.connection().prepareStatement(queryString);
ps.setString(1,userVO.getAppUsrNm()+CAPConstants.PERCENTILE_SYMBOL);
ps.setString(2,userVO.getAppUsrFirstNm()+CAPConstants.PERCENTILE_SYMBOL);
ps.setString(3,userVO.getAppUsrLastNm()+CAPConstants.PERCENTILE_SYMBOL);
ps.setString(4,userVO.getAppUsrRoleCd());
ps.setInt(5, 1);
}
else
{
queryString = "SELECT " +
"APPL_USR_ID,APPL_USR_NM,APPL_USR_FRST_NM, " +
"APPL_USR_LST_NM,ACCESS_ROLE_CD " +
"FROM APPL_USR " +
"WHERE " +
"APPL_USR_NM LIKE ?"+
" AND APPL_USR_FRST_NM LIKE ?"+
" AND APPL_USR_LST_NM LIKE ?"+
" AND APPL_USR_ID != ?";
ps = session.connection().prepareStatement(queryString);
ps.setString(1,userVO.getAppUsrNm()+CAPConstants.PERCENTILE_SYMBOL);
ps.setString(2,userVO.getAppUsrFirstNm()+CAPConstants.PERCENTILE_SYMBOL);
ps.setString(3,userVO.getAppUsrLastNm()+CAPConstants.PERCENTILE_SYMBOL);
ps.setInt(4, 1);
}
if(userVO.getQueryAction()!=null && userVO.getQueryAction().equals(CAPConstants.GET_DATA))
queryString += " ORDER BY APPL_USR_ID LIMIT " + userVO.getPAGE_MIN_LIMIT() + ", " + userVO.getPAGE_MAX_LIMIT();
else
queryString += " ORDER BY APPL_USR_ID";
rs = ps.executeQuery();
if(userVO.getQueryAction()!=null && userVO.getQueryAction().equals(CAPConstants.GET_DATA))
{
int tempCOunt = 0;
while(rs!=null && rs.next())
{
tempCOunt ++;
UserVO returnVO = new UserVO();
returnVO.setAppUsrId(rs.getInt("APPL_USR_ID"));
returnVO.setAppUsrNm(rs.getString("APPL_USR_NM"));
returnVO.setAppUsrFirstNm(rs.getString("APPL_USR_FRST_NM"));
returnVO.setAppUsrLastNm(rs.getString("APPL_USR_LST_NM"));
if (rs.getString("ACCESS_ROLE_CD")!=null && rs.getString("ACCESS_ROLE_CD").trim().equalsIgnoreCase(CAPConstants.ADMINISTRATOR_ROLE_CD))
returnVO.setApplicationLevelRole("Administrator");
else if (rs.getString("ACCESS_ROLE_CD")!=null && rs.getString("ACCESS_ROLE_CD").trim().equalsIgnoreCase(CAPConstants.MAINTAINER_ROLE_CD))
returnVO.setApplicationLevelRole("Maintainer");
else if (rs.getString("ACCESS_ROLE_CD")!=null && rs.getString("ACCESS_ROLE_CD").trim().equalsIgnoreCase(CAPConstants.VIEWER_ROLE_CD))
returnVO.setApplicationLevelRole("Viewer");
else
returnVO.setApplicationLevelRole("None");
returnList.add(returnVO);
}
System.out.println("Count >>>>>>>>>>>>>>>>>>> "+tempCOunt);
userVO.setReturnListFromDB(returnList);
}
else
{
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
userVO.setTotalRecordCount(rowcount);
System.out.println("Total count of the records to be used for pagination >> "+rowcount);
rowcount = 0;
while(rs!=null && rs.next())
{
rowcount ++;
UserVO returnVO = new UserVO();
returnVO.setAppUsrId(rs.getInt("APPL_USR_ID"));
returnVO.setAppUsrNm(rs.getString("APPL_USR_NM"));
returnVO.setAppUsrFirstNm(rs.getString("APPL_USR_FRST_NM"));
returnVO.setAppUsrLastNm(rs.getString("APPL_USR_LST_NM"));
if (rs.getString("ACCESS_ROLE_CD")!=null && rs.getString("ACCESS_ROLE_CD").trim().equalsIgnoreCase(CAPConstants.ADMINISTRATOR_ROLE_CD))
returnVO.setApplicationLevelRole("Administrator");
else if (rs.getString("ACCESS_ROLE_CD")!=null && rs.getString("ACCESS_ROLE_CD").trim().equalsIgnoreCase(CAPConstants.MAINTAINER_ROLE_CD))
returnVO.setApplicationLevelRole("Maintainer");
else if (rs.getString("ACCESS_ROLE_CD")!=null && rs.getString("ACCESS_ROLE_CD").trim().equalsIgnoreCase(CAPConstants.VIEWER_ROLE_CD))
returnVO.setApplicationLevelRole("Viewer");
else
returnVO.setApplicationLevelRole("None");
returnList.add(returnVO);
System.out.println("Row count >>"+rowcount);
if(rowcount == CAPConstants.PAGINATION_MAX_VALUE)
break;
}
rowcount = 0;
userVO.setReturnListFromDB(returnList);
}
System.out.println("returnList >>"+returnList);
return userVO;
} catch (Throwable e) {
e.printStackTrace();
logger.writeToTivoliAlertLog(className, CAPConstants.ERROR, methodName, userVO.getAppUsrNm(), "Error occured while trying to fetch application user details. Printing stack trace to the log for analysis..", e);
throw new CAPDAOException("Error occured while trying to fetch application user details.",CAPException.SPEXECUTION_ERROR_CODE);
}
finally{
closeTransactionAndSession(session,transaction);
}
}
MYSQL Query -
SELECT APPL_USR_ID,APPL_USR_NM,APPL_USR_FRST_NM, APPL_USR_LST_NM,ACCESS_ROLE_CD
FROM APPL_USR WHERE APPL_USR_NM LIKE '%'
AND APPL_USR_FRST_NM LIKE '%'
AND APPL_USR_LST_NM LIKE '%'
AND APPL_USR_ID != 1
ORDER BY APPL_USR_ID
LIMIT 10, 10
you add your LIMIT after
ps = session.connection().prepareStatement(queryString);
so when calling
rs = ps.executeQuery();
the LIMIT is not in there.
So, call prepareStatement when the queryString construction is finished.
You are changing the querystring after you have prepared the statement with the string.