I have a StudentInfo table, I need to fetch all the names under name column in the table.
can any one help me to correct me in the below function
@Override
public List<StudentRecord> getAllStudentNames(){
Session session = HibernateUtil.getSessionFactory().openSession();
try {
List<StudentRecord> smrList = new ArrayList<StudentRecord>();
String SQL_QUERY = "select smr.studentName from StudentRecord as smr";
Query query = session.createQuery(SQL_QUERY)
smrList = query.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.flush();
session.close();
HibernateUtil.getSessionFactory().close();
}
return smrList
}
You want names, and names are strings, so you don’t want a
List<StudentRecord>, but aList<String>.The
query.list()method returns a List, so there’s no need to create a new ArrayList, only to replace it by the list returned by the method.So you just need the following (which respects Java naming conventions):
Note that I named the variable
hql, and notsql, since HQL and SQL are not the same language, and you’re using HQL here. The above query will work if the persistent property of theStudentRecordclass is namedstudentName. The name of the table and the name of the column are irrelevant, since HQL uses entities for its queries, and not tables.Finally, you should not catch Exception: it will only hide errors. Let the exception propagate to the caller.
It seems you lack basic Java knowledge. I would start by learning Java with simpler problems before using Hibernate, which is a complex framework.