I don't understand why in this code, it's do that:
query.setString("idFamilleDeProduit", String.valueOf(familleDeProduits.getFamilleDeProduitsGenerique().getId()));
When I looked my table in my database, id column is integer.
it's PostgreSql-9.4.1207
my function:
public List<ContratMdd> recherchePourDuplication(String typeAccord, FamilleDeProduitsNomenclature familleDeProduits, SocieteInterne societeInterne, SocieteExterne societeExterne, String anneeAccord) throws PersistenceException {
List<ContratMdd> listContratMdd = new ArrayList<ContratMdd>();
String requete = "";
if (!"".equals(anneeAccord)){
requete += " anneeAccord = :anneeAccord";
}
if (!"".equals(typeAccord) && ! "".equals(requete)){
requete += " AND";
}
if (!"".equals(typeAccord)){
requete += " type = :type";
}
boolean existFamille = false;
requete += (familleDeProduits != null && familleDeProduits.getFamilleDeProduitsGenerique() != null) ? " AND " : "";
if(familleDeProduits != null && familleDeProduits.getFamilleDeProduitsGenerique() != null){
existFamille = true;
requete += " estAppliqueSur.familleDeProduitsGenerique IS NOT NULL AND estAppliqueSur.familleDeProduitsGenerique.id = :idFamilleDeProduit";
}
boolean existSocieteInterne = false;
boolean existSocieteExterne = false;
requete += (societeInterne != null) ? " AND " : "";
if(societeInterne != null){
existSocieteInterne = true;
String table = societeInterne instanceof Master ? "MasterImpl" : "AdherentImpl";
requete += " contractantInterne.id = :idsocieteInterne AND contractantInterne IN (FROM "+table+") ";
}
requete += (societeExterne != null) ? " AND " : "";
if(societeExterne!=null){
existSocieteExterne = true;
String table = societeExterne instanceof GroupeIndustriel ? "GroupeIndustrielImpl" : "FournisseurImpl";
requete += " contractantExterne.id = :idsocieteExterne AND contractantExterne IN (FROM "+table+") ";
}
if (!"".equals(requete)) {
requete = "from ContratMddImpl where" + requete;
Query query = createQuery(requete);
if (!"".equals(anneeAccord)){
query.setBigInteger("anneeAccord", new BigInteger(anneeAccord));
}
if (!"".equals(typeAccord)){
query.setString("type", typeAccord);
}
if(existFamille){
query.setString("idFamilleDeProduit", String.valueOf(familleDeProduits.getFamilleDeProduitsGenerique().getId()));
}
if (existSocieteInterne){
query.setInteger("idsocieteInterne", societeInterne.getId());
}
if (existSocieteExterne){
query.setInteger("idsocieteExterne", societeExterne.getId());
}
listContratMdd.addAll((List<ContratMdd>) query.list());
}
return listContratMdd;
}
It is happening because the Postgre's DB Driver allows it. But you should be using setInt() instead of setString() for an Integer as other DB Drivers might not support it.
Here is what java.sql.PreparedStatement Documentation has to say:
Note: The setter methods (setShort, setString, and so on) for setting
IN parameter values must specify types that are compatible with the
defined SQL type of the input parameter. For instance, if the IN
parameter has SQL type INTEGER, then the method setInt should be used.
Related
I have some Java code that runs an SQL query like this:
SELECT DISTINCT ven.enterprise_network_id, st.*
FROM studies st
inner join v_enterprise_network_members ven on st.ib_id = my_ib_id
WHERE ven.ib_id=:IB_ID
AND (st.myvrn_expiration_date IS NULL OR st.myvrn_expiration_Date >= sysdate)
ORDER BY st.study_date DESC
I understand everything except I don't understand what st.ib_id=my_ib_id. What does it mean? This is the whole method just in case if it helps:
public List<Study> searchRepository(StudySearchCriteria criteria, boolean isEnterpriseNetwork,
boolean isExactNameMatch) {
String selectForNone = null;
String studyStatus = null;
studyStatus = verifyStudyStatus(criteria, studyStatus, isEnterpriseNetwork);
if (criteria.contains(SearchField.STUDY_STATUS) && StringUtils.isBlank(studyStatus)) {
return new ArrayList<>();
}
if (StringUtils.isNotBlank(studyStatus) && studyStatus.contains(StudyPacsState.State.NONE.toString())) {
selectForNone = "DISTINCT {st.*}, st.study_date as stdate FROM studies st";
}
StringBuffer select = new StringBuffer(512);
StringBuffer where = new StringBuffer(512);
StringBuffer orderBy = new StringBuffer(selectForNone != null ? "" : " ORDER BY st.study_date DESC ");
select.append("SELECT ");
if (criteria.containsWildcard()) {
select.append(queryHint);
}
if (!isEnterpriseNetwork) {
select.append(selectForNone != null ? selectForNone : "DISTINCT {st.*} FROM studies st");
where.append(" WHERE st.ib_id=:IB_ID AND ").append(myVrnSql);
}
else {
///////////////////////////////////// HERE IS WHERE my_ib_id is
select.append("DISTINCT ven.enterprise_network_id, {st.*} FROM studies st")
.append(" inner join v_enterprise_network_members ven on st.ib_id=my_ib_id ");
/////////////////////////////////////
where.append(" WHERE ven.ib_id=:IB_ID AND ").append(myVrnSql);
}
StringBuilder queryForNone = selectForNone != null ? new StringBuilder(" UNION ") : new StringBuilder(" ");
createStudyStatusQuery(criteria, isExactNameMatch, studyStatus, where, queryForNone, false);
buildStudyQuery(criteria, select, where, orderBy, isEnterpriseNetwork, isExactNameMatch, true, false);
if (criteria.contains(SearchField.STUDY_STATUS)) {
select.append(" , smr_study_pacs_state sps ");
}
SQLQuery sq = null;
Query hq = null;
if (isEnterpriseNetwork) {
sq = getSession().createSQLQuery(select.toString() + where.toString());
sq.addEntity("st", Study.class).addScalar("enterprise_network_id", StandardBasicTypes.LONG)
.setCacheable(false).setCacheRegion("vrnstudysearch");
}
else {
sq = getSession().createSQLQuery(select.toString() + where.toString() + queryForNone.toString());
sq.addEntity("st", Study.class).setCacheable(false).setCacheRegion("vrnstudysearch");
if (selectForNone != null) {
sq.addScalar("stdate", StandardBasicTypes.TIMESTAMP);
}
}
hq = sq;
hq.setLong(SearchField.IB_ID.toString(), (Long) criteria.get(SearchField.IB_ID));
supplyParameters(criteria, hq, isExactNameMatch);
logger.info("Query searchRepository {}", hq.getQueryString());
List<Study> result = null;
if (!isEnterpriseNetwork) {
if (selectForNone != null) {
List<?> returned = hq.list();
if (returned != null) {
result = new ArrayList<Study>();
for (Object n : returned) {
Object[] tuple = (Object[]) n;
Study st = (Study) tuple[0];
result.add(st);
}
}
}
else {
result = hq.list();
}
}
else {
List<?> returned = hq.list();
if (returned != null) {
result = new ArrayList<Study>();
for (Object n : returned) {
Object[] tuple = (Object[]) n;
Study st = (Study) tuple[0];
st.setEnterpriseNetworkId((Long) tuple[1]);
result.add(st);
}
}
}
logger.debug(" returned " + (result == null ? 0 : result.size()));
return result;
}
st.ib_id=my_ib_id is the join condition - it defines the relationship between the two tables you are joining in the query. Presumably, my_ib_id is a column in one of those tables.
I'm using a spring framework and the code I'm using won't work or check if the query is null, though I used a .isEmpty() method it doesn't mean that the query is empty. I wanted to make sure that my query is empty because a part of my code does invoke an id in which case I didn't even though its null so please help me T.T
public List<Object> searchEmployee(EmployeeSearchDto data) {
Session session = sessionFactory.openSession();
final String CRITERIA_EMPLOYEEID = "emp.employeeID =:id";
final String CRITERIA_EMPLOYEEID2 = "emp.employeeID LIKE:id";
final String CRITERIA_POSITION= "emp.positionID =:posID";
final String CRITERIA_DEPARTMENT="emp.departmentID =:deptID";
final String CRITERIA_WORKPLACE = "emp.workplaceID =:workID";
Boolean selected_dept = false;
Boolean selected_pos = false;
Boolean selected_work = false;
Boolean input_empID = false;
Boolean input_empName = false;
firstName = "";
middleName = "";
lastName = "";
completeName = "";
firstLastName = "";
List<String> criteria = new ArrayList<>();
List<Object> employees = null;
// checking the fields if all the fields is empty
try{
//one by one check the select field
String query = "Select"
+ " emp.employeeID,"
+"emp.firstName,"
+"emp.middleName,"
+"emp.lastName,"
+"pos.positionName,"
+"dept.deptName,"
+"work.workplaceName"
+"from Employee emp "
+ "INNER JOIN Department dept "
+ "ON emp.departmentID = dept.deptID "
+ "INNER JOIN Position pos "
+ "ON emp.positionID = pos.positionID "
+ "INNER JOIN Workplace work "
+ "ON emp.workplaceID = work.workplaceID ";
if(!data.isEmpty()) {
query = query.concat("WHERE ");
if(data.getEmployeeID()!="" && data.getEmployeeID()!=null) {
criteria.add(CRITERIA_EMPLOYEEID2);
System.out.println("Employee IDs");
input_empID = true;
}
if(data.getEmployeeName()!="" && data.getEmployeeName()!=null){
criteria.add(nameCriteriaHelper(data.getEmployeeName()));
System.out.println("Employee Name AKOOO");
input_empName = true;
}
if(data.getDepartmentID()!=0) {
criteria.add(CRITERIA_DEPARTMENT);
System.out.println("Dept ID ");
selected_dept = true;
}
if(data.getPositionID()!=0) {
criteria.add(CRITERIA_POSITION);
System.out.println("POS ID ");
selected_pos = true;
}
if(data.getWorkplaceID()!=0) {
criteria.add(CRITERIA_WORKPLACE);
selected_work = true;
}
query = query.concat(String.join(" OR ", criteria));
}
query = query.concat(" ORDER BY emp.joinDate DESC");
System.out.println("QUERY: " + query);
Query q = session.createQuery(query);
if(input_empID) {
q.setParameter("id", "%" + data.getEmployeeID() + "%");
}
if(input_empName) {
if(searchbyOne)
q.setParameter("inputName", "%" + data.getEmployeeName() + "%");
if(searchbyFandL)
q.setParameter("firstLastName", "%" +firstLastName+ "%");
if(searchbyCompName)
q.setParameter("completeName", "%" +completeName+ "%");
}
if(selected_dept) {
q.setParameter("deptID", data.getDepartmentID());
}
if(selected_pos) {
q.setParameter("posID", data.getPositionID());
}
if(selected_work) {
q.setParameter("workID", data.getWorkplaceID());
}
employees = (List<Object>) q.list();
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
return employees;
}
public String nameCriteriaHelper(String name) {
searchbyOne = false;
searchbyFandL = false;
searchbyCompName = false;
final String noOfTokens_1 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :inputName";
final String noOfTokens_2 = "(CONCAT(emp.lastName, ' ', emp.firstName) LIKE :firstLastName "
+ "OR CONCAT(emp.firstName, ' ', emp.lastName) LIKE :firstLastName)";
final String noOfTokens_3 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :completeName";
StringTokenizer stringTokenizer = new StringTokenizer(name);
int no_of_tokens = stringTokenizer.countTokens();
switch(no_of_tokens) {
case 1: searchbyOne = true;
return noOfTokens_1;
case 2: firstName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
firstLastName = lastName + " " + firstName;
searchbyFandL = true;
return noOfTokens_2;
default: int counter = 0;
while( counter < (no_of_tokens - 2)) {
firstName = firstName.concat(stringTokenizer.nextToken() + " ");
counter++;
}
firstName = stringTokenizer.nextToken();
middleName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
completeName = lastName + " " + firstName + " " + middleName;
searchbyCompName = true;
return noOfTokens_3;
}
You're using wrong order and wrong function to compare string:
Replace:
data.getEmployeeID()!="" && data.getEmployeeID()!=null
With
data.getEmployeeID() != null && !data.getEmployeeID().equals("")
Comparing string must use equals(). And check for null should be done first, before accessing the equals method
You should correct other conditions as above too.
Actually, the logic that Mr. Nguyễn provided here is faulty. An object or variable cannot both be null and initialized to a default value (such as foo == "") at the same time.
At the time of the logic check, if the String is in fact null, the second half of the logic statement will engage, checking to see if the String is equal to "", which will throw a null pointer exception. Instead of checking for both at the same time, check for one and then check for the other like so:
//since two logic checks are being performed,
//it is advantageous to put the data from the query
//into memory so you don't have to get the
//same result twice
String foo = data.getEmployeeID();
if (foo != null)
{
if (!(foo.equals("")))
{
//the result is neither null or empty
}
else
{
//the result is not null but it is empty
}
}
else
{
//the result is null
}
I'm generating an SQL statement by checking if each of the column fields submitted to the query are empty (== null) or not. It seems that my approach is pretty naive so I'm wondering what can be done about handling null parameters elegantly. When something isn't specified it should simply match anything.
Here is the code:
public List<Flight> findMatchingFlights(Flight flight)
{
List<Flight> foundFlights = new ArrayList<>();
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM Flights");
boolean emptyQuery = true;
if(flight.getDeparture() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
sqlQueryBuilder.append("Departure = '" + flight.getDeparture() + "'");
}
if(flight.getArrival() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Arrival = '" + flight.getArrival() + "'");
}
if(flight.getFlightNumber() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Number = '" + flight.getFlightNumber() + "'");
}
if(flight.getFlightMinutes() != 0)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Duration = " + flight.getFlightMinutes());
}
/*
...
A bunch more fields
*/
if(flight.getAirplane() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Airplane = '" + flight.getAirplane() + "'");
}
sqlQueryBuilder.append(";");
// Execute sql and fill list with rows that match
}
You can create the common method for the below block and call the method by passing the arguments.
if(flight.getArrival() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Arrival = '" + flight.getArrival() + "'");
}
Best approach would be to do the trick in SQL than checking for null in Java. This is how you can do it.
sqlQueryBuilder.append("(Number = '" + flight.getFlightNumber() + "' OR " + flight.getFlightNumber() + " IS NULL)");
This way you wont have to check null in java, if the flight.getFlightNumber() is null then this where clause will always return true which is what you would want.
The only drawback to this method is that the clause will be included in the query, but since you are intending to use these columns to query the table incase they are not null, i would assume the table would be indexed likewise.
sqlQueryBuilder.append("SELECT * FROM Flights WHERE 1 = 1");
then you don't need emptyQuery flag and checks and many if else constractions.
List<Flight> foundFlights = new ArrayList<>();
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM Flights WHERE 1 = 1");
if(flight.getDeparture() != null) {
sqlQueryBuilder.append("AND Departure = '" + flight.getDeparture() + "'");
}
Hi I'm trying to filter records on the basis of Brand,Flavor,Price,Size,Type. i am using a single form to handle this so if user filter only by brand then rest of options like price,flavor will be unchecked so i am checking if Brand or flavor or price is null.I got the solution but i have make lot of comparisons for all cases. i need a solution by which i have make less comparisons.I am using following code
public List<Products> Filter_Items(String[] Brand, String[] Flavour,Float Price,String Size,String Type)
{
ResultSet rs;
List<Products> data = null;
PreparedStatement stmt;
try {
StringBuilder param = new StringBuilder();
if (Brand != null) {
for (String str : Brand) {
param.append("'").append(str).append("', ");
}
}
StringBuilder param1 = new StringBuilder();
if (Flavour != null) {
for (String str : Flavour) {
param1.append("'").append(str).append("', ");
}
}
String prm = param.toString().length() > 2 ? param.toString()
.substring(0, param.toString().length() - 2) : null;
String prm1 = param1.toString().length() > 2 ? param1.toString()
.substring(0, param1.toString().length() - 2) : null;
String query = "select * from products where ";
if (prm != null && prm1 != null) {
query += "Brand in (" + prm + ") and Flavour in (" + prm1 + ")";
} else if (prm != null && prm1 == null) {
query += "Brand in (" + prm + ")";
} else if (prm1 != null && prm == null) {
query += "Flavour in (" + prm1 + ")";
}
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString("Ttile"));
p.setCategory(rs.getString("Category"));
p.setSubCategory(rs.getString("SubCategory"));
p.setSubCategoryTwo(rs.getString("SubCategorytwo"));
p.setPrice(rs.getInt("Price"));
p.setFlavour(rs.getString("Flavour"));
p.setSize(rs.getString("Size"));
p.setImage(rs.getString("image"));
p.setBrand(rs.getString("Brand"));
p.setInstock(rs.getString("instock"));
p.setInstockQty(rs.getInt("instockqty"));
data.add(p);
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
return null;
}
return data;
}
}
You can use as always third party libraries for validation like javax validation or any other more specialized on this.
You could create a bean of your data with all the getters and setters and apply validation on your bean.
To pass arrays you need getters and setters like this one:
public class Foo {
private int[] array;
public Foo(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
/** #param the array to use */
public setArray(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
/** #return a copy of the array */
public int[] getArray() {
return Arrays.copyOf(array, array.length);
}
}
To validate a bean see this tutorial.
What you really need is to start naming variables according to what they are logically. Names like prm and prm1 are meaningless, while brand and flavor make more sense as variable names since that's what's in them.
I don't see the number of comparisons as a problem. But giving everything generic variable names and then not even indenting the if-statements makes my eyes glaze over.
How about something like this:
if (brand != null && flavor != null)
{
query += "Brand in (" + brand + ") and Flavour in (" + flavor + ")";
}
else if (brand != null && flavor == null)
{
query += "Brand in (" + brand + ")";
}
else if (flavor != null && brand == null)
{
query += "Flavour in (" + flavor + ")";
}
Edit: One thing you can do is split your SQL into two variables, one for the main query and one for the where clause, then just add to the where clause like this:
private String addToWhereClause(String currentWhereClause, String fieldname, String value)
{
String returnValue = "";
if (value != null)
{
if(!"".equals(currentWhereClause))
{
returnValue += " AND ";
}
returnValue += " "+fieldname+" IN(" + value + ") ";
}
return returnValue;
}
String whereClause = "";
whereClause += addToWhereClause(whereClause, "Brand", brand);
whereClause += addToWhereClause(whereClause, "Flavour", flavor);
query = query + " " + whereClause;
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.