Hibernate Query whit function count - java

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();

Related

sql for paging notice board in jsp

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.

sql Query builder in JPA query?

I've made a search tool in java.
String query = "SELECT * FROM Customer WHERE 1 = 1 ";
if (!firstname.isEmpty()) query += "AND cName = '" + firstname + "' ";
if (!lastname.isEmpty()) query += "AND cLastName = '" + lastname + "' ";
if (!epost.isEmpty()) query += "AND cEpost = '" + epost + "' ";
if (!phonenumber.isEmpty()) query += "AND cPhonenumber '" + phonenumber + "' ";
That ouput this if all of those paramerets has values:
SELECT * FROM Customer WHERE 1 = 1
AND cName = 'test'
AND cLastName = 'test1'
AND cEpost = 'test2'
AND cPhonenumber 'test3'
This way I can get better results by filling in more data, but i can still choose to not do.. I need a solution for JPA for this.. any tips?
Thanks!
EDIT: End result based on the answer below:
public static List<Customer> searchCustomersByParameters(String firstname, String lastname,
String epost, String phonenumber) {
String sql = "SELECT c FROM Customer c WHERE 1 = 1 ";
if (!firstname.isEmpty()) sql += "AND c.cName = :firstname ";
if (!lastname.isEmpty()) sql += "AND c.cLastName = :lastname ";
if (!epost.isEmpty()) sql += "AND c.cEpost = :epost ";
if (!phonenumber.isEmpty()) sql += "AND c.cPhonenumber = :phonenumber";
Query q = em.createQuery(sql);
if (!firstname.isEmpty()) q.setParameter("firstname", firstname);
if (!lastname.isEmpty()) q.setParameter("lastname", lastname);
if (!epost.isEmpty()) q.setParameter("epost", epost);
if (!phonenumber.isEmpty()) q.setParameter("phonenumber", phonenumber);
return q.getResultList();
}
While it is of course possible to create dynamic SQL using string concatenation as suggested in this answer, a more type safe and less risky (in terms of SQL injection) approach is to use the JPA criteria API
public static List<Customer> searchCustomersByParameters(String firstname, String lastname,
String epost, String phonenumber) {
var qb = em.getCriteriaBuilder();
var query = qb.createQuery(Customer.class);
var root = query.from(Customer.class);
query.select(root);
if (!firstname.isEmpty()) query.where(qb.equal(root.get("cName"), firstName));
if (!lastname.isEmpty()) query.where(qb.equal(root.get("cLastName"), lastname));
if (!epost.isEmpty()) query.where(qb.equal(root.get("cEpost "), epost ));
if (!phonenumber.isEmpty()) query.where(qb.equal(root.get("cPhonenumber "), phonenumber));
return em.createQuery(query).getResultList();
}
... or if you don't strictly need to use JPQL you could also use a third party SQL builder like jOOQ:
public static List<Customer> searchCustomersByParameters(String firstname, String lastname,
String epost, String phonenumber) {
return
ctx.selectFrom(CUSTOMER)
.where(!firstname.isEmpty() ? CUSTOMER.CNAME.eq(firstname) : noCondition())
.and(!lastname.isEmpty() ? CUSTOMER.CLASTNAME.eq(lastname) : noCondition())
.and(!epost.isEmpty() ? CUSTOMER.CEPOST.eq(epost) : noCondition())
.and(!phonenumber.isEmpty() ? CUSTOMER.CPHONENUMBER.eq(phonenumber) : noCondition())
.fetchInto(Customer.class);
}
Disclaimer: I work for the company behind jOOQ
use ? and set Parameters for preventing sql injection and in JPA you can use native sql as old way you do and also JPQL.Generate your sql by conditions and set your parameters.I use here where 1=1 condition to easy append next conditions by and.Otherwise you will have difficulties for appending "where" to your sql.
by native:
public static List<YourEntity> getFromTable(String name,String surname) {
EntityManager em = PersistenceManager.instance().createEntityManager();
try {
String sql = " select * from table where 1=1 ";
if(name!=null && !name.trim().isEmpty()){
sql +=" and name = :name";
}
if(surname!=null && !surname.trim().isEmpty()){
sql +=" and surname = :surname";
}
Query q = em.createNativeQuery(sql);
if(name!=null && !name.trim().isEmpty()){
q.setParameter("name", name);
}
if(surname!=null && !surname.trim().isEmpty()){
q.setParameter("surname", surname);
}
List<YourEntity> l = q.getResultList();
return l;
} finally {
em.close();
}
}
By jpql:
public static List<YourEntity> getFromTable(String name,String surname) {
EntityManager em = PersistenceManager.instance().createEntityManager();
try {
String sql = " select e from YourEntity e where 1=1 ";
if(name!=null && !name.trim().isEmpty()){
sql +=" and e.name = :name";
}
if(surname!=null && !surname.trim().isEmpty()){
sql +=" and e.surname = :surname";
}
Query q = em.createQuery(sql);
if(name!=null && !name.trim().isEmpty()){
q.setParameter("name", name);
}
if(surname!=null && !surname.trim().isEmpty()){
q.setParameter("surname", surname);
}
List<YourEntity> l = q.getResultList();
return l;
} finally {
em.close();
}
}

Hibernate Hql orderby problems

I am using Hibernate, and I have a problem with HQL. I have users who have a latitude and longitude, and I need to compare distances between the user logged and the other users in a query and order it. What I need to do is (userloged.latitude - user.latitude)^2 + (userloged.longitude - user.longitude)^2 in the query. I have the user logged, and I need to get the < 20 nearest to him. Thanks.
public List<Usuarios> getAllUsuarios(String correito, String desea) {
// TODO Auto-generated method stub
this.session = sf.openSession();
Query query;
if(desea.equals("Ambos"))
query = session.createQuery("FROM Usuarios WHERE correo != '" + correito + "' ORDER BY ");
else
{
if(desea.equals("Hombres"))
desea = "Hombre";
else if(desea.equals("Mujeres"))
desea = "Mujer";
query = session.createQuery("FROM Usuarios WHERE correo != '" + correito + "' AND genero = '" + desea + "'");
}
query.setMaxResults(MAX);
List<Usuarios> usuarios = (List<Usuarios>) query.list();
session.close();
return usuarios;
}

Java MySQL returns only one row

I have this code:
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
System.out.println("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
System.out.println(p);
tasks.add(p);
}
The problem is that it returns only the first row, and if I run the query manually I get more results (16 total). Here's the output:
SELECT * FROM tasks WHERE uid = 4 ORDER BY title ASC
models.Task#164b9b8f
Any idea why this is happening?
May be you can improve the code a bit like below which will help you to quickly identify the issue.
int rowCount = 0;
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
String query = "SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC";
System.out.println(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
rowCount++;
System.out.println(rowCount + "." + p);
tasks.add(p);
}
} finally {
System.out.println("Number of records = " + rowCount);
}
In this approach you can clearly identify how many rows were iterated.

MYSQL LIMIT not working as expected - Java

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.

Categories

Resources