Is it possible to get NHibernate to enforce a unique constraint for me by attempting to load the existing reference to the key instead of just inserting it? Say I have the following classes:
Code:
public class item
{
//....declarations
public CASNum CASNumber{//get\set stuff here}
}
public class cas_num
{
public string CAS{//get\set}
public long cas_id{//get\set}
}
In the database, there are two tables: items and cas_nums. items has a foreign key to cas_id (which is cas_nums' primary key). In addition, the field CAS has a unique constraint. CAS would be a candidate key if I wasn't using surrogate keys.
When I save an item, I would like NHibernate to look up whether that CAS already exists and if so, use that CAS's cas_id in the foreign key in the items table for that item.
Presently, NHibernate blindly attempts to insert the CAS, so if it's a duplicate, I get a duplicate key constraint violation.
Should I just implement this in my business code, or can NHibernate look the key up for me as detailed above?
Hibernate version: 1.02
Mapping documents:casNum.hbm.xml
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0" assembly="data" namespace="data">
<class name="CASNum" table="cas_nums">
<id name="ID" column="cas_id" type="Int64" unsaved-value="-1">
<generator class="sequence">
<param name="sequence">cas_num_id_seq</param>
</generator>
</id>
<property name="CAS" column="cas_num" type="String" unique="true" />
<property name="Compound" column="chemical" type="String" />
</class>
</hibernate-mapping>
item.hbm.xml
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0" assembly="data" namespace="data">
<class name="Item" table="current_inventory">
<id name="ID" column="item_id" type="Int64" unsaved-value="-1">
<generator class="sequence">
<param name="sequence">item_id_seq</param>
</generator>
</id>
<many-to-one name="CASNum" class="CASNum" column="cas_id" />
</class>
</hibernate-mapping>
Name and version of the database you are using: PostgreSQL 8.1
The generated SQL (show_sql=true):Code:
NHibernate: select nextval ('cas_num_id_seq')
NHibernate: INSERT INTO cas_nums (chemical, cas_num, cas_id) VALUES (:p0, :p1, :p2)
:p0 = ''
:p1 = '58-08-2'
:p2 = '515'