Grails: Foreign key as primary key? - sql

first of all i have to say that i have an existing database that it can not be modify (that´s why i am having this problem)
I have two cases, the first one is this:
In this case the id (primary key) must be a foreign key as well. The code that i put, it doesn´t work.
class SbPEstadoComponente {
static mapping = {
table 'SB_P_ESTADO_COMPONENTE'
version false
idEstadoComponenteHxPEstado column:'ID_ESTADO_COMPONENTE'
id column:'ID_ESTADO_COMPONENTE'
}
// Relation
SbPDemora idEstadoComponenteHxPEstado
String facturable
..
..
..
}
In the other case the table has 3 columns, that coluns are foreign key to 3 tables. Also those 3 columns have to be a composite primary key.
Any ideas? sugestions?
Thanks a lot !!

In your child class's mapping you need id composite: ['fkey1', 'fkey2'] and implements Serializable
Note that when you do a get you will need to populate all the composite key values

Related

SQL relation 1 key not 2 keys between tables

I want to define a foreign key constraint between the table Speler and the table Wedstrijd. I want the key on the Wedstrijd table, but when I use this code in my SQL console:
ALTER TABLE Speler
ADD FOREIGN KEY (idSpeler) REFERENCES Wedstrijd(idWedstrijd);
It puts a key on the table Speler and on the table Wedstrijd
Thanks for your time!
ALTER TABLE Wedstrijd
ADD FOREIGN KEY (idWedstrijd) REFERENCES Speler(idSpeler);
Instead of "solving" what you perceive as your problem, I think you have a different problem:
By mapping idSpeler to idWedstrijd, you are basically saying that a Speler (Player) is equal to a Wedstrijd (Match). That becomes a 1:1 relation which is then shown as a line with two yellow 'key'-endings (assuming you are using SQL Server).
It is very likely to me that instead you need to create a linking table WedstrijdSpeler that sits between the other two tables.
Then the new table WedstrijdSpeler needs to be given 2 Foreign Keys:
WedstrijdSpeler.idWedstrijd -> Wedstrijd.idWedstrijd
WedstrijdSpeler.idSpeler -> Speler.idSpeler.
Then you can give WedstrijdSpeler either a combined Primary Key (containing both fields idWedstrijd and idSpeler), or you can add a third field idWedstrijdSpeler and make that the Primary Key. Either approach will do, it is up to you.

how do I save to a database record with the primary key value = 0?

I have a client's database that I am accessing with nHibernate. In one table, they have a primary key which auto-increments starting at 0. I cannot have the client's database changed to a 1 based auto-increment.
When I attempt to save a child record in a table with a foreign key back to this table I receive the following error: "not-null property references a null or transient value". The problem is only found when I save the child of the record that has the 0 primary key value, all other records work fine.
This is the generator for the parent table
and the foreign key relationship map:
Question: how do I save to a database record with the primary key value = 0?
i cant see your mappings but i would try
public ParentMap()
{
Id(x => x.Id).GeneratedBy.Increment().UnsavedValue(-1);
}
and
public Parent()
{
Id = -1;
}

SQL Server 2008: The columns in table do not match an existing primary key or unique constraint

