java - hibernate 异常 : Missing Column (column exists)

标签 java sql hibernate

好的,所以在数据库中我们有一个名为 distributionCompanies 的表,创建方式如下:

CREATE TABLE `distributionCompanies` (
    `distributionCompanyID` INT(11) NOT NULL,
    `distributionCompanyName` VARCHAR(255) NOT NULL,
     PRIMARY KEY (distributionCompanyID)
);

我正在尝试使用 Hibernate 将此表映射到一个类:

@Entity
@Table(name = "distributionCompanies")
public class DistributionCompany implements DatabaseObject {
    @Id
    @GeneratedValue
    @Column(name = "distributionCompanyID", length = 11, unique = true, nullable = false)
    private int distributionCompanyID;
....

但是,在运行时,我遇到了这个问题:

Initial SessionFactory creation failedorg.hibernate.HibernateException: Missing column: distributionCompanyID_distributionCompanyID in database2.distributionCompanies

这不是数据库中唯一的表,我已经使用相同的方法成功地映射了其他类,所以我有点困惑为什么这会导致问题。

谢谢你的时间, 塞缪尔·史密斯

编辑:为了回应 Xavi 的评论,我暂时删除了该列的另一个映射,错误消失了,所以问题可能出在以下代码中:

@ManyToOne(targetEntity = DistributionCompany.class)
@JoinTable(name = "distributionCompanies", joinColumns = { @JoinColumn(name =    "distributionCompanyID", nullable = false) })
private int distributionCompanyID;

最佳答案

Hibernate 正在您的 distributionCompanies 表中寻找名为 distributionCompanyID_distributionCompanyID 的列。

这可能是由于 ToOne 关联映射到此表而没有 @JoinColum

来自 Hibernate Documentation :

The @JoinColumn attribute is optional, the default value(s) is like in one to one, the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column in the owned side. In this example company_id because the property name is company and the column id of Company is id.

如果您在另一个实体中有一个 @ManyToOne@OneToOne 关联映射,这就可以解释为什么 Hibernate 正在寻找这样一个列。

编辑 看到您发布的关联映射,看起来应该是:

@ManyToOne(targetEntity = DistributionCompany.class)
@JoinColumn(name = "distributionCompanyID")
private DistributionCompany distributionCompany;

@JoinTable 注释用于指定连接表(这意味着用于模拟多对多关联的中间表)。映射关联的目的是处理映射的对象实例(在本例中是 DistributionCompany,而不仅仅是 distributionCompanyId)。

关于java - hibernate 异常 : Missing Column (column exists),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237514/

相关文章:

java - 创建类路径资源中定义的名为 'entityManagerFactory' 的 bean

hibernate.properties和hibernate.cfg.xml

java - 使用 mvnDebug 命令在 maven 中调试

sql - 如何在 SQL 中实现 "hasChildren"SELECT 语句?

sql - 计算给定时间段内有多少首条目和末尾条目相等

mysql - 在 MySQL 的嵌套 Select 语句中使用 Select 数据

mysql - 一夜之间失去连接(spring boot + mysql)

java - JButton 缩放整个屏幕

java - 在Java中选择声卡以播放声音

java - 第 32 行出现空指针异常 (java)