Reputation: 967
I'm developing a spring web application with Hibernate. I have faced an error when getting column values from a table to a list. But this error keeps coming. Please help me put. Thanks in advance.
@Repository
@Transactional
public class GetProjectsDaoImpl implements GetProjectsDao {
@Autowired
private HibernateUtilImpl hibernateutilimpl;
public List<Projects> getProjects() {
String sql = "select project_id from project";
List<Object[]> projectObjects = hibernateutilimpl.fetchAll(sql);
List<Projects> projectsList = new ArrayList<Projects>();
for(Object[] projectObject: projectObjects) {
Projects project = new Projects();
String id = (String) projectObject[0];
project.setProjectId(id);
projectsList.add(project);
}
return projectsList;
}
}
@Repository
public class HibernateUtilImpl implements HibernateUtil {
@Autowired
private SessionFactory sessionFactory;
public <T> Serializable create(final T entity) {
return sessionFactory.getCurrentSession().save(entity);
}
public <T> T update(final T entity) {
sessionFactory.getCurrentSession().update(entity);
return entity;
}
public <T> void delete(final T entity) {
sessionFactory.getCurrentSession().delete(entity);
}
@SuppressWarnings("rawtypes")
public <T> List<T> fetchAll(String query) {
return sessionFactory.getCurrentSession().createNativeQuery(query).list();
}
}
Upvotes: 1
Views: 1635
Reputation: 172
I have following suggestions. First change:
List<Object[]> projectObjects = hibernateutilimpl.fetchAll(sql);
to:
List<Object> projectObjects = hibernateutilimpl.fetchAll(sql);
Next, change:
for(Object[] projectObject: projectObjects) {
String id = (String) projectObject[0];
to
for(Object projectObject: projectObjects) {
String id = (String) projectObject;
The above change is needed because you are selecting only a single column. Object[]
is used only when selecting more then one column.
Upvotes: 2