首页 > 解决方案 > Hibernate SQL 语法错误生成的查询

问题描述

更新!:删除这一行:configuration.addAnnotatedClass(Order.class);从 HibernateUtil.loadSessionFactory 使休眠能够无错误地执行。但是订单仍然没有保存到数据库中。

当我用它保存对象时session.save()会引发此错误:`

java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“Order (orderNumber, totalPrice, orderId) values ('2019000009', 0.5, 1)' 附近使用正确的语法

` 它曾经工作得很好,但是在一点一点地改变代码试图让休眠与对象的关系一起工作之后,我一定是改变了导致这种情况的东西。

我自己不编写查询。它是由休眠生成的。这是我要保存在数据库中的对象:


@Entity
@Table(name = "Order", schema = "products", catalog = "")
public class Order {

    @OneToMany
    private List<Product> products = new ArrayList<Product>();

    @Id
    @Column( name = "orderId",  nullable = false)
    private int orderId;

    @Basic
    @Column(name = "orderNumber", nullable = false)
    private String orderNumber;

    @Basic
    @Column(name = "totalPrice", nullable = false)
    private double totalPrice;

    protected Order() {
    }

    public int getOrderId() {
        return this.orderId;
    }

    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }


    public String getOrderNumber() {
        return this.orderNumber;
    }

    public double getTotalPrice() {
        return this.totalPrice;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Order that = (Order) o;
        return orderId == that.orderId &&
                Objects.equals(orderNumber, that.orderNumber) &&
                Objects.equals(totalPrice, that.totalPrice);
    }

    @Override
    public int hashCode() {
        return Objects.hash(orderId, totalPrice, orderNumber);
    }


    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }
}

休眠.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/products?serverTimezone=UTC</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">****</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.pool_size">1</property>
        <property name="show_sql">true</property>


        <mapping class="nu.educom.calculateChange.Product"/>
        <mapping class="nu.educom.calculateChange.Order"/>
        <mapping resource="Order.hbm.xml"/>


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

休眠实用程序:


public class HibernateUtil {

    private static SessionFactory sessionFactory = loadSessionFactory();

    static {
        try{
            loadSessionFactory();
        }catch(Exception e){
            System.err.println("Exception while initializing hibernate util.. ");
            e.printStackTrace();
        }
    }

    public static SessionFactory loadSessionFactory(){

        Configuration configuration = new Configuration();
        configuration.configure("/hibernate.cfg.xml");
        configuration.addAnnotatedClass(Order.class);
        configuration.addAnnotatedClass(Product.class);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        return configuration.buildSessionFactory(serviceRegistry);
    }

    public static Session getSession() throws HibernateException {
        Session retSession=null;
        try {
            retSession = sessionFactory.openSession();
        }catch(Throwable t){
            System.err.println("Exception while getting session.. ");
            t.printStackTrace();
        }
        if(retSession == null) {
            System.err.println("session is discovered null");
        }

        return retSession;
    }

    public static long insertOrder(Object object) {
        loadSessionFactory();
        Session session = getSession();
        Integer lastInsertId = 1;
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            lastInsertId = (Integer) session.save(object);
            tx.commit();
        } catch (HibernateException ex) {
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }

        return lastInsertId;
    }
}

订单.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name = "nu.educom.calculateChange.Order" table = "order">
        <id name = "orderId" type = "int" column="orderId">
            <generator class="native"/>
        </id>
        <property name="orderNumber" column="orderNumber" type="string"/>
        <property name="totalPrice" column="totalPrice" type="double"/>

    </class>
</hibernate-mapping>

最后,调用保存订单:

public void processOrder() {
        Order order = new Order();
        order.setTotalPrice(this.getTotal());
        order.setOrderNumber("2019000009");
        order.setOrderId(1);


        for (Product product: this.productsAddedToRegister) {
            order.getProducts().add(product);
        }
        HibernateUtil.loadSessionFactory();
        long orderId = HibernateUtil.insertOrder(order);


    }

标签: javahibernate

解决方案


问题是 Order 是 mysql 的函数或关键字。所以关于“订单”表的每个查询都不会执行。将其重命名为“订单”解决了它。


推荐阅读