我真的很难解决以下错误。 请帮我解决?
我正在开发ManyToMany关系示例。
Initial SessionFactory creation failed.org.hibernate.MappingException: Foreign key (FK302BCFEEB260666:category [CATEGORY_ID])) must have same number of columns as the referenced primary key (category [STOCK_ID,CATEGORY_ID])
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
at com.mkyong.util.HibernateUtil.<clinit>(HibernateUtil.java:8)
at com.mkyong.App.main(App.java:13)
Caused by: org.hibernate.MappingException: Foreign key (FK302BCFEEB260666:category [CATEGORY_ID])) must have same number of columns as the referenced primary key (category [STOCK_ID,CATEGORY_ID])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:112)
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:95)
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1808)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1729)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1396)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1829)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 2 more
我开发的代码, Category.java
@Entity
@Table(name = "category")
public class Category implements java.io.Serializable {
private static final long serialVersionUID = 8833944947723156024L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "CATEGORY_ID", unique = true, nullable = false)
private Integer categoryId;
@Column(name = "NAME", nullable = false, length = 10)
private String name;
@Column(name = "DESCRIPTION", nullable = false)
private String desc;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
private Set<Stock> stocks = new HashSet<Stock>(0);
public Category() { }
public Category(String name, String desc) {
this.name = name;
this.desc = desc;
}
public Category(String name, String desc, Set<Stock> stocks) {
this.name = name;
this.desc = desc;
this.stocks = stocks;
}
// setters and getters
}
Stock.java
@Entity
@Table(name = "stock",uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {
private static final long serialVersionUID = 7788035862084120942L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "category",
joinColumns = { @JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID")})
private Set<Category> categories = new HashSet<Category>(0);
public Stock() { }
public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}
public Stock(String stockCode, String stockName, Set<Category> categories) {
this.stockCode = stockCode;
this.stockName = stockName;
this.categories = categories;
}
// setters and getters
}
HibernateUtil.java
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
App.java
public class App {
public static void main(String[] args) {
System.out.println("Hibernate many to many (Annotation)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY");
Set<Category> categories = new HashSet<Category>();
categories.add(category1);
categories.add(category2);
stock.setCategories(categories);
session.save(stock);
session.getTransaction().commit();
System.out.println("Done");
}
}
请帮我解决这里有什么问题?
create table stock(
stock_id BIGINT(10) NOT NULL AUTO_INCREMENT,
stock_code VARCHAR(50),
stock_name VARCHAR(50),
PRIMARY KEY (`stock_id`)
);
create table Category(
stock_id BIGINT(10) NOT NULL AUTO_INCREMENT,
category_id VARCHAR(50),
name VARCHAR(50),
description VARCHAR(50),
PRIMARY KEY (`stock_id`)
)
修改-1: 现在我遇到错误了?
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.mkyong.App.main(App.java:31)
Caused by: java.sql.BatchUpdateException: Table 'test.stock_category' doesn't exist
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
答案 0 :(得分:0)
假设连接表的名称是表的名称 关联的主表连接在一起(首先拥有一方) 使用下划线。
在这种情况下,Join Table是stock_category
@JoinTable(name = "stock_category",
joinColumns = { @JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID")})