简体   繁体   English

带有MySQL的Hibernate错误org.hibernate.exception.SQLGrammarException

[英]Hibernate error org.hibernate.exception.SQLGrammarException with MySQL

I'm creating a project in Java and MySQL with Hibernate, I can get data from the database, but I can't save data into it because shows error, I'm trying to create this project with MVC and annotations very simple, without Spring or nothing, just Hibernate. 我正在使用Hibernate在Java和MySQL中创建一个项目,我可以从数据库中获取数据,但是由于显示错误,我无法将数据保存到该项目中,我试图使用MVC和注释创建该项目非常简单,而没有春天还是什么都没有,只是休眠。 This are my classes: 这是我的课程:

Quote.java Quote.java

package stock.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;


@SuppressWarnings("serial")
@Entity
@Table(name = "quote")
public class Quote implements Serializable{

    public Quote(Long idQuote, int idCompany, BigDecimal price, Long volume,
            Date lastDate, Time lastTime, Long avgVolume, BigDecimal marketCap,
            BigDecimal change, BigDecimal percChange, String marketPeriod) {
        super();
        this.idQuote = idQuote;
        this.idCompany = idCompany;
        this.price = price;
        this.volume = volume;
        this.lastDate = lastDate;
        this.lastTime = lastTime;
        this.avgVolume = avgVolume;
        this.marketCap = marketCap;
        this.change = change;
        this.percChange = percChange;
        this.marketPeriod = marketPeriod;
    }

    public Quote() {
    }

    @Id
    @Column(name = "id_quote")
    private Long idQuote;

    @Id
    @Column(name = "id_company")
    private int idCompany;

    private BigDecimal price;
    private Long volume;

    @Column(name = "last_date")
    private Date lastDate;

    @Column(name = "last_time")
    private Time lastTime;

    @Column(name ="avg_volume")
    private Long avgVolume;

    @Column(name = "market_cap")
    private BigDecimal marketCap;

    private BigDecimal change;

    @Column(name = "perc_change")
    private BigDecimal percChange;

    @Column(name = "market_period")
    private String marketPeriod;

    public Long getIdQuote() {
        return idQuote;
    }

    public void setIdQuote(Long idQuote) {
        this.idQuote = idQuote;
    }

    public int getIdCompany() {
        return idCompany;
    }

    public void setIdCompany(int idCompany) {
        this.idCompany = idCompany;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Long getVolume() {
        return volume;
    }

    public void setVolume(Long volume) {
        this.volume = volume;
    }

    public Date getLastDate() {
        return lastDate;
    }

    public void setLastDate(Date lastDate) {
        this.lastDate = lastDate;
    }

    public Time getLastTime() {
        return lastTime;
    }

    public void setLastTime(Time lastTime) {
        this.lastTime = lastTime;
    }

    public Long getAvgVolume() {
        return avgVolume;
    }

    public void setAvgVolume(Long avgVolume) {
        this.avgVolume = avgVolume;
    }

    public BigDecimal getMarketCap() {
        return marketCap;
    }

    public void setMarketCap(BigDecimal marketCap) {
        this.marketCap = marketCap;
    }

    public BigDecimal getChange() {
        return change;
    }

    public void setChange(BigDecimal change) {
        this.change = change;
    }

    public BigDecimal getPercChange() {
        return percChange;
    }

    public void setPercChange(BigDecimal percChange) {
        this.percChange = percChange;
    }

    public String getMarketPeriod() {
        return marketPeriod;
    }

    public void setMarketPeriod(String marketPeriod) {
        this.marketPeriod = marketPeriod;
    }

}

QuoteDaoImpl.java QuoteDaoImpl.java

package stock.dao;

import java.sql.Time;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import stock.model.Quote;

@SuppressWarnings("rawtypes")
public class QuoteDaoImpl implements QuoteDao{

    private Session session;

    public QuoteDaoImpl(Session session) {
        this.session = session;
    }

    @Override
    public void setQuote(Quote quote) {
        session.save(quote);
    }

}

QuoteController.java QuoteController.java

package stock.controller;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import stock.dao.QuoteDao;
import stock.dao.QuoteDaoImpl;
import stock.model.Quote;

@SuppressWarnings("deprecation")
public class QuoteController {

    private QuoteDao quoteDao;
    private static final SessionFactory sessionFactory;
    private Session session;

    static {
        try {
            // Initialize factory using contents of hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }

    }

    @SuppressWarnings("unused")
    private static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private void openSession(){
        session = sessionFactory.openSession();
        session.beginTransaction();
        quoteDao = new QuoteDaoImpl(session);
    }

    private void closeSession(){
        session.getTransaction().commit();
        session.close();
    }

    public QuoteController() {
        this.openSession();
    }

    public void setQuote(){
        Quote qte = new Quote();
        qte.setIdQuote(new Long("20130418140532"));
        qte.setIdCompany(4);
        qte.setLastDate(new Date(20130418));
        qte.setLastTime(new Time(140532));
        qte.setPrice(new BigDecimal(2.35));
        quoteDao.setQuote(qte);
        this.closeSession();
    }

}

hibernate.cfg.xml hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC 
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration> 
    <session-factory> 
        <!-- Session Thread  -->
        <property name="current_session_context_class">thread</property>

        <!-- Database connection settings --> 
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
        <property name="connection.url">jdbc:mysql://localhost:3306/stock</property> 
        <property name="connection.username">root</property> 
        <property name="connection.password">root</property>   

