I want to recuperate all rows from user table.
String queryS = "select u from user u";
System.out.println("entityManager: "+(entityManager == null));
Query query = entityManager.createQuery(queryS);
//staff
The line that throws the exception is Query query = entityManager.createQuery(queryS);
I don't know why even persistance file is ok and the table exists
The stack is:
10:36:06.693 [AWT-EventQueue-0] DEBUG org.hibernate.hql.ast.ErrorCounter - throwQueryException() : no errors
10:36:06.693 [AWT-EventQueue-0] DEBUG o.h.hql.antlr.HqlSqlBaseWalker - select << begin [level=1, statement=select]
You have to put the name of the table in the query as in the persistence file not in database.
If this:
String queryS = "select u from user u"
Is referred on table name you can't use createQuery method but createNativeQuery
If you want to use createQuery you must use in your query the entity/class mapped youe user table
Summarizing:
Case 1 (use createNativeQuery)
String queryS = "select u from user u";
Query query = entityManager.createNativeQuery(queryS);
Case 2 (use createQuery)
String queryS = "select u from " + User.class.getName() + " u";
Query query = entityManager.createNativeQuery(queryS);
Related
My problem is that I want to apply the following two commands in JavaFX in order to get how many 1ones are in a named "party" column from a database named "conteo".
sql ="select count(*) from conteo where party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
i used System.out.println(rs.getString("party")); to expect the correct number of 1ones in "party" column from "conteo" database and i get "the error column party do not exist", but actually it already exist!!!
sql ="select count(*) from conteo where party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
I would like to print in command line "rs" using "System.out.println()"
My database address is correctly address it, because i already write data sucessfully in mysql databases using javafx, how can i properly print "rs" result in command line?, anyhelp is appreciated, thanks in advance, Omar Torres
You asked...
how can i properly print "rs" result
Do you mean something like this...
if (rs.next()) {
int theCount = rs.getInt(1);
System.out.println(theCount);
}
You did not select the party column for the output. Since you're using a aggregate function, this shouldn't work in this case anyways. You'd need to use GROUPING BY+HAVING anyways.
It's much simpler to provide an alias for the value
sql ="SELECT COUNT(*) AS num FROM conteo WHERE party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
if (rs.next()) {
int i = rs.getInt("num");
...
}
or
sql ="SELECT COUNT(*) FROM conteo WHERE party =1";
ResultSet rs = conn.createStatement().executeQuery(sql);
if (rs.next()) {
int i = rs.getInt(1); // access first column in result
...
}
I am building an endpoint where 3 query param comes in request like
status(mendatory)
searchCriteria(optional)
startDate(optional)
I am considering that i have to write three(3) native sql queries with combination of ex.
1: status and searchCriteria
2: status and startDate
3: status and searchCriteria and startDate
but I do not want to write three queries,
I know it is possible to achieve in a single query using case .
This is my native sql query
#Query(value = "select * from email_info u where u.status =:status and u.campaign =:searchCriteria and u.scheduleat =:startDate",
nativeQuery = true)
object getPromotional(String status, String searchCriteria, String startDate);
How to use case in above query using jpa like
CASE
WHEN :searchCriteria != null THEN u.campaign =:searchCriteria
WHEN :startDate != null THEN u.scheduleat =:startDate
END
How should I convert this MySQL query to HQL to retrieve some data I need?
SELECT pu.url, count(sen.content)
FROM Sentence sen JOIN ProcessedUrl pu
ON sen.PROCESSED_URL_ID=pu.url_id
GROUP BY pu.url ORDER BY 2;
In my code there is POJO ProcessedUrl which have id/url/date/set(of Sentence) fields mapped. I wanted to do something like:
Session session = HibernateUtils.getSession();
Transaction transaction = session.beginTransaction();
List<ProcessedUrl> result = session.createQuery("proper HQL query", ProcessedUrl.class).getResultList();
transaction.commit();
session.close();
return result;
and then iterate over this result to print result.getUrl() & result.getSentences().size() for each url.
I know my query should return fields which are inside ProcessedUrl then how I can return some grouped query and retrieve data from it that is not kept directly inside the table? Like this count() for every url?
Thanks for help.
I have found out right HQL query so no need help anymore.
List<Object[]> result = session.createQuery("select pu.url, count(sen.content)"
+ " FROM ProcessedUrl pu"
+ " JOIN pu.sentences sen "
+ " GROUP BY pu.url "
+ " ORDER BY 2", Object[].class).getResultList();
This is my code.. Query working when i search with mysql query(find it in screenshot).But failed with hiberbate query.
EmployeeAttendanceMaster masterEmployeeFromRepository = masterEmployeeRepository.findById(employee, date);
if (masterEmployeeFromRepository == null) {
System.out.println("SignIn Successfully");
}else System.out.println("You are already Logged In");
masterEmployeeRepository:
#Query("select me from EmployeeAttendanceMaster me where me.employee = ?1 and Date(me.date) = ?2 order by me.date desc")
EmployeeAttendanceMaster findById(Employee employee,Date date);
mysql db screenshot in with same query
Data with same date there in db..So it shoudnot go through if condition.It should follow else condition.But as long as i tried this it prints "SignIn Successfully"
Thanks advance
You are using the Spring Data JPA #Query annotation (as discerned from the full data type you have provided in the comments to your question). The query you specify with #Query (select me from EmployeeAttendanceMaster me ...) must be a valid JPA Query Language (JPQL) statement. From what I know and remember, JPQL does not have a Date() function. So, your query is invalid because it contains Date(me.date) which refers to a non-existent JPQL Date() function, even if you can run it directly on MySQL.
You can change your query declaration to:
#Query(value = "select * from EmployeeAttendanceMaster where employee_id = ?1 and Date(date) = ?2 order by date desc", nativeQuery = true)
This will force the JPA provider (Hibernate in your case) to treat the query as a native SQL query and will be executed on the underlying database without any translation. You will lose database independence though.
The hibernate manual says this:
String sql = "SELECT ID as {c.id}, NAME as {c.name}, " +
"BIRTHDATE as {c.birthDate}, MOTHER_ID as {c.mother}, {mother.*} " +
"FROM CAT_LOG c, CAT_LOG m WHERE {c.mother} = c.ID";
List loggedCats = sess.createSQLQuery(sql)
.addEntity("cat", Cat.class)
.addEntity("mother", Cat.class).list()
Now, what I have is basically the same. I am return two of the same type per row. I am doing a select something like this:
SELECT {ctrl1.*}, {ctrl2.*} FROM tableA AS A
LEFT JOIN tableB AS ctrl1 ON (A.controlID = ctrl1.controlID AND ctrl1.controlOptionType = ? AND ctrl1.controlOptionValue = ?)
LEFT JOIN tableB AS ctrl2 ON (A.controlID = ctrl2.controlID AND ctrl2.controlOptionType = ? AND ctrl2.controlOptionValue = ?)
And then I addEntity("ctrl1", typeof(mycontrolclass) and
addEntity("ctrl1", typeof(mycontrolclass)
Which seems exactly the same to me as their example. But I get this exception:
"Could not execute query" and the inner exception is "Could not find specified column in results".
If I copy the sql in the exception(to which it has added "AS ctrl1_1_3_3_" etc) it works fine.
Thanks.
What exactly are you trying to do? I believe you might not need using either of them.
// Using HQL:
var motherId = 25;
var hql = "select c.birthDate, c.mother from Cat c where c.mother.Id = :motherId";
var result = Session.CreateQuery(hql)
.SetParameter("motherId", motherId)
.ToList();
// Using NHibernate.LINQ:
var result = (from cat in Session.Linq<Cat>()
where cat.Mother.Id == motherId
select new { cat.birthDate, cat.mother }).ToList();
HQL query examples.
LINQ for NHibernate examples.
I dealt with your problem just for studying purposes, because you will surely
have found a solution in the meanwhile, but the problem should not lie in
the query (which is ok), but in some mapping inconsistency or somewhere else
(perhaps Database).