java DAO update query failure - java

I am trying to write DAO method to update value in postgres table "accounts" with just two columns:
"id" string
"balance" int
public Account setAccountBalance(String id, Integer balance) {
Handle h = dbi.open();
try{
return h.createQuery("UPDATE accounts SET balance=" + balance.intValue() +
" WHERE id=\'" + id +"\';")
.mapTo(Account.class)
.first();
} finally {
h.close();
}
}
But on execute I see the following exception:
org.skife.jdbi.v2.exceptions.NoResultsException: Query did not have a result set, perhaps you meant update? [statement:"UPDATE accounts SET balance=20 WHERE id='1';", located:"UPDATE accounts SET balance=20 WHERE id='1';", rewritten:"UPDATE accounts SET balance=20 WHERE id='1';", arguments:{ positional:{}, named:{id:'1'}, finder:[]}]
Any idea if the problem is in query syntax, or use of DAO?

Looks like you are using JDBI. According to the documentation, SQL UPDATEs can be performed through Handle.execute(), as follows:
h.execute("UPDATE accounts SET balance=? WHERE id=?", balance.intValue(), id);
But the execute method doesn't return a result set and therefore cannot be used for creating an Account object. You would need to issue a separate query for doing that, maybe something like
return h.createQuery("SELECT id, balance FROM accounts WHERE id = :id")
.bind("id", id)
.mapTo(Account.class)
.first();

Related

hibernate query giving an inccorect result list

