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

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;
}

Related

Duplicate values get inserted instead composite key in xampp server phpadmin database

I had 1st created the table with only one primary key then converted 1 more column to primary key using:
ALTER TABLE students DROP PRIMARY KEY, ADD PRIMARY KEY(student_id, email);
The composite key created successfully but composite key isn't working the way it should work.
On inserting the same values of email but with different id database inserts the value successfully isn't giving me catch statements
I have tried this code:
try{
$dbhandler = new PDO('mysql:host=127.0.0.1;dbname=project_db','root','');
$dbhandler->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql="insert into students (student_id,faculty,password,cpi,first_name,last_name,birthdate,email,contact_no,participate,leader,allocated) values (?,?,?,?,?,?,?,?,?,?,0,0)"; // leader is 0 means not decided
$query=$dbhandler->prepare($sql);
$p=0;
if(isset($_POST['s_participate']))
{
$p=1;
}
$r=$query->execute(array($_POST['s_id'],$_SESSION['faculty'],$_POST['s_id'],$_POST['s_cpi'],$_POST['s_f_name'],$_POST['s_l_name'],$_POST['s_birthday'],$_POST['s_email'],$_POST['s_contact'],$p));
}
catch(PDOException $e){
$msg='student with this id is already exist';
$temp=1;
header("location:./insert_student.php?msg=".$msg);
}
if($r){
header("location:./insert_student.php?msg=Student ".$_POST['s_f_name']." with id ".$_POST['s_id']." is successfully added");
}

MVC 4 EF5 Primary Key

In my application my user model has a foreign key to the address table. My problem is after I insert the the address into the address table I have to run a LINQ query on the whole population of the address table looking for the record I just persisted. Is there a better way to get the primary key from a record that was just persisted?
I suggest you change the primary key type to GUID, which is UNIQUEIDENTIFIER in SQL. then you will know your inserted id:
var id = Guid.NewGuid();
var model = new Address()
{
Id = id,
// ...
};
// add and save context
Upon SaveChanges(), the Context will update your Entity with the newly-created id.

Grails: Foreign key as primary key?

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

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.

SQLite: prevent duplicates

I would like to create a table to store device settings. The table has three rows: id, parameter_name and parameter_value.
The table was created by executing the following query statement:
DATABASE_CREATE = "create table DATABASE_TABLE (KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT, KEY_NAME INTEGER not null, VALUE TEXT not null);
and then the rows are stored by executing the following method:
private long insertRow(int rowParameter, String rowValue, SQLiteDatabase db){
long res = -1;
ContentValues settingsParameterValues = new ContentValues();
settingsParameterValues.put(KEY_NAME, rowParameter);
settingsParameterValues.put(VALUE, rowValue);
if(db != null){
res = db.insert(DATABASE_TABLE, null, settingsParameterValues);
}
return res;
}
When the database is created the default values are stored:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
insertRow(PRIVACY_LEVEL_ROW_INDEX, "0", db);
insertRow(STREAM_TITLE_ROW_INDEX, "untitled", db);
insertRow(STREAM_TAGS_ROW_INDEX, "", db);
}
The problem with method insertRow() however is that it can't prevent duplicating the entries.
Does anyone know how to prevent duplicate entries in this case?
You can use the column constraint UNIQUE.
The UNIQUE constraint causes an unique index to be created on the specified columns.
I would create a UNIQUE CONSTRAINT in the database table definition. That will automatically prevent duplicate entries and it's pretty much the only concurrency-safe way to do it!
Also, don't forget about CHECK CONSTRAINT which may be more helpful if you need to define more complex rules for the data in you tables.
Are you trying to prevent it through code, or in the database?
If trying to prevent from code you'll need to do a SELECT and see if the row already exists.
If trying to prevent it from the database you'll need to add a UNIQUE constraint on whichever row you don't want to allow duplicates on.
In your case, the correct primary key would have been parameter_name.