0

我正在使用 Hibernate 在 Java 和 MySQL 中创建一个项目,我可以从数据库中获取数据,但我无法将数据保存到其中,因为显示错误,我正在尝试使用 MVC 和注释非常简单地创建这个项目,没有春天或什么都没有,只是休眠。这是我的课:

引用.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

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

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

}

休眠.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>

正如您在配置文件中看到的那样,我尝试使用 org.hibernate.dialect.MySQLDialect 和 org.hibernate.dialect.MySQLInnoDBDialect 但显示相同的错误。

显示的错误是:

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

报价为:

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

谢谢你的帮助。

4

1 回答 1

0

尝试添加到字段private Long idQuote;columnDefintion 之类"bigInt(8)"的,可能会成功

于 2013-06-08T19:54:28.350 回答