无法使用 OneToMany 和 ManyToOne 关系在休眠中创建表(也无法创建外键)

Posted

技术标签:

【中文标题】无法使用 OneToMany 和 ManyToOne 关系在休眠中创建表(也无法创建外键)【英文标题】:Unable to create a table in hibernate using OneToMany and ManyToOne relationship(also unable to create Foreign Key) 【发布时间】:2020-08-14 06:46:15 【问题描述】:

这里的代码只是用来判断OnetoMany和ManyToOne的关系,我用的是Spring Tool suite 3.9.11 with XAMPP and Server as apache 7.5

这是第一个文件/表 customer.java

package com.bean;

import java.util.List;

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;


@Entity
@Table(name = "Customer")
public class Customer 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int cid;

    private String cname;
    private int ccontact;
    private String cemail;
    private String cpassword;

    @OneToMany(mappedBy = "customer")
    private List<OrderF> order;

    public List<OrderF> getOrder() 
        return order;
    

    public void setOrder(List<OrderF> order) 
        this.order = order;
    

    public Customer() 
        super();
    

    public int getCid() 
        return cid;
    

    public void setCid(int cid) 
        this.cid = cid;
    

    public String getCname() 
        return cname;
    

    public void setCname(String cname) 
        this.cname = cname;
    

    public int getCcontact() 
        return ccontact;
    

    public void setCcontact(int ccontact) 
        this.ccontact = ccontact;
    

    public String getCemail() 
        return cemail;
    

    public void setCemail(String cemail) 
        this.cemail = cemail;
    

    public String getCpassword() 
        return cpassword;
    

    public void setCpassword(String cpassword) 
        this.cpassword = cpassword;
    




这是我的第二个文件/表 OrderF.java

package com.bean;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="Order")
public class OrderF 

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int food_id;
    private String foodName;
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "cid")
    private Customer customer;

    public int getFood_id() 
        return food_id;
    

    public void setFood_id(int food_id) 
        this.food_id = food_id;
    

    public String getFoodName() 
        return foodName;
    

    public void setFoodName(String foodName) 
        this.foodName = foodName;
    

public Customer getCustomer() 
    return customer;
    

    public void setCustomer(Customer customer) 
        this.customer = customer;
    



这是我的 main.java

package com.bean;

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

public class MainClass 

    public static void main(String[] args) 
        Customer c=new Customer();
        c.setCid(1);
        OrderF  o=new OrderF();
        o.setCustomer(c);
        o.setFood_id(1);
        o.setFoodName("Java");
        
        SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        session.save(o);
        session.getTransaction().commit();
        session.close();
    



这是休眠配置文件hibernate.cfg.xml

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

<hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>  
    <property name="hibernate.show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
    
    <mapping class="com.bean.Customer"></mapping>
    <mapping class="com.bean.OrderF"></mapping>
    </session-factory>
    

</hibernate-configuration>

这是我的控制台/错误日志:

version for the right syntax to use near 'Order drop foreign key FKk8oprs3d23xg7tjw95wxaft8l' at line 1
Hibernate: drop table if exists Customer
Hibernate: drop table if exists Order
Aug 14, 2020 12:04:34 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: drop table if exists Order
Hibernate: create table Customer (cid integer not null auto_increment, ccontact integer not null, cemail varchar(255), cname varchar(255), cpassword varchar(255), primary key (cid))
Aug 14, 2020 12:04:34 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order' at line 1
Hibernate: create table Order (food_id integer not null auto_increment, foodName varchar(255), cid integer, primary key (food_id))
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: create table Order (food_id integer not null auto_increment, foodName varchar(255), cid integer, primary key (food_id))
Hibernate: alter table Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Customer (cid)
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order (food_id integer not null auto_increment, foodName varchar(255), cid integ' at line 1
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Customer (cid)
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Cu' at line 1
Aug 14, 2020 12:04:35 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Order (cid, foodName) values (?, ?)
Aug 14, 2020 12:04:35 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Aug 14, 2020 12:04:35 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Order (cid, foodName) values (1, 'Java')' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2792)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3363)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:597)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:232)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:213)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:256)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:679)

【问题讨论】:

【参考方案1】:

作为重命名的替代方法,您可以使用SQL quoted identifiers:

@Entity
@Table(name="`Order`")
public class OrderF 
  // ...

【讨论】:

【参考方案2】:

您的 Order 实体的表名是 SQL 引擎中的保留字,请尝试重命名表名

@Entity
@Table(name="OrderF ")
public class OrderF ...

【讨论】:

以上是关于无法使用 OneToMany 和 ManyToOne 关系在休眠中创建表(也无法创建外键)的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 OneToMany 和 ManyToOne 关系在休眠中创建表(也无法创建外键)

无法在 HIbernate 4 中保持 OneToMany 关系

JPA 2 / Hibernate 孤儿删除仍然无法与@OneToMany 一起使用?

CDI + JPA 多个 @OneToMany - LAZY/EAGER - LazyInitializationException 或无法实例化多个包

无法在休眠中删除 OneToMany 关系的实例

ORA-01400: 当使用 @onetomany 映射并且在子端具有复合主键时,无法将 NULL 插入