Getting single result of type int in hibernate - spring

I have a controller that communicates with my service to get the id of the logged in user. I first get the username using principal object
#ResponseBody
#RequestMapping(value = "/lid",method = RequestMethod.GET)
public Integer lid(Principal p) {
String name = p.getName();
Integer gotid = personService.getDbId(name);
return gotid;
}
then call the service passing the username to the dao
public Integer getDbId(String name){
Session currentSession = sessionFactory.getCurrentSession();
#SuppressWarnings("rawtypes")
Query theQuery = currentSession.createQuery("select id from app_user where sso_id=:name");
//set multiple parameters from the user
//theQuery.setParameter("city", city);
theQuery.setParameter("sso_id", name);
//Get the int or the big int
//Get results into list object : List list = query.list();
int theid = (int)theQuery.getSingleResult();
//uniqueResult
return theid;
//org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: from near line 1, column 8 [select from app_user where sso_id=:name]
}
However, i get this error
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: app_user is not
mapped [select id from app_user where sso_id=:name]
How can i fix it to give me the one result that i want?.

You are trying to execute pure SQL but hibernate expects HQL. So it tries to find an Entity with app_user name but fails - there is no such class.
Try instead
Query theQuery = currentSession.createSQLQuery("...");

Try with this
Query theQuery = currentSession.createQuery("select id from AppUser where ssoId=:name");
AppUser might be your class name and ssoId is field name.
use your Domain class name and domain field names whatever it is because query requires HQL.

Related

How to access PostgreSQL RETURNING value in Spring Boot DAO?

I want to return the auto-generated id of entity. PostgeSQL is able to automaticaly selects certain column via RETURNING, but I have a hard time trying to find how to retrieve this value in Spring Boot.
I would want something like:
public int createUser(User user) {
String sql = "INSERT INTO user (name, surname) VALUES (?,?) RETURNING id";
return jdbcTemplate.update(sql,
user.getName(),
user.getSurname(),
resultSet -> resultSet.getInt("id")
);
}
I know it's straightforward in Hibernate, then whether you use a Repository class or an EntityManager, the save method returns the saved entity, so you can just do:
int id = userRepository.save(user).getId();
Or is there a reason you want to persist it the way you do?

Return type of Query function in Android Room Database?

I have a simple question but I just can't find any documentation anywhere.
Suppose we have the below example, which can be found here.
#Dao
public interface UserDao {
#Query("SELECT * FROM User WHERE userId = :id")
public User getById(int id);
}
I notice the return type of the function is User, but what happens if there query doesn't return a result? (i.e. there is no user in the table with the specified id)
Will the function simply return null?
Also, if this were a Kotlin function, should the signature be the following with nullable type User?
#Query("SELECT * FROM User WHERE userId = :id")
fun getById(int id): User?
When documentation is not enough, reading sources could help.
Whatever you use (Java or Kotlin) describing Dao interface - Dao class implementation in Java (generated by Room under the hood) would be the same:
public User getById(int id) {
...
final Cursor _cursor = DBUtil.query(__db, "SELECT * FROM User ...", false, null);
.....
if(_cursor.moveToFirst()) {
// If there is at least one record
_result = new User(<...User's fields gotten from query...>);
} else {
// If there is no record
_result = null; // <---- here it is!
}
return _result;
...
}
Also, if this were a Kotlin function, should the signature be the following with nullable type User?
Technically you could omit ?, but it could mislead in reading code, so better use User? explicitly.

Native Query Like Format Issue in SpringBoot

I am trying to use like operator in native query as below:
#Query(value = "SELECT max(id) FROM EMP where id like ___:country%", nativeQuery=true)
country as input parameter for method.
getting the below error:
java.lang.IllegalArgumentException: Unknown parameter name : country
can anyone please help me on this.
use JPA query in your repository interface like this:
#Query(nativeQuery = true, value = "SELECT max(r_id) FROM registrations WHERE r_name LIKE ?1")
int getCount (String name);
when you call this function add modulus(%) with your string like this:
#Autowired
private RegistrationRepository registrationRepository;
#GetMapping(value = "/reg-like")
#ResponseBody
public void regLike() {
int max = registrationRepository.getCount("s%");
System.out.println("" + max);
}
Or you can try something like this:
#Query(nativeQuery = true, value = "SELECT max(r_id) FROM registrations WHERE r_name LIKE %?1")
int getCount (String name);
Then you can omit the modulus(%), when calling the function.
See official documentation here.

Spring Rest Hibernate Update List with PUT method

I'm tying to update List with a rest service, but an InvalidDataAccessApiUsageException is thrown :
Parameter value element [Sharing{uuid=af777b47-3dfc...updated=2016-05-04T10:37:29.000Z}] did not match expected type [java.util.UUID (n/a)]
Controller :
#RequestMapping(value = "/updateChecked", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public int update(#RequestBody SharingList shares){
return this.sharingService.updateChecked(shares);
}
Service :
public int updateChecked(SharingList shares) {
int updated = sharingDao.setCheckedSharingFor(shares);
return updated;
}
DAO :
#Modifying
#Query("UPDATE Sharing s SET s.checked=1 WHERE uuid in :shares")
int setCheckedSharingFor(#Param("shares") SharingList shares);
SharingList:
public class SharingList extends ArrayList<Sharing> {
}
What is wrong please ?
There is the answer here
Sharing{uuid=af777b47-3dfc...updated=2016-05-04T10:37:29.000Z}]
did not match expected type [java.util.UUID (n/a)]
Hibernate doesn't have artificial intelligence to understand that it should get uuid from Sharing.
Fo this query
#Query("UPDATE Sharing s SET s.checked=1 WHERE uuid in :shares")
you should provide a collection of UUID as the shares parameter.