        <!-- JDBC connection pool (use the built-in) --> 
        <property name="connection.pool_size">1</property>   

        <!-- SQL dialect --> 
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>   
<!--        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>    -->

        <!-- Echo all executed SQL to stdout --> 
        <property name="show_sql">true</property>   
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">validate</property>

        <!-- configuration pool via c3p0-->
        <property name="c3p0.acquire_increment">1</property>
        <property name="c3p0.idle_test_period">3600</property> <!-- seconds -->
        <property name="c3p0.min_size">3</property>
        <property name="c3p0.max_size">5</property>
        <property name="c3p0.max_statements">0</property>
        <property name="c3p0.timeout">3605</property> <!-- seconds -->
        <property name="hibernate.c3p0.preferredTestQuery">select 1;</property>

        <!-- Mapping files --> 
        <mapping class="stock.model.Company"/>
        <mapping class="stock.model.Quote"/>
<!--        <mapping class="stock.model.QuoteInfo"/> -->
    </session-factory> 
</hibernate-configuration>

As you can see in the configuration file, I've tried with org.hibernate.dialect.MySQLDialect and org.hibernate.dialect.MySQLInnoDBDialect but shows the same error. 正如您在配置文件中看到的那样,我尝试使用org.hibernate.dialect.MySQLDialect和org.hibernate.dialect.MySQLInnoDBDialect,但显示了相同的错误。

And the error shown is: 并且显示的错误是:

ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, last_date, last_time, market_cap, market_period, perc_change, price, vol' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, last_date, last_time, market_cap, market_period, perc_change, price, vol' at line 1
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at sun.proxy.$Proxy10.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3028)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3469)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1213)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:402)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
    at stock.controller.QuoteController.closeSession(QuoteController.java:46)
    at stock.controller.QuoteController.setQuote(QuoteController.java:72)
    at stock.view.Test.main(Test.java:13)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, last_date, last_time, market_cap, market_period, perc_change, price, vol' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2683)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2144)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2444)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2347)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    ... 18 more

The table quote is: 该表的引用是:

CREATE TABLE `quote` (
  `id_quote` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT 'Codigo identificación quote\\nYYYYMMDDHHMMSS',
  `id_company` int(11) NOT NULL DEFAULT '0' COMMENT 'Id compañia ',
  `price` decimal(10,4) NOT NULL COMMENT 'Precio actual de la acción',
  `volume` bigint(20) NOT NULL COMMENT 'volumen actual de la acción',
  `last_date` date NOT NULL COMMENT 'fecha de la acción',
  `last_time` time NOT NULL COMMENT 'hora de la acción',
  `avg_volume` bigint(20) NOT NULL COMMENT 'volumen promedio actual de la acción sobre los últimos 30 días',
  `market_cap` decimal(10,4) DEFAULT NULL COMMENT 'El valor total de la compañia en el mercado actualmente',
  `change` decimal(5,2) DEFAULT NULL COMMENT 'Valor que la acción ha cambiado con respecto al inicio del día',
  `perc_change` decimal(5,2) DEFAULT NULL COMMENT 'Porcentaje que la acción ha cambiado con respecto al inicio del día',
  `market_period` varchar(2) DEFAULT NULL COMMENT 'Periodo de la acción\\nAH: After Hours\\nPM: Pre-Market\\nNH: Horas normales',
  PRIMARY KEY (`id_quote`,`id_company`),
  KEY `quote_ibfk_1` (`id_company`),
  CONSTRAINT `quote_ibfk_1` FOREIGN KEY (`id_company`) REFERENCES `company` (`id_company`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Thanks for your help. 谢谢你的帮助。

try to add to the field private Long idQuote; 尝试将private Long idQuote;添加到字段中private Long idQuote; columnDefintion like "bigInt(8)" , may do the trick "bigInt(8)"这样的columnDefintion可以解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.hibernate.exception.SQLGrammarException:无法插入,使用mysql休眠 - org.hibernate.exception.SQLGrammarException: could not insert, hibernate with mysql 通过Hibernate使用MySQL:org.hibernate.exception.SQLGrammarException - using MySQL by Hibernate : org.hibernate.exception.SQLGrammarException Spring Hibernate:org.hibernate.exception.SQLGrammarException - Spring hibernate: org.hibernate.exception.SQLGrammarException JPA 异常:org.hibernate.exception.SQLGrammarException - JPA Exception: org.hibernate.exception.SQLGrammarException 获取异常:org.hibernate.exception.sqlgrammarexception - Getting Exception : org.hibernate.exception.sqlgrammarexception 获取异常org.hibernate.exception.SQLGrammarException: - getting exception org.hibernate.exception.SQLGrammarException: 错误 org.hibernate.exception.SQLGrammarException: 无法提取 ResultSet - Error org.hibernate.exception.SQLGrammarException: could not extract ResultSet InvalidDataAccessResourceUsageException:org.hibernate.exception.SQLGrammarException: - InvalidDataAccessResourceUsageException: org.hibernate.exception.SQLGrammarException: org.hibernate.exception.SQLGrammarException:休眠不会加入列 - org.hibernate.exception.SQLGrammarException: hibernate will not join column 休眠注释错误(org.hibernate.exception.SQLGrammarException:无法插入:[com.hib.ex.entity.Node]) - Hibernate Annotation Error (org.hibernate.exception.SQLGrammarException: could not insert: [com.hib.ex.entity.Node])
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM