Adding field to hasMany, got MySql error ??

25 / May / 2015 by Ankit Agrawal 0 comments

It’s a common practice to add fields to Grails domain’s hasMany block while in database a foreign key relationship is maintained for every such entry. In other words, for each foreign key, we have a column in parent table (or domain) and a reference column in other table.

I was adding a field into hasMany block recently when I got this issue. Error looks somewhat like this-

mysql ERROR 1005 Can’t create table ‘foo.#sql-426_c0’ (errno: 150)

From database perspective,  there can be many reasons behind this. Some are –

1. The two key fields type and/or size doesn’t match exactly. For example, if one is INT(10) the key field needs to be INT(10) as well and not INT(11) or TINYINT. You should also check that one is not SIGNED and the other is UNSIGNED. They both need to be exactly the same.

2. One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field.

3. The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this.

4. One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB. (Actually, if both tables are MyISAM then you won’t get an error message – it just won’t create the key.)

5. You have specified a cascade ON DELETE SET NULL, but the relevant key field is set to NOT NULL. You can fix this by either changing your cascade or setting the field to allow NULL values.

6. You have a default value (ie default=0) on your foreign key column.

7. One of the fields in the relationship is part of a combination (composite) key and does not have it’s own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint.

8. You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship.

9. The name of your foreign key exceeds the max length of 64 chars.

What my case was –

10. Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns.

Now, how do you do that?

In MySql terminal, enter following –

SHOW CREATE TABLE ‘table_first’;
SHOW CREATE TABLE ‘table_second’;

It will show charset and collate values. In my case table_first was having ‘utf8’ where as table_second was having ‘latin’ charset.

You can simply change the charset of table_second(prefer mapping table) by –

ALTER TABLE table_second CONVERT TO CHARACTER SET ‘utf8’;

Hope this helps.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *