Reputation: 3619
I have been trying to add constraint UNSIGNED to a column using MYSQL. Below is my table.
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;
But it is not creating that constraint for user column in the database due to which foreign key and index are not setting up. This and this could not help. Kindly help me out. Thanks
LOGS:
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 Queries :
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;
and below are the logs for the above mysql queries :
Error Code: 1005. Can't create table 'community_db.#sql-43f0_5d19' (errno: 150) 0.048 sec
Upvotes: 1
Views: 4273
Reputation: 3619
The columnDefinition
property value of the @JoinColumn
or the foreign key must be equal to the columnDefinition
property value of the @Column
annotation present in the Entity Id, i.e., they must have the same property.
Below is the 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;
}
..................
}
And in the UserActivity which would contain the customer Id as the foreign key the same same columndDefinition must be present.
public class UserActivity implements BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
Long entityId;
@ManyToOne
@JoinColumn(nullable = false, columnDefinition = "INT(11) UNSIGNED")
CustomerEntity user;
..................
}
I created that table using IntelliJIdea which did not added those property due to which I got the error.
Upvotes: 4