Trouble formulating a sql query in DAO Implementation using EntityManager.createQuery - java

I've method in my DAOImplwhich is intended to get a list of all books belonging to a specific user, from the database... The method looks like this:
#Override
public List<>BooksList> findListsOf(String userId) {
Query query = em.createQuery("SELECT * from BooksList where booksListOwner = unserid");
List<BooksList> resultsList = query.getResultList();
if (resultsList.isEmpty()) throw new NotFoundException();
return resultsList;
}
IntelliJ is showing me this error:
expression or DISTINCT expected, got '*'
What's wrong with my sql statement here?
BR,
Mic

You need to specify an identification variable rather than an SQL wilcard
List<BooksList> resultsList = em.createQuery(
"SELECT b from BooksList b where booksListOwner = :userId")
.setParameter("userId", userId)
.getResultList();

Related

HQL: Two conditions in where clause returning empty result

I am trying to select from db using HQL with two conditions as below:
String hql = "from User u where u.login=? and u.password=?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
System.out.println(query);
query.setString(0, u);
query.setString(1, p);
#SuppressWarnings("unchecked")
List<User> listUser = (List<User>) query.list();
System.out.println(listUser);
if (listUser != null && !listUser.isEmpty()) {
return true;
}
return false;
But I am getting empty result. I tried by giving only one condition , then it is giving proper result. (i.e. from User u where u.login=?). How to achieve this with two conditions?

Pass list of values on query parameter

String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
query.setString("school","");
query.setString("isActive", "Y");//working
query.setString("isActive", "N");//working
query.setString("isActive", "Y","N"); // not working
query.setString("isActive", "'Y','N'"); // not working
return query.list();
I have no idea if the code below should work, I was wondering if i can pass list of values to my search string parameter so there's no need for me to create to queries ; one for select all data regardless of status and another to select only active data.
Use Query.setParameterList() to pass in a List as a parameter:
String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
List<String> isActiveList = new ArrayList<>();
isActiveList.add("Y");
isActiveList.add("N");
query.setParameterList("isActive", isActiveList);
return query.list();

Is there any spring jpa equivalent to following query

Query :
#Query("Select p.name,t.points from Player p,Tournament t where t.id=?1 And p.id=t.player_id")
I have my player and tournament entity and their corresponding JPA repositories. But the problem is we can get only entities from our query, but i want to do above query, please help me with this i am new to it.
this is my sql query i want to add but where to add i am not getting:
Select p.name, t.points_rewarded from player p, participant t where t.tournament_id="1" and t.player_id=p.id;
This is how you can do it with JPQL for JPA:
String queryString = "select p.name, t.points from Tournament t," +
" Player p where t.player_id=p.id " +
"and t.id= :id_tournament";
Query query = this.entityManager.createQuery(queryString);
query.setParameter("id_tournament", 1);
List results = query.getResultList();
You can take a look at this JPA Query Structure (JPQL / Criteria) for further information about JPQL queries.
And this is ho you can do it using HQL for Hibernate, these are two ways of doing it:
String hql = "SELECT p.name, t.points from Player p,Tournament t WHERE t.id= '1' And p.id=t.player_id";
Query query = session.createQuery(hql);
List results = query.list();
Or using query.setParameter() method like this:
String hql = "SELECT p.name, t.points from Player p,Tournament t WHERE t.id= :tournament_id And p.id=t.player_id";
Query query = session.createQuery(hql);
query.setParameter("tournament_id",1);
List results = query.list();
You can take a look at this HQL Tutorial for further information about HQL queries.
Note:
In both cases you will get a list of Object's array List<Object[]> where element one array[0] is the p.name and the second one is t.points.
TypedQuery instead of normal Query in JPA
this is what i was looking for, thanks chsdk for help, i have to create pojos class, and in above link answer is working fine foe me,
Here is my code sample
String querystring = "SELECT new example.restDTO.ResultDTO(p.name,t.pointsRewarded) FROM Player p, Participant t where t.tournamentId=?1 AND t.playerId = p.id ORDER by t.pointsRewarded DESC";
EntityManager em = this.emf.createEntityManager();
try {
Query queryresults = em.createQuery(querystring).setParameter(1, tournamentId);
List<ResultDTO> result =queryresults.getResultList();
return new ResponseEntity<>(result, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} finally {
if (em != null) {
em.close();
}}

Native query with named parameter fails with "Not all named parameters have been set"

I want to execute a simple native query, but it does not work:
#Autowired
private EntityManager em;
Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = :username");
em.setProperty("username", "test");
(int) q.getSingleResult();
Why am I getting this exception?
org.hibernate.QueryException: Not all named parameters have been set: [username]
Named parameters are not supported by JPA in native queries, only for JPQL. You must use positional parameters.
Named parameters follow the rules for identifiers defined in Section 4.4.1. The use of named parameters applies to the Java Persistence query language, and is not defined for native queries. Only positional parameter binding may be portably used for native queries.
So, use this
Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");
While JPA specification doesn't support named parameters in native queries, some JPA implementations (like Hibernate) may support it
Native SQL queries support positional as well as named parameters
However, this couples your application to specific JPA implementation, and thus makes it unportable.
After many tries I found that you should use createNativeQuery And you can send parameters using # replacement
In my example
String UPDATE_lOGIN_TABLE_QUERY = "UPDATE OMFX.USER_LOGIN SET LOGOUT_TIME = SYSDATE WHERE LOGIN_ID = #loginId AND USER_ID = #userId";
Query query = em.createNativeQuery(logQuery);
query.setParameter("userId", logDataDto.getUserId());
query.setParameter("loginId", logDataDto.getLoginId());
query.executeUpdate();
You are calling setProperty instead of setParameter. Change your code to
Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = :username");
em.setParameter("username", "test");
(int) q.getSingleResult();
and it should work.
I use EclipseLink. This JPA allows the following way for the native queries:
Query q = em.createNativeQuery("SELECT * FROM mytable where username = ?username");
q.setParameter("username", "test");
q.getResultList();
Use set Parameter from query.
Query q = (Query) em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");
This was a bug fixed in version 4.3.11
https://hibernate.atlassian.net/browse/HHH-2851
EDIT:
Best way to execute a native query is still to use NamedParameterJdbcTemplate
It allows you need to retrieve a result that is not a managed entity ; you can use a RowMapper and even a Map of named parameters!
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
final List<Long> resultList = namedParameterJdbcTemplate.query(query,
mapOfNamedParamters,
new RowMapper<Long>() {
#Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong(1);
}
});

Hibernate query for searching part of string

I'm trying to write a hibernate query to search if table Room contains roomname which contains part of string.The string value is in a variable. I wrote a query to get exact room name from the table.
findRoom(String name) {
Query query = em.createQuery("SELECT a FROM Room a WHERE a.roomname=?1");
query.setParameter(1, name);
List rooms = query.getResultList();
return rooms;
}
In sql the query is something like this:
mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%"name"%' or '%"name"' or '"name"%'
");
I want to know the hql query for searching the table that matches my query. I can not use string directly, so the search query has to be veriable based and I need all three types in a query, if it's begin with name, or contains name or ends name.
I would do something like that:
findRoom(String name) {
Query query = em.createQuery("SELECT a FROM Room a"
+ "WHERE a.roomname LIKE CONCAT('%',?1,'%')");
query.setParameter(1, name);
List rooms = query.getResultList();
return rooms;
}
Use like instead of =:
Query query = em.createQuery("SELECT a FROM Room a WHERE a.roomname like ?1");
query.setParameter(1, "%"+name+"%");

Categories