Hibernate

时间:2016-05-12 06:42:18

标签: java mysql sql hibernate tomcat

我一直在尝试使用MYSQL将约束UNSIGNED添加到列中。以下是我的表格。

public class UserActivity implements BaseEntity{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;

Long entityId;

@Column(columnDefinition = "enum('QUESTION','ANSWER', 'COMMENT', 'TAGS')")
@Enumerated(EnumType.STRING)
Type type;

@ManyToOne
@JoinColumn(nullable = false, columnDefinition="INT(11) UNSIGNED")
CustomerEntity user;

但是由于未设置外键和索引,因此不会为数据库中的用户列创建该约束。 Thisthis无能为力。请帮助我。感谢

日志:

Hibernate:
alter table UserActivity
    add constraint FK_jfw954ii6gw7mbqdth6y3n0rs
    foreign key (user_Id)
    references customerDb.customer (Id)
12:31:30.350 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaExport - HHH000389: Unsuccessful: alter table UserActivity add constraint FK_jfw954ii6gw7mbqdth6y3n0rs foreign key (user_Id) references customerDb.customer (Id)
12:31:30.350 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaExport - Can't create table 'community_db.#sql-43f0_5a07' (errno: 150)
Hibernate:

MySQL查询:

ALTER TABLE `community_db`.`Question` 
ADD INDEX `fk_Question_Customer_idx` (`author_Id` ASC);
ALTER TABLE `community_db`.`Question` 
ADD CONSTRAINT `fk_Answer_Customer`
FOREIGN KEY (`author_Id`)
REFERENCES `customerDb`.`customer` (`Id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

及以下是上述mysql查询的日志:

Error Code: 1005. Can't create table 'community_db.#sql-43f0_5d19' (errno: 150) 0.048 sec

1 个答案:

答案 0 :(得分:4)

columnDefinition或外键的@JoinColumn属性值必须等于实体ID中存在的columnDefinition注释的@Column属性值,即他们必须拥有相同的财产。

以下是CustomerEntity

@PersistenceUnit(unitName="persistenceUnit")
@Entity
@Table(name = "customer", schema = "customerDb")
public class CustomerEntity {
    @Id
    @Column(name = "Id", nullable = false, columnDefinition = "INT(11) UNSIGNED")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
..................
}

在UserActivity中包含客户ID作为外来用户 key必须存在相同的columndDefinition。

public class UserActivity implements BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    Long entityId;

    @ManyToOne
    @JoinColumn(nullable = false, columnDefinition = "INT(11) UNSIGNED")
    CustomerEntity user;
..................
}

我使用IntelliJIdea创建了该表,但没有添加那些属性,因为我得到了错误。