I need to make some changes to a SQL Server 2008 database.
This requires the creation of a new table, and inserting a foreign key in the new table that references the Primary key of an already existing table. So I want to set up a relationship between my new tblTwo, which references the primary key of tblOne.
However when I tried to do this (through SQL Server Management Studio) I got the following error:
The columns in table 'tblOne' do not
match an existing primary key or
UNIQUE constraint
I'm not really sure what this means, and I was wondering if there was any way around it?
It means that the primary key in tblOne hasn't been properly declared - you need to go to tblOne and add the PRIMARY KEY constraint back onto it.
If you're sure that tblOne does have a PRIMARY KEY constraint, then maybe there are multiple tblOne tables in your DB, belonging to different schemas, and your references clause in your FK constraint is picking the wrong one.
If there's a composite key (which your comment would indicate), then you have to include both columns in your foreign key reference also. Note that a table can't have multiple primary keys - but if it has a composite key, you'll see a key symbol next to each column that is part of the primary key.
If you have a composite key the order is important when creating a FK, and sometimes the order is not how it is displayed.
What I do is go to the Keys section of the table1 and select script primary key as create to clipboard and then create FK using the order as shown in script
I've had this situation that led me to this topic. Same error but another cause. Maybe it will help someone.
Table1
ColA (PK)
ColB (PK)
ColC
Table2
ID (PK)
ColA
COLB
When trying to create foreign key in Table2 I've choose values from combobox in reverse order
Table1.ColB = Table2.ColB
Table1.ColA = Table2.ColA
This was throwing me an error like in topic name. Creating FK keeping order of columns in Primary key table as they are, made error disappear.
Stupid, but.. :)
If you still get that error after you have followed all advice from the above answers and everything looks right.
One way to fix it is by Removing your Primary keys for both tables, Save, Refresh, and add them again.
Then try to add your relationship again.
This Error happened with me When I tried to add foreign key constraint starting from PrimaryKey Table
Simpy go to other table and and create this foreign key constraint from there (foreign key Table)
This issue caught me out, I was adding the relationship on the wrong table. So if you're trying to add a relationship in table A to table B, try adding the relationship in table B to table A.
That looks like you are trying to create a foreign key in tblTwo that does not match (or participate) with any primary key or unique index in tblOne.
Check this link on MSDN regarding it. Here you have another link with a practical case.
EDIT:
Answwering to your comment, I understand you mean there are 2 fields in the primary key (which makes it a composite). In SQL it is not possible to have 2 primary keys on the same table.
IMHO, a foreign key field should always refer to a single register in the referenced table (i.e. the whole primary key in your case). That means you need to put both fields of the tblOne primary key in tblTwo before creating the foreign key.
Anyway, I have investigated a bit over the Internet and it seems SQL Server 2008 (as some prior versions and other RDBMS) gives you the possibility to reference only part of the primary key as long as this part is a candidate key (Not Null and Unique) and you create an unique constraint on it.
I am not sure you can use that in your case, but check this link for more information on it.
I have found that the column names must match.
Example:
So if tblOne has id called categoryId a reference in tblTwo must also be called categoryId.
_tblname, primary key name, foreign key_
tblOne, "categoryId", none
tblTwo, "exampleId", "categoryId"
I noticed this when trying to create foreign key between 2 tables that both had the column name "id" as primary key.
If nothing helps, then this could be the reason:
Considering this case:
Table A:
Column 1 (Primary Key)
Column 2 (Primary Key)
Column 3
Column 4
Table B:
Column a (Primary Key)
Column b
Column c
when you are defining a dependency B to A, then you are forced to respect the order in which the primaries are defined.
That's mean your dependency should look like this:
Table A Table B
Column 1 Column b
Column 2 Column c
AND NOT:
Table A Table B
Column 2 Column c
Column 1 Column b
then this will lead to the error you are encountering.
I've found another way to get this error. This can also happen if you are trying to make a recursive foreign key (a foreign key to the primary key in the same table) in design view in SQL Management Studio. If you haven't yet saved the table with the primary key it will return this message. Simply save the table then it will allow you to create the foreign key.
If you have data in your tables this could be the issue.
In my case I had some data in the Account table that I loaded at 3 pm, and some data in Contact table that I loaded at 3:10 pm, so Contact table had some values that weren't in my Account table yet.
I ended up deleting these values from the contact table and then managed to add a key without any problems.
Kindly also see that there are no existing data inside the table where the primary key is defined while setting the foreign key with another table column.
this was the cause of the error in my case.
I had to take backup empty the table set the relationship and then upload the data back.
sharing my experience
Was using ms sql smss

Problem adding #ManyToOne mapping on Non primary-key in SQL Server

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 Id annotation:
9.1.8 Id Annotation
The Id annotation specifies the
primary key property or field of an
entity. The Id annotation may be
applied in an entity or mapped
superclass.
By default, the mapped column for the
primary key of the entity is assumed
to be the primary key of the primary
table. If no Column annotation is
specified, the primary key column name
is assumed to be the name of the
primary key property or field.
So I'm tempted to say that things behave as per the specification (and the login property gets actually mapped on the id column). Try to specify a Column annotation:
#Id #Column(name = "login")
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
I can't recreated the table1 because this is an excisting table. I must use the alter table option from the DLL: "alter table table2 add constraint FK1751F2B3CEB31922 foreign key (table1_login) references table1" and I rather want the referential integrity.
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_login can't reference the id of table1, you can make login unique in table1 and create a FK constraint that would reference login. Something like that:
ALTER TABLE table2
ADD CONSTRAINT FK_table2_table1
FOREIGN KEY (table1_login)
REFERENCES table1(login)
This assumes you added a UNIQUE constraint on login in table1.
See also
FOREIGN KEY Constraints
EDIT:
AFTER reading the message carefully I found this...
'table1.id' is not the same data type as referencing column 'table2.table1_login'
Table1.ID -> table2.table1_login.
ID and login are not the same datatype. So there is a wrong PK-FK relation around...
This sounds like you are using the wrong collation. Both columns need the same collation. Otherwise you can not join them.
http://msdn.microsoft.com/en-us/library/aa174903(SQL.80).aspx
Make sure that you remove all explicitly set collations on the database creation script.

Does MySQL allow two primary keys on one table?

CREATE TABLE Orders
-> (
-> ID SMALLINT UNSIGNED NOT NULL,
-> ModelID SMALLINT UNSIGNED NOT NULL,
-> Descrip VARCHAR(40),
-> PRIMARY KEY (ID, ModelID)
-> );
Basically, this appears to me to be creating two primary key on one table. Is that correct?
I thought that we could create a number of unique keys in one table, but only one primary key.
How is it that my system is allowing the creation of multiple primary keys?
Please advise: what are the rules governing this?
Your system is not allowing multiple primary keys - it is creating the key based on 2 columns (ID, ModelID)
Think of it like it suggest, a 'KEY'. So the key would be all of the columns specified. In your case you can have multiple rows with the same 'ID' and multiple rows with the same 'ModelID' but there shall never be two rows that have the same 'ID' AND 'ModelID'.
So in this case it is not saying that the column 'ID' must be unique nor is it saying that 'ModelID' must be unique, but only the combination.
You are making 1 primary key. But that key is a combination of 2 values.
Which is not a wrong thing to do. But in your case it does look wrong.
You seem to have a primary key named ID and a foreign key named ModelID. You should probable have an index on the ModelID, and a primary key constraint on the ID
You can have one primary key (thats why it is called the primary key)
You can have multiple UNIQUE keys if you like.