Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hibernate.hql.internal.ast.QuerySyntaxException: is not mapped [from Team]

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;
}   
like image 671
Serhii Soboliev Avatar asked Feb 15 '14 10:02

Serhii Soboliev


2 Answers

"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.

like image 30
MolodecSerg Avatar answered Oct 19 '22 12:10

MolodecSerg


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.

like image 144
Hari Avatar answered Oct 19 '22 14:10

Hari