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.
Related
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();
I have two tables with the foreign key relating them:
enter image description here
I have used a SQL query to retrieve the value form both tables:
User u = new User();
String sql = "SELECT * FROM user INNER JOIN account ON user.id = account.user WHERE user.id = 1 ";
try {
Statement stm = con.createStatement();
ResultSet rsu = stm.executeQuery(sql);
while(rsu.next()){
u.setFname(rsu.getString("fname"));
u.setLname(rsu.getString("lname"));
u.setMname(rsu.getString("mname"));
u.setGender(rsu.getString("gender"));
u.setAddress(rsu.getString("address"));
u.setCitizenship(rsu.getLong("citizenship"));
/**
*
* Here i want to get values of account table and set it on
* user object to return u
*
*/
}
return u;
} catch (SQLException e) {
e.printStackTrace();
}
It is easy to get the values of table. All you need to do is provide the column name of account table which you already got in your ResultSet.
u.setAccountID(rsu.getLong("accId"));
Here account id is stored in Result set object which you already retrieved from database in result set
1) Include account data in your SQL like so:
SELECT user.*, account.* FROM user INNER JOIN account ON user.id = account.user WHERE user.id = 1
2) Access account field just like user fields:
u.setAccountType(rsu.getString("accountType"));
u.setAccountNo(rsu.getString("accountNo"));
3) Make sure to close Statement in finally block.
4) You dont need to iterate the whole result set since you are expecting only one record. Just replace while with if.
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.
I've got a MySQL database which contains a table named User. It has two columns. One is named ID, the other is EMAIL. It has more columns but that is irrelevant to the question.
In my DAO-object, I'd like to create a method named findByEmail. It currently looks like this:
#Override
public User findByEmail(String email) {
Object obj = em.createQuery("FROM User WHERE EMAIL LIKE :email").setParameter("email", email).getSingleResult();
User user = (User)obj;
return user;
}
This gives a nullpointer-exception. My guess is, my query is wrong. Can anyone help me out on this one?
Apparently, the MySQL-server was configured to block all remote connections. It now works (with the JPA query supplied by vels4j, select r FROM User r WHERE r.EMAIL = :email)
as you said, you can do it that way. But if you wanted to follow a closer SQL approach, you might as well use
#Override
public User findByEmail(String email) {
Object obj = em.createNativeQuery("SELECT * FROM User WHERE EMAIL = " + email).getSingleResult();
User user = (User)obj;
return user;
}
Also if you want to shorten the code you could declare and cast the user in the same line you execute the query, like so:
User user = (User) em.createNativeQuery("SELECT * FROM User WHERE EMAIL = " + email).getSingleResult();
Hope it helps!
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();