I have this code of hibernateTemplate to verify the username and password but this code was working fine with MYSQL but failed in Oracle and was showing some problem in DAO class as it created the table but not saving the value.For project it was necessary to use Oracle
package com.infotech.dao.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.infotech.dao.StudentDAO;
import com.infotech.model.Student;
#Repository("studentDAO")
public class StudentDAOImpl implements StudentDAO {
#Autowired
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
#Override
public boolean saveStudent(Student student) {
int id = (Integer)hibernateTemplate.save(student);
if(id>0)
return true;
return false;
}
#SuppressWarnings("unchecked")
#Override
public Student getStudentDetailsByEmailAndPassword(String email,String password){
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);
detachedCriteria.add(Restrictions.eq("email", email));
detachedCriteria.add(Restrictions.eq("password", password));
List<Student> findByCriteria = (List<Student>) hibernateTemplate.findByCriteria(detachedCriteria);
if(findByCriteria !=null && findByCriteria.size()>0)
return findByCriteria.get(0);
else
return null;
}
}
**Now I again changed the DAO class instead of HibernateTemplate I used Session Interface and now value are saving in Database but the Validation of username and password is not taking place some issues in Hibernate Template.Please suggest changes instead of hibernate template what should I use
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.infotech.dao.StudentCredentialDao;
import com.infotech.model.Student;
import com.infotech.model.StudentCredential;
#Repository("StudentCredentialDAO")
public class StudentCredentialDaoImpl implements StudentCredentialDao {
#Autowired
private SessionFactory sessionFactory;
#Autowired
private HibernateTemplate hibernateTemplate;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public boolean saveStudentCred(StudentCredential stuCred) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(stuCred);
tx.commit();
session.close();
return true;
}
#SuppressWarnings("unchecked")
#Override//This method is creating problem as I need to use something else other than Hibernate Template
public StudentCredential getStudentDetailsByUnameAndPassword(String uname,String password){
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(StudentCredential.class);
detachedCriteria.add(Restrictions.eq("uname", uname));
detachedCriteria.add(Restrictions.eq("password", password));
List<StudentCredential> findByCriteria = (List<StudentCredential>)hibernateTemplate.findByCriteria(detachedCriteria);
if(findByCriteria !=null && Hibernate template .size()>0)
return findByCriteria.get(0);
else
return null;
}
}
#Repository
public class LoginDAOImpl implements LoginDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public String loginCheck(String customerID, String password) {
Session currentSession = sessionFactory.getCurrentSession();
Query theQuery = currentSession.createQuery("from UserAccount u where u.customerID=:id AND u.password=:pass");
theQuery.setParameter("id", customerID);
theQuery.setParameter("pass", password);
List results = theQuery.list();
if ((results!=null) && (results.size()>0)){
return "success";
}
else {
return "failed";
}
}
You could use in this way
Related
I have a CustomerUserDetailsService class, which is part of an implementation of Spring Boot authentication. I have tested my code manually, and it works correctly, allowing me to successfully log in to my app. However, I am unable to work out how to test the CustomerUserDetailsService.
As a unit test, I believe I would need to mock the userRepository member variable, but whatever I try in my test fails, the reason being userRepository is set to null. I've tried adding the #Repository annotation to userRepository but am told that is not allowed because it is an interface. There's also the fact that loadUserByUsername returns an instance of CustomUserDetails, which is just an implementation of an interface, so I have no idea how I'd mock that dependency?
I've also tried doing some kind of integration test but had similar issues, probably due to incorrect annotations on the test itself. In an ideal world, I'd prefer a unit test and would be extremely grateful for any guidance as to how to set it up.
These are the relevant classes...
CustomerUserDetailsService:
package com.phil.urlshortener.security;
import com.phil.urlshortener.model.User;
import com.phil.urlshortener.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class CustomUserDetailsService implements UserDetailsService {
#Autowired private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user);
}
}
User:
package com.phil.urlshortener.model;
import lombok.Data;
import javax.persistence.*;
#Data
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, unique = true, length = 50)
private String username;
#Column(nullable = false, length = 64)
private String password;
}
UserRepository:
package com.phil.urlshortener.repositories;
import com.phil.urlshortener.model.User;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> {
#Query("SELECT u FROM User u WHERE u.username = ?1")
User findByUsername(String username);
}
CustomUserDetails:
package com.phil.urlshortener.security;
import com.phil.urlshortener.model.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class CustomUserDetails implements UserDetails {
private final User user;
public CustomUserDetails(User user) {
this.user = user;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getUsername();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Maybe you forgot to use mockito annotation #RunWith(MockitoJUnitRunner.class).
Here it's the unit test for CustomUserDetailsService :
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class CustomUserDetailsService {
#Mock
private UserRepository userRepository;
private CustomUserDetailsService customUserDetailsService;
#Before
public void setUp() throws Exception {
customUserDetailsService = new CustomUserDetailsService(userRepository);
}
#Test
public void GIVEN_username_THEN_return_user_details() {
//Arrange
final String username = "existingUserName";
final User user = mock(User.class);
when(userRepository.findByUsername(username)).thenReturn(user);
//Act
final UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
//Assert
assertNotNull(userDetails);
assertEquals(user, ReflectionTestUtils.getField(userDetails, "user"));
}
}
I am trying to create a login concept with spring boot application, so i just need row count of a mysql table, I tried with various internet answers but nothing got solution, please your help and suggestion is appriciate. I will mention my code bellow.
Controller
#GetMapping("/Login")
public String Login(Model model) {
model.addAttribute("customer", new Customer());
return "login";
}
#PostMapping("/LoginProcess")
public String LoginProcess(#ModelAttribute("customer") Customer thecustomer,HttpSession session) {
System.out.println(thecustomer);
Customer result = customerservice.Login_service(thecustomer.getUserName(),thecustomer.getPassword());
if(result==null)
{
return "login";
}
else if(result.getRole().equals("1"))
{
return "admindash";
}
else
{
//session.setAttribute("jsp_uname", result.getUserName());
return "customerdash";
}
}
CustomerImplDao
import javax.persistence.EntityManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.filedemo.model.Customer;
#Repository
public class CustomerDaoImpl implements Customerdao {
#Autowired
private EntityManager entityManager;
#Override
public void save(Customer theCustomer) {
Session cursession = entityManager.unwrap(Session.class);
//If Id=0 then It will do insert or id=x then it will do update
cursession.save(theCustomer);
}
#Override
public Customer Login(String username,String password) {
Session cursession = entityManager.unwrap(Session.class);
String hql="from Customer c where c.UserName=:username and c.password=:password";
Query<Customer> query = cursession.createQuery(hql,Customer.class);
query.setParameter("username", username);
query.setParameter("password", password);
Customer theCustomer = query.uniqueResult();
System.out.println("******************"+query.getResultList().size());
return theCustomer;
}
}
You can simply use:
query.getResultList().size();
Or on database siede:
entityManager.creteQuery("select count(c) from Customer c where c.UserName=:username and c.password=:password", Long.class).getSingleResult();
To do that, you need to inject it on top of your service (bean):
#Autowired
private EntityManager entityManager;
I'm new with Java Spring, I need a guidance with Mockito.
I tried to test my Service Layer but it keeps failing to verify the mock username and email address.
I'm currently really confused on how should I do it properly.
Thanks you!
UserService.java
package com.example.newproject.newproject.service;
import com.example.newproject.newproject.entity.User;
import java.util.List;
public interface UserService {
boolean addUser(String username,String email);
List<User> viewAllUsers();
}
UserServiceImpl.java
package com.example.newproject.newproject.service.impl;
import com.example.newproject.newproject.entity.User;
import com.example.newproject.newproject.repository.UserRepository;
import com.example.newproject.newproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Override
public boolean addUser(String username, String email) {
if(userRepository.findByUsernameAndEmail(username, email) == null)
{
User user = new User();
user.setUsername(username);
user.setEmail(email);
userRepository.save(user);
return false;
}else{
return true;
}
}
#Override
public List<User> viewAllUsers() {
return userRepository.findAll();
}
}
My Mock
#Test
public void testAddUser(){
Mockito.when(userRepository.findByUsernameAndEmail("Google","google#google.com")).then(invocationOnMock -> {
User user = new User();
return user;
});
boolean result = userService.addUser("Google","google#google.com");
Assert.assertFalse(result);
Mockito.verify(userRepository, Mockito.times(1)).save(userArgumentCaptor.capture());
User user = userArgumentCaptor.getValue();
Assert.assertEquals("Google", user.getUsername());
Assert.assertEquals("google#google.com", user.getEmail());
}
The error I get is
java.lang.AssertionError
during run
I am new to Spring. When I'm trying to view localhost:8080/persons, I am getting an error
java.lang.NullPointerException: null
at by.bsuir.task.service.PersonServiceImpl.listPersons(PersonServiceImpl.java:32) ~[classes/:na]
at by.bsuir.task.controller.PersonController.listPersons(PersonController.java:31) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at ...
I think problem is in PersonDAOImpl, method listPersons(), session getting NPE. But I'm not sure.
My project below:
PersonServiceImpl
package by.bsuir.task.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import by.bsuir.task.dao.PersonDAO;
import by.bsuir.task.model.Person;
"personService"
public class PersonServiceImpl implements PersonService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
#Transactional
public void addPerson(Person p) {
this.personDAO.addPerson(p);
}
#Transactional
public void updatePerson(Person p) {
this.personDAO.updatePerson(p);
}
#Transactional
public List<Person> listPersons() {
return this.personDAO.listPersons();
}
#Transactional
public Person getPersonById(int id) {
return this.personDAO.getPersonById(id);
}
#Transactional
public void removePerson(int id) {
this.personDAO.removePerson(id);
}
}
PersonDAOImpl
package by.bsuir.task.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import by.bsuir.task.model.Person;
#Repository
public class PersonDAOImpl implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
public void addPerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Person saved successfully, Person Details="+p);
}
public void updatePerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Person updated successfully, Person Details="+p);
}
"unchecked"
public List<Person> listPersons() {
Session session = this.sessionFactory.getCurrentSession();
List<Person> personsList = session.createQuery("from Person").list();
for(Person p : personsList){
logger.info("Person List::"+p);
}
return personsList;
}
public Person getPersonById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details="+p);
return p;
}
public void removePerson(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
if(null != p){
session.delete(p);
}
logger.info("Person deleted successfully, person details="+p);
}
}
PersonController
package by.bsuir.task.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import by.bsuir.task.model.Person;
import by.bsuir.task.service.PersonService;
#Controller
public class PersonController {
#Autowired
private PersonService personService;
required=true
#Qualifier(value = "personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
value = "/persons", method = RequestMethod.GET
public String listPersons(Model model) {
List<Person> listOfUsers = this.personService.listPersons();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", listOfUsers);
return "person";
}
//For add and update person both
value= "/person/add", method = RequestMethod.POST
public String addPerson(#ModelAttribute("person") Person p){
if(p.getId() == 0){
//new person, add it
this.personService.addPerson(p);
}else{
//existing person, call update
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
"/remove/{id}"
public String removePerson(#PathVariable("id") int id){
this.personService.removePerson(id);
return "redirect:/persons";
}
"/edit/{id}"
public String editPerson(#PathVariable("id") int id, Model model){
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
Cannot seem to find what my problem is, I'm just learning about Spring\Hibernate
You are missing some code in your question.
For the class PersonServiceImpl, the code should be as follows:
#Service("personService")
public class PersonServiceImpl implements PersonService {
#Autowired
private PersonDAO personDAO;
// Some other code
}
Add #Autowired annotation to the PersonDAO class without doing so will result in NullPointerException as you did not create any object for that class, annotating it with #Autowired will tell the Spring where an injection needs to occur.
I'm working on little Spring MVC CRUD application. Got some strange problems:
configuration class:
package sbk.spring.simplejc.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration //Specifies the class as configuration
#ComponentScan("sbk.spring.simplejc") //Specifies which package to scan
//#Import({DataBaseConfig.class})
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
#EnableWebMvc //Enables to use Spring's annotations in the code
public class WebAppConfig extends WebMvcConfigurerAdapter{
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
application.properties:
#DB properties:
db.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
db.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=Examples
db.username=sa
db.password=
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=sbk.spring.simplejc.entity
#Entity class:
package sbk.spring.simplejc.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Team")
public class Team {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer rating;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
}
Controller class:
package sbk.spring.simplejc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import sbk.spring.simplejc.service.ITeamService;
#Controller
public class TeamController {
#Autowired
ITeamService service;
#RequestMapping(value="/")
public ModelAndView goToHelloPage() {
ModelAndView view = new ModelAndView();
view.addObject("teamList", service.listTeams());
return view;
}
}
Error stack trace:
org.hibernate.hql.internal.ast.QuerySyntaxException: Team is not mapped [from Team]
org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3420)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3309)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1777)
sbk.spring.simplejc.dao.HibTeamDAO.listTeams(HibTeamDAO.java:23)
sbk.spring.simplejc.service.TeamService.listTeams(TeamService.java:27)
I haven't got a clue about this issue.
Update
DAO class:
package sbk.spring.simplejc.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sbk.spring.simplejc.entity.Team;
#Repository
public class HibTeamDAO implements TeamDAO {
#Autowired
private SessionFactory sessionFactory;
public void addTeam(Team team) {
sessionFactory.getCurrentSession().save(team);
}
public void updateTeam(Team team) {
sessionFactory.getCurrentSession().update(team);
}
#SuppressWarnings("unchecked")
public List<Team> listTeams() {
return sessionFactory.getCurrentSession().createQuery("from Team").list();
}
#SuppressWarnings("unchecked")
public Team getTeamById(Integer teamID) {
Session session = sessionFactory.getCurrentSession();
List<Team> listTeam = session.createQuery("from Team t where t.id = :teamID")
.setParameter("teamID", teamID)
.list();
return listTeam.size() > 0 ? (Team)listTeam.get(0) : null;
}
public void removeTeam(Integer teamID) {
Team team = (Team) sessionFactory.getCurrentSession().load(Team.class, teamID);
if(team != null){
sessionFactory.getCurrentSession().delete(team);
}
}
#Override
public Integer count() {
return (Integer) sessionFactory.getCurrentSession().createQuery("select count(t) from Team t").uniqueResult();
}
}
TeamController class:
package sbk.spring.simplejc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import sbk.spring.simplejc.service.ITeamService;
#Controller
public class TeamController {
#Autowired
ITeamService service;
#RequestMapping(value="/")
public ModelAndView goToHelloPage() {
ModelAndView view = new ModelAndView();
view.addObject("teamList", service.listTeams());
return view;
}
}
Update
Now I got rid from this problem by changing DAO method from
return sessionFactory.getCurrentSession().createQuery("from Team").list();
to
return sessionFactory.getCurrentSession().createQuery("from sbk.spring.simplejc.entity.Team").list();
But received another issue: every query return null despite of existing rows in Team table.
Update
Finally I noticed warning messages:
Feb 15, 2014 7:01:05 PM org.hibernate.hql.internal.QuerySplitter concreteQueries
WARN: HHH000183: no persistent classes found for query class: from sbk.spring.simplejc.entity.Team
Update
At least I've sorted out this issue by adding next row of code in dataSource bean definition in WebAppConfig:
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setAnnotatedClasses(new Class[]{Team.class});//new row!!!
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
In my case it was because I didn't have the hibernate packagesToScan property. I see that you have it. May be this comment will be useful for someone who missed it.
"No, in this instance I've got org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: * near line 1, column 8 [select * from Team] – Sobik Feb 15 at 10:29"
Instead "Select * from Team" try write "from Team". Because Hibernate works with java entity.