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;
}
Related
I want to insert data to my table, I have an insert statement (to the same table) that I use in a different method which works in one method, but returns an JdbcSQLSyntaxErrorException: Column xyz not found; in another.
where xyz is the value I want to pass into the column (not the column name).
This is the method which triggers the exception:
public void btnSaveStock(MouseEvent mouseEvent) {
ArrayList<Stock> stock = new ArrayList<>();
stock.addAll(tblStock.getItems());
stock.remove(removedStock);
try {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(url, "", "");
Statement statement = connection.createStatement();
for (int i = 0; i < stock.size(); i++) {
String stockName = stock.get(i).getDescription();
String stockCode = stock.get(i).getCode();
double fuelBalance = stock.get(i).getStoresBalance();
double counterBalance = stock.get(i).getCounterBalance();
System.out.println(stockName + stockCode + fuelBalance + counterBalance);
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES (" + stockCode + ",'New Product','1.00','1.00')";
statement.executeUpdate(insertQuery);
String updateQuery = "Update STOCK set DESCRIPTION='" + stockName + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
updateQuery = "Update STOCK set \"fuelBalance\"='" + fuelBalance + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
updateQuery = "Update STOCK set \"counterBalance\"='" + counterBalance + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
//more method calls here
}
This is the method that successfully inserts data:
public void addNewStock(MouseEvent mouseEvent) {
Stock stock = new Stock();
String lastCode = savedStockList.get(savedStockList.size() - 1).getCode();
int newCode = 1 + Integer.parseInt(lastCode);
stock.setCode(String.valueOf(newCode));
stock.setCounterBalance(0);
stock.setDescription("New Product");
stock.setStoresBalance(0);
savedStockList.add(stock);
try {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(url, "", "");
Statement statement = connection.createStatement();
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES (" + newCode + ",'New Product','1.00','1.00')";
statement.executeUpdate(insertQuery);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
initialiseStock();
}
So if stockCode contains the value xyz, the exception will be Column xyz not found
I'm failing to understand why this works in one method, but returns an exception in another.
It works because newCode is a number which doesn't need quotes and doesn't work because stockCode is a string and needs to be quoted. Add single quotes around stockCode and it should work:
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES ('" + stockCode + "','New Product','1.00','1.00')";
As a side note you should really use prepared statement.
Code example with Hibernate which evaluate possible parameters:
String query = "SELECT * FROM instances";
String where = "";
if(userName!=null) {
where+="AND username = '" + userName + "'";
}
if(componentName!=null) {
where+="AND componentname = '" + componentName + "'";
}
if(componentAlias!=null) {
where+="AND componentalias = '" + componentAlias + "'";
}
if(!where.equalsIgnoreCase("")) {
where = where.substring(3);
where = " WHERE " + where;
}
query = query + where;
LOGGER.info("Query: " + query);
Statement s = (Statement) conn.createStatement();
ResultSet rs = s.executeQuery(query);
How can I do that with Speedment ORM Filters?
It is very similar in Speedment. The Stream interface returns a new Stream every time a filter is added. You can simply store that in a variable and use if-statements as in your code.
Stream stream = instances.stream();
if (userName != null) {
stream = stream.filter(Instance.USERNAME.equal(userName));
}
if (componentName != null) {
stream = stream.filter(Instance.USERNAME.equal(componentName));
}
if (componentAlias != null) {
stream = stream.filter(Instance.USERNAME.equal(componentAlias));
}
List<Instance> result = stream.collect(toList());
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();
}
}
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.