this is the method Dao layer List,
public List<PortfolioMemberView> getPortfolioMemberViewByPid(Integer pid){
//check the portfolioId value in console
System.out.print(pid);
try {
Session session = sessionFactory.getCurrentSession();
String sql = "from PortfolioMemberView pv where pv.portfolioId = ?0";
Query query = session.createQuery(sql).setParameter(0, pid);
List<PortfolioMemberView> pmvl = query.list();
//check the result list by assetCode in console
for(PortfolioMemberView pv: pmvl){
System.out.print(pv.getAssetCode());
}
return pmvl;
}catch(Exception e){
logger.info("操作失败:" + e.getMessage() + ", " +e.getCause());
throw new RuntimeException();
}
I have a view(That I create) PortfolioMemberView in my database
and it has the following data
inmage
when I involke the method, the console print following result.
2
Hibernate: select portfoliom0_.portfolioId as portfoli1_8_,
portfoliom0_.assetId as assetId2_8_, portfoliom0_.accountType as accountT3_8_, portfoliom0_.assetCode as assetCod4_8_, portfoliom0_.assetLabel as assetLab5_8_, portfoliom0_.value_ as value_6_8_, portfoliom0_.annualReturn as annualRe7_8_, portfoliom0_.returnRate as returnRa8_8_ from PortfolioMemberView portfoliom0_ where portfoliom0_.portfolioId=?
CMPROP0121CMPROP0121CMPROP0121CMPROP0121CMPROP0121
The expected result should be CMPROP0121kckbGYck, because when portfolioId = 2, the assetCode of three object in the resulting list shoud be CMPROP0121,kckb,GYck.
I also copy the query hibenate generated and run it at mysql database, and the result is correct.
Hibernate: select portfoliom0_.portfolioId as portfoli1_8_,
portfoliom0_.assetId as assetId2_8_, portfoliom0_.accountType as accountT3_8_, portfoliom0_.assetCode as assetCod4_8_, portfoliom0_.assetLabel as assetLab5_8_, portfoliom0_.value_ as value_6_8_, portfoliom0_.annualReturn as annualRe7_8_, portfoliom0_.returnRate as returnRa8_8_ from PortfolioMemberView portfoliom0_ where portfoliom0_.portfolioId=?
not sure what's wrong, pls help!!!
I mapped portfolioId as primary Id, and primary Id cannot be duplicated. but obviously the primary key portfolioId is duplicated. I make aother primary key portfolioMemberId, and the problem solved

null pointer exception on retrieving records from the database hibernate hql

I have a record that exists in my database which I crossed several times and the record is correct. I have also ensured that toString is overriden in my class to get a meaningful representation of the data I am retrieving.
This is the hql I am using to fetch records from the database
public List <Admin> getByAdminRole(int id) {
Query query = _sessionFactory.getCurrentSession()
.createQuery("select a.id from Admin a WHERE a.id = :id");
query.setParameter("role", id);
return query.list();
}
In my controller class I am calling the hql method this way
SupportDao _supportDao = new SupportDao();
List <Admin> add = _supportDao.getByAdminRole(1); //this line of code throws null pointer exception
System.out.println(">>>>>>>>>>> the value of add>>>>>>> " + add);
After research on solving nullpointer exception, I have ensured that toString is overriden in my model class Admin.java
#Override
public String toString(){
return this.id + this.name + this.getEmail() + this.getPassword() + this.role;
}
Please what could be wrong with my code?
change
query.setParameter("role", id);
to
query.setParameter("id", id);
if want to return List<Admin> also modify ,
.createQuery("select a.id from Admin a WHERE a.id = :id");
to
.createQuery("from Admin a WHERE a.id = :id");
it will return Admin list with only one Admin if single id is present
if you want single Admin then
return query.uniqueResult(); and change return type as per requirement
Since you're instantiating SupportDAO yourself are you absolutely, 101% sure that _sessionFactory in SupportDAO is also instantiated?
Looking to your above code where you passing the "id" as parameter but in setParameter method your are passing with "role" .
I guess you need to pass it with "id" only.

hibernate update always null

iam new in hibernate, i have a entity class named student, it have 5 field, name, age, address, phone, and sex.
then i want to update name and age field.
student.setName("foo");
student.setAge("11");
getHibernateTemplate().update(student);
after i ran the code, the other field value become null, except the two field in the code above. i expecting my other field to stay as it is.
any suggest is deeply appreciated
btw sorry for my bad english
For updating value first of all you have to get the value by primary key and then update the object(Bean) then update method should be called.
What you have to do is retrieve your student from database before, to have a value for all the fields :
Student student = getHibernateTemplate().get(Student.class, id);
student.setName("foo");
student.setAge("11");
getHibernateTemplate().update(student);
Or, alternatively, you can do a manual update of your fields :
Session session;
boolean newSession=false;
try {
session=getHibernateTemplate().getSessionFactory().getCurrentSession();
} catch (final HibernateException e) {
session=getHibernateTemplate().getSessionFactory().openSession();
newSession=true;
}
session.createQuery(
"update Student student set " +
"student.Name = :studentName, " +
"student.Age = :studentAge " +
"where student.Id = :studentId")
.setString("studentName", "foo")
.setString("studentAge", "11")
.setString("studentId", id)
.executeUpdate();
if (newSession)
session.close();

Hibernate retrieve results from database based on condition

I am a bit lost when it comes to retrieving results from the database.
My MemberModel consists of 4 fields: id, username, password and email. I have been able to successfully save it to database.
Now I need to retrieve an id of a member who's username equals "Test".
I tried something along the lines:
SQLQuery query = session.createSQLQuery("SELECT id FROM members WHERE username = :username");
query.setString("username", username);
List<MemberModel> returnedMembers = query.list();
MemberModel member = returnedMembers.get(0);
int id = member.getId();
However I get an error that member.getId() cannot be converted to int, since it is MemberModel... But the getter getId() returns int.
I am quite confused. The question is: what would be the easiest and fastes way to retrieve member id based on condition (value of username)?
You are using a native SQL query, but should use HQL query. That means you have to change the query to:
session.createQuery("SELECT m FROM MemberModel m WHERE m.username = :username")
I would change your code into something like this:
public MemberModel getMember(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from " + MemberModel.class.getName() + " where username = :username ");
query.setParameter("username", username);
return (MemberModel) query.uniqueResult();
}
Then you should be able to do:
MemberModel model = someInstance.getMember("someUsername");
int id = model.getId();
You can also use criteria and restrictions api.
Criteria criteria = session.createCriteria(MemberModel.class);
criteria.add(Restrictions.eq("username", username));
MemberModel member=(MemberModel)criteria.uniqueResult();

DAO method retrieve single entry

How can I write DAO method which will return as a result only first entry from the database. For instance lets say I'm looking at Users table and I want to retrieve only the first entry, I'd declare method like:
public User getFirstUser(){
//method logic
}
EDIT:
User has primary key id if that matters at all.
I apologize if this question is too simple/stupid/whatever I'm beginner with Java so I'm trying new things. thank you
My attempt :
public User getFirstUser(){
try {
final String getQuery = "SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)";
final Query query = getSession().createQuery(getQuery);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("get successful");
// return what??
} catch (RuntimeException re) {
log.error("get not successful", re);
throw re;
}
}
You can
use:
Query query = session.createQuery("from User");
query.setMaxResults(1);
User result = (User) query.uniqueResult();
use User user = session.get(User.class, id); if you know the ID upfront.
Get all users ordered by id and limit the results to 1 (but don't use LIMIT, use setMaxResults() to remain portable):
Query q = session.createQuery("from User u order by u.id");
q.setMaxResults(1);
User u = (User) q.uniqueResult();
SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)
:)
Don't remember exactly but i think there is a method getSingleResult in JPA and also in Hibernate so...
But this method perhaps throw exception when multiple results are returned... can't remember...
Actually there is also getResultList returning a List of entities, and you could do list.get(0) no?
Or create a query with LIMIT 1?
In MS SQL Server we do it like,
First user, min ID,
SELECT TOP 1 * FROM Users ORDER BY Id
Latest user, max ID,
SELECT TOP 1 * FROM Users ORDER BY Id DESC
thanks.

Categories