[我试图通过URL直接从表中获取数据时遇到SQLGrammarException

问题描述 投票:0回答:1

我正在使用Apache Tomcat v9.0,并且在运行简单的MVC项目时出现错误。

  1. Alien.class
@Entity(name="alien")
public class Alien {
    @Id
    @Column(name="aid")
    private int aid;
    @Column(name="aname",length = 50)
    private String aname;



    public Alien(int aid, String aname) {
        super();
        this.aid = aid;
        this.aname = aname;
    }
    public int getAid() {
        return aid;
    }
    public void setAid(int aid) {
        this.aid = aid;
    }
    public String getAname() {
        return aname;
    }
    public void setAname(String aname) {
        this.aname = aname;
    }
    @Override
    public String toString() {
        return "Alien [aid=" + aid + ", aname=" + aname + "]";
    }



}

2.AlienDao

package com.example.OnlySpringMVCdemo.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.example.springMVCdemo.models.Alien;

@Component
public class AlienDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public List<Alien> getAlien(){
        System.out.println("Inside getAliens method in DAO...");
        Session session = sessionFactory.getCurrentSession();
        System.out.println(session.createQuery("from alien", Alien.class).getQueryString());
        List<Alien> aliens = session.createQuery("from alien",Alien.class).list();
        System.out.println("the list is"+aliens);
        return aliens;
    }

}

3.HomeController

package com.example.OnlySpringMVCdemo;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.OnlySpringMVCdemo.dao.AlienDao;
import com.example.springMVCdemo.models.Alien;




@Controller
public class HomeController {


      @Autowired 
      private AlienDao dao;



    @RequestMapping("/")
    public String home() {
        System.out.println("Home page requested");
        return "index";
    }

    @ModelAttribute
    public void modelData(Model m) {
        m.addAttribute("name", "Piyush");
    }




    @GetMapping("getAliens")
    public String getAliens(Model m) {
        System.out.println("Inside the getAliens URL....");
        m.addAttribute("result", dao.getAlien());
        return "showAliens";

    }

    @RequestMapping("add")
    /*public String add(HttpServletRequest req) {
        int i = Integer.parseInt(req.getParameter("num1"));
        int j = Integer.parseInt(req.getParameter("num2"));

        int num3 = i+j;
        HttpSession session = req.getSession();
        session.setAttribute("num3", num3);

        return "result.jsp";
    }*/

    /*public String add(@RequestParam("num1") int i,@RequestParam("num2")int j,HttpSession session) {
        int num3= i+j;
        session.setAttribute("num3", num3);
        return "result.jsp";
    }*/

    /*
     * public ModelAndView add(@RequestParam("num1") int i,@RequestParam("num2")int
     * j) {
     * 
     * ModelAndView mv = new ModelAndView(); mv.setViewName("result"); int num3 =
     * i+j; mv.addObject("num3", num3); return mv; }
     */



    //GetMethods



    /*
     * @RequestMapping(value="addAlien",method=RequestMethod.POST) public String
     * addAlien(@ModelAttribute("alien") Alien a) {
     * //System.out.println(a.getAid()+"          "+a.getAname()); return "result";
     * }
     */

    @PostMapping(value="addAlien")
    public String addAlien(@ModelAttribute("alien") Alien a) {
        //System.out.println(a.getAid()+"          "+a.getAname());
        return "result";
    }

}

4.dispatcherServlet-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">



    <ctx:component-scan base-package="com.example.OnlySpringMVCdemo"></ctx:component-scan>
    <ctx:annotation-config></ctx:annotation-config>

<!-- Configurations done to use ORM using Hibernate:-Start -->
<!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcldb"/>
        <property name="user" value="piyush" />
        <property name="password" value="admin" />
        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>
    <!-- Step 2: Setup Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.example.springMVCdemo.models" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager"></tx:annotation-driven>
    <!-- Add support for reading web resources: css, images, js, etc ... -->
    <!-- <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources> -->

<!-- Configurations done to use ORM using Hibernate:-End -->



    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  1. web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>


  <servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>

   <servlet-mapping>
   <servlet-name>dispatcherServlet</servlet-name>
   <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

我试图在地址栏中简单地调用URL http://localhost:8080/ORMMVC/getAliens,但出现以下错误:

HTTP Status 500 – Internal Server Error
Type Exception Report

Message Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select a1_0.aid, a1_0.aname from alien as a1_0]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select a1_0.aid, a1_0.aname from alien as a1_0]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: JDBC exception executing SQL [select a1_0.aid, a1_0.aname from alien as a1_0]
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    org.hibernate.query.spi.AbstractQuery.list(AbstractQuery.java:1365)
    com.example.OnlySpringMVCdemo.dao.AlienDao.getAlien(AlienDao.java:23)
    com.example.OnlySpringMVCdemo.dao.AlienDao$$FastClassBySpringCGLIB$$93172482.invoke(<generated>)
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
    com.example.OnlySpringMVCdemo.dao.AlienDao$$EnhancerBySpringCGLIB$$600bf15f.getAlien(<generated>)
    com.example.OnlySpringMVCdemo.HomeController.getAliens(HomeController.java:45)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java spring-mvc nhibernate-mapping
1个回答
0
投票

**此问题的两个原因是:**

  1. 之所以如此,是因为Hibernate正在生成HT_Alien表,这是一个临时表,其背后的原因是Hibernate核心版本6.0.0.Alpha3。

  2. 我在Alien(Entity)类中没有默认的构造函数,]

  3. 建议:

各位,请在使用Hibernate的ORM时使用hibernate core 5.4.1.Final。下面是相同的依赖项:

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

问题已解决!

© www.soinside.com 2019 - 2024. All rights reserved.