How to select a row based on a unique column. In my table, Id is auto generated. I am using phone number to select the row which is unique in my table schema.
Ex:
Id Phone Name
1 2209897 abc
2 5436567 def
Here, Id is primary key. Phone is unique.
I am using phone to login. I donot want a list to be generated but a single row as output.
@Repository
public class CustomerDetailsDAOImpl implements CustomerDetailsDAO {
@Autowired
SessionFactory sessionFactory;
@Override
@Transactional
public List<CustomerDetails> getCustomer(String customerPhone) {
Session session = sessionFactory.openSession();
Query q = session.createQuery("from CustomerDetails where customerPhone =:p");
q.setParameter("p", customerPhone);
List<CustomerDetails> customer = q.getResultList();
session.close();
return customer;
}
Use getSingleResult() instead of using getListResult().This Executes a SELECT query that returns a single untyped result. So whenever you expect a single record to be retrieved with unique type, should use getSingleResult().
@Repository
public class CustomerDetailsDAOImpl implements CustomerDetailsDAO {
@Autowired
SessionFactory sessionFactory;
@Override
@Transactional
public List<CustomerDetails> getCustomer(String customerPhone) {
Session session = sessionFactory.openSession();
Query q = session.createQuery("from CustomerDetails where customerPhone =:p");
q.setParameter("p", customerPhone);
CustomerDetails customer = q.getSingleResult();
session.close();
return customer;
}
Hope this helps :)