Hibernate:抛出对象插入到Derby嵌入式数据库中的SQLGrammerException

时间:2016-08-30 18:32:11

标签: java hibernate derby

每当我尝试将对象插入到Derby嵌入式数据库的表中时,我都会从Hibernate收到此错误:

Hibernate: insert into car (cost, make, model, price, sold, start, type, year, doors, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Aug 30, 2016 2:13:40 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 20000, SQLState: 42X01
Aug 30, 2016 2:13:40 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Syntax error: Encountered "year" at line 1, column 63.
Aug 30, 2016 2:13:40 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: could not prepare statement]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1403)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:473)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3133)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at com.ethanrich.dao.CarDAO.insert(CarDAO.java:27)
    at com.ethanrich.finalproject.Main.main(Main.java:26)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:78)
    at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.buildBatchStatement(AbstractBatchImpl.java:136)
    at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.getBatchStatement(AbstractBatchImpl.java:125)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2915)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3434)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:582)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:456)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1397)
    ... 10 more
Caused by: java.sql.SQLSyntaxErrorException: Syntax error: Encountered "year" at line 1, column 63.
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedPreparedStatement42.<init>(Unknown Source)
    at org.apache.derby.jdbc.Driver42.newEmbedPreparedStatement(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$1.doPrepare(StatementPreparerImpl.java:87)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    ... 21 more
Caused by: ERROR 42X01: Syntax error: Encountered "year" at line 1, column 63.
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.impl.sql.compile.ParserImpl.parseStatementOrSearchCondition(Unknown Source)
    at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source)
    at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
    at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
    at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
    ... 28 more

代码:

Main.class

public class Main {

    public static void main(String[] args) {

        Model m = new Model();

        ArrayList<Vehicle> vehicles = new ArrayList<>();
        vehicles.add(new Car(2, "Toyota", "Camry", 2009, dateOf(2012, 7, 23), dateOf(2012, 7, 27), 7600.00, 17500.00, 4));


        for(Vehicle v : vehicles) {
            m.getCarDAO().insert((Car) v);
        }
    }

    public static Date dateOf(int year. int month, int day) {
        GregorianCalendar gc = new GregorianCalendar(year, month, day);
        return new Date(gc.getTimeInMillis());\
    }
}

Vehicle.class

import java.util.Date;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class Vehicle {

    @Id
    private int id;
    private int year;
    private String type;
    private String make;
    private String model;
    private Date start; 
    private Date sold;
    private double cost;
    private double price;

    public Vehicle() {}
    public Vehicle(int id, String type, String make, String model, int year, Date start, Date sold, double cost, double price) {
        this.setId(id);
        this.setType(type);
        this.setMake(make);
        this.setModel(model);
        this.setYear(year);
        this.setDateStart(start);
        this.setDateSold(sold);
        this.setCost(cost);
        this.setPrice(price);
    }

    // GETTERS

    public int getId() {return id;}
    public String getType() {return type;}
    public String getMake() {return make;}
    public String getModel() {return model;}
    public int getYear() {return year;}
    public Date getDateStart() {return start;}
    public Date getDateSold() {return sold;}
    public double getCost() {return cost;}
    public double getPrice() {return price;}

    // SETTERS

    public void setId(int id) {this.id = id;}
    public void setType(String type) {this.type = type;}
    public void setMake(String make) {this.make = make;}
    public void setModel(String model) {this.model = model;}
    public void setYear(int year) {this.year = year;}
    public void setDateStart(Date start) {this.start = start;}
    public void setDateSold(Date sold) {this.sold = sold;}
    public void setCost(double cost) {this.cost = cost;}
    public void setPrice(double price) {this.price = price;}

}

Car.class

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "car")
public class Car extends Vehicle {

    private int doors;

    public Car() {
        super();
    }

    public Car(int id, String make, String model, int year, Date start, Date sold, double cost, double price, int doors) {
        super(id, "CAR", make, model, year, start, sold, cost, price);
        this.setDoors(doors);
    }

    public int getDoors() {
        return doors;
    }

    public void setDoors(int doors) {
        this.doors = doors;
    }

    public String toString() {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY");
        return "ID: #" + getId() + " Type: Car, " + getMake() + ", " + getModel() + ", car year is , start inventory date is " +  sdf.format(getDateStart()) + ", date sold " + sdf.format(getDateSold()) + ", dealer’s car cost is $" + getCost() + ", sold price is $" + getPrice() + ", 4 wheels.";
    }
}

CarDAO.class

import java.util.ArrayList;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;

public class CarDAO {

    public static SessionFactory sessionFactory;

    public CarDAO(SessionFactory sf) {
        sessionFactory = sf;
    }

    public CarDAO(){}

    public void insert(Car c) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(c);
        session.getTransaction().commit();
        session.close();
    }

    public void delete(Car c) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.delete(c);
        session.getTransaction().commit();
        session.close();
    }

    public void update(Car c) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.update(c);
        session.getTransaction().commit();
        session.close();
    }

    public Car getById(int id) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Car c = (Car) session.get(Car.class, id);
        session.getTransaction().commit();
        session.close();
        return c;
    }
}

Model.class

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

import com.ethanrich.databeans.*;

public class Model {

    private TruckDAO truckDAO;
    private CarDAO carDAO;

    public Model() {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        configuration.addAnnotatedClass(Car.class); 

        SessionFactory sessionFactory = configuration.buildSessionFactory();

        carDAO = new CarDAO(sessionFactory);
    }

    public CarDAO getCarDAO() { return carDAO; }
    public void setCarDAO(CarDAO carDAO) { this.carDAO = carDAO;}

}

的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>
  <property name="hibernate.dialect">org.hibernate.dialect.DerbyTenSevenDialect</property>
  <property name="hibernate.event.merge.entity_copy_observer">allow</property>
  <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
  <!--  -->
  <property name="hibernate.connection.url">jdbc:derby:vehicles;create=true</property>
  <property name="hibernate.connection.username">admin</property>
  <property name="hibernate.connection.password">admin</property>
  <property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
  <property name="hibernate.show_sql">true</property>
  <!--  <property name="hibernate.connection.release_mode">ON_CLOSE</property> -->
  <mapping class="com.erisawesome.databeans.Vehicle"/>

 </session-factory>
</hibernate-configuration>

程序只是将Car对象放在ArrayList中,然后将它们插入到数据库中。

1 个答案:

答案 0 :(得分:1)

查看异常,它会告诉您问题的原因:“错误:语法错误:在第1行第63行遇到”年“。碰巧“年”是Derby中的保留关键字,因此您不能将其用于表名或列名。更改列的名称并重试..

https://db.apache.org/derby/docs/10.1/ref/rrefkeywords29722.html

检查德比中的保留关键字