org.hibernate.hql.internal.ast.QuerySyntaxException:未映射[来自Team]

时间:2014-02-15 10:18:39

标签: java spring hibernate spring-mvc

我正在开发一些Spring MVC CRUD应用程序。遇到了一些奇怪的问题:

  • 配置类:

    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上课:

    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;
            }
        }
    
  • 控制器类:

    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;
        }
    
    }
    
  • 错误堆栈跟踪:

        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)
    

我对这个问题一无所知。


更新

  • DAO课程:

    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上课:

    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;
        }
    
    }
    

更新

现在我通过改变

中的DAO方法摆脱了这个问题
return sessionFactory.getCurrentSession().createQuery("from Team").list();

return sessionFactory.getCurrentSession().createQuery("from sbk.spring.simplejc.entity.Team").list();

但是收到了另一个问题:尽管Team表中存在行,但每个查询都返回null。


更新

最后我注意到了警告信息:

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

更新

至少我通过在dataSource中的WebAppConfig bean定义中添加下一行代码来解决这个问题:

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;
}   

2 个答案:

答案 0 :(得分:4)

在我的情况下,这是因为我没有hibernate packagesToScan属性。我知道你拥有它。可能这个评论对错过它的人有用。

答案 1 :(得分:0)

“不,在这个例子中我得到了org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌:*靠近第1行,第8列[select * from Team] - Sobik Feb 15 at 10:29”

相反“从团队中选择*”尝试写“来自团队”。因为Hibernate适用于java实体。