Unable to create a table in hibernate using OneToMany and ManyToOne relationship(also unable to create Foreign Key)

huangapple go评论81阅读模式
英文:

Unable to create a table in hibernate using OneToMany and ManyToOne relationship(also unable to create Foreign Key)

问题

这里的代码主要用于确定OneToMany和ManyToOne的关系。我使用Spring Tool Suite 3.9.11与XAMPP以及Apache 7.5作为服务器。

以下是第一个文件/表customer.java的代码部分:

@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;

	// 省略了其他方法和构造函数
}

以下是第二个文件/表OrderF.java的代码部分:

@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;

	// 省略了其他方法和构造函数
}

这是你的main.java的代码部分:

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配置文件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>

这是你的控制台/错误日志部分。

英文:

This code here is simply used to determine the relation of OnetoMany and ManyToOne, I use Spring Tool suite 3.9.11 with XAMPP and Server as apache 7.5

This is first file/table 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 = &quot;Customer&quot;)
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 = &quot;customer&quot;)
	private List&lt;OrderF&gt; order;

	public List&lt;OrderF&gt; getOrder() {
		return order;
	}

	public void setOrder(List&lt;OrderF&gt; 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;
	}

}


This is my second file/table 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=&quot;Order&quot;)
public class OrderF {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int food_id;
	private String foodName;
	@ManyToOne(cascade = CascadeType.PERSIST)
	@JoinColumn(name = &quot;cid&quot;)
	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;
	}

}

This is my 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(&quot;Java&quot;);
		
		SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		session.save(o);
		session.getTransaction().commit();
		session.close();
	}

}

This is hibernate Configuration file hibernate.cfg.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
&quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
&quot;http://hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt;

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

&lt;/hibernate-configuration&gt;

This is my Console/Error Log:

version for the right syntax to use near &#39;Order drop foreign key FKk8oprs3d23xg7tjw95wxaft8l&#39; 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 &#39;Order&#39; 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 &#39;Order (food_id integer not null auto_increment, foodName varchar(255), cid integ&#39; 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 &#39;Order add constraint FKk8oprs3d23xg7tjw95wxaft8l foreign key (cid) references Cu&#39; 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 &#39;Order (cid, foodName) values (1, &#39;Java&#39;)&#39; at line 1
Exception in thread &quot;main&quot; 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

得分: 0

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

@Entity
@Table(name="OrderF")
public class OrderF {...}
英文:

Your Order entity's table name is a reserved word in the SQL engine, try renaming the table's name

@Entity
@Table(name=&quot;OrderF &quot;)
public class OrderF {...}

答案2

得分: 0

作为重命名的替代方法,您可以使用SQL带引号的标识符:

@Entity
@Table(name="`Order`")
public class OrderF {
  // ...
}
英文:

As an alternative to renaming you can use SQL quoted identifiers:

@Entity
@Table(name=&quot;`Order`&quot;)
public class OrderF {
  // ...
}

huangapple
  • 本文由 发表于 2020年8月14日 14:46:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63407833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定