How to use Spring ColumnMapRowMapper?

Can anyone help me with an example of ColumnMapRowMapper? How to use it?
I've written an answer in my blog, http://selvam2day.blogspot.com/2013/06/singlecolumnrowmapper.html, but here it is for your convenience below:
SingleColumnRowMapper & ColumnMapRowMapper examples in Spring
Spring JDBC includes two default implementations of RowMapper - SingleColumnRowMapper and ColumnMapRowMapper. Below are sample usages of those row mappers.
There are lots of situations when you just want to select one column or only a selected set of columns in your application, and to write custom row mapper implementations for these scenarios doesn't seem right. In these scenarios, we can make use of the spring-provided row mapper implementations.
SingleColumnRowMapper
This class implements the RowMapper interface. As the name suggests, this class can be used to retrieve a single value from the database as a java.util.List. The list contains the column values one per each row.
In the code snippet below, the type of the result value for each row is specified by the constructor argument. It can also be specified by invoking the setRequiredType(Class<T> requiredType) method.
public List getFirstName(int userID)
{
String sql = "select firstname from users where user_id = " + userID;
SingleColumnRowMapper rowMapper = new SingleColumnRowMapper(String.class);
List firstNameList = (List) getJdbcTemplate().query(sql, rowMapper);
for(String firstName: firstNameList)
System.out.println(firstName);
return firstNameList;
}
More information on the class and its methods can be found in the spring javadoc link below.
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/jdbc/core/SingleColumnRowMapper.html
ColumnMapRowMapper
ColumnMapRowMapper class can be used to retrieve more than one column from a database table. This class also implements the RowMapper interface. This class creates a java.util.Map for each row, representing all columns as key-value pairs: one entry for each column, with the column name as key.
public List<Map<String, Object>> getUserData(int userID)
{
String sql = "select firstname, lastname, dept from users where userID = ? ";
ColumnMapRowMapper rowMapper = new ColumnMapRowMapper();
List<Map<String, Object>> userDataList = getJdbcTemplate().query(sql, rowMapper, userID);
for(Map<String, Object> map: userDataList){
System.out.println("FirstName = " + map.get("firstname"));
System.out.println("LastName = " + map.get("lastname"));
System.out.println("Department = " + map.get("dept"));
}
return userDataList;
}
More information on the class and its methods can be found in the spring javadoc link below.
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/jdbc/core/ColumnMapRowMapper.html

Resources