I have a problem with changing my spring/hibernate application from MySql to SQL Server.
When Hibernate is updating the database by starting the server he want to creates(by hibernate.hbm2ddl.auto set on update ) the database but a foreign-key fails on following error:
Unsuccessful: alter table table2 add constraint FKDC2DC97ECEB31922 foreign key (login) references table1
Column 'table1.id' is not the same data type as referencing column 'table2.table1_login' in foreign key 'FKDC2DC97ECEB31922'.
the mapping is as follows:
table1:
@Id
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
table2:
@ManyToOne
@JoinColumn (name = "table1_login", referencedColumnName = "login", insertable=false, updatable=false)
public Table1 getTable1() {
return table1;
}
public void setTable1(Table1 table1) {
this.table1= table1;
}
++edit:
SQL looks likes this:

keys from table1:

The table table1 is also used by an other application and therefore this table needs the column ‘id’ as primary key. So table1.id is primary key of table1. But this table1.id isn’t used by hibernate, because hibernate use the table1.login as id (see annotations above). But why is SQL Server trying to set a foreign key to table1.id and not to table1.login ?
Thanks
Here is what the JPA specification writes about the
Idannotation:So I’m tempted to say that things behave as per the specification (and the
loginproperty gets actually mapped on theidcolumn). Try to specify aColumnannotation:To clarify, here is what Wikipedia says about foreign keys: the foreign key identifies a column or a set of columns in one (referencing) table that refers to a set of columns in another (referenced) table. The columns in the referencing table must be the primary key or other candidate key in the referenced table.
So, while you can’t apply the above alter statement (
table1_logincan’t reference theidof table1, you can makeloginunique in table1 and create a FK constraint that would referencelogin. Something like that:This assumes you added a
UNIQUEconstraint on login in table1.See also