NHibernate: Error when saving Bag with NOT-Nullable Constraint - nhibernate

Given are tables Item and ItemTranslation where the latter has a NOT-Nullable foreign key on Item.
ItemTranslation.hbm.xml only has its properties Text and LanguageCode, it does NOT map Item.
Item.hbm.xml:
<bag name="Translations" cascade="all-delete-orphan">
<key column="ItemID" />
<one-to-many class="ItemTranslation, SomeNamespace" />
</bag>
Now when I do the following:
Item item = new Item();
item.Translations.Add( new ItemTranslation { LanguageCode = "DE", Text = "Test DE" } );
item.Translations.Add( new ItemTranslation { LanguageCode = "EN", Text = "Test EN" } );
item.Save();
NHibernate throws the following exception:
System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls.
I could fix it either by mapping ItemID as many-to-one in IssuedItemTranslation.hbm.xml or making the column NULLable.
But both ways are kind of ugly.
Is there any other possibility? Maybe with some change in the bag-mapping?
Thank you in advance.

If we do not want to use inverse mapping (see below) .. we must left the column in DB nullable.
That is how it works. NHibernate will
insert children (or parent)
insert parent (or children) read more here 9.6. Flush
update children with parent id
Another way: Inverse mapping
There is nothing bad on explicit Item back reference mapping on ItemTranslatin. I do that always. And If we really do not like it.. it could be protected property.
But then, we would need inverse mapping.
<bag name="Translations" cascade="all-delete-orphan" inverse="true">
And also set the reference on both sides.
Item item = new Item();
var tr1 = new ItemTranslation {
LanguageCode = "DE",
Text = "Test DE"
Item = item } ;
item.Translations.Add(tr1);
...
This solution does not require item column to be nullable...
That would be the way I suggest. Read more here:
Minimal and correct way to map one-to-many with NHibernate

It works when mapping the bag as follows:
<bag name="Translations" cascade="all-delete-orphan">
<key column="ItemID" not-null="true" update="false" />
<one-to-many class="ItemTranslation, SomeNamespace" />
</bag>
Is this the correct solution?

Related

coldfusion ORM: many-to-many conditional property

I am trying to add a where clause to a many-to-many property I have defined in one of my objects. I must be doing something wrong though because I keep getting hibernate errors saying that the column doesn't exist.
in the template cfc:
<cfproperty
name="Settings"
fieldtype="many-to-many"
cfc="Setting"
linktable="settings_templates"
fkcolumn="templateID"
inversejoincolumn="settingsId"
where="deleted='false'"
>
In the settings cfc:
<cfproperty
name="templates"
fieldtype="many-to-many"
cfc="Template"
linktable="settings_templates"
fkcolumn="settingsId"
inversejoincolumn="templateID"
where="deleted='false'"
>
The error I am getting is:
08/02 16:06:27 [jrpp-170] HIBERNATE ERROR - [Macromedia][SQLServer
JDBC Driver][SQLServer]Invalid column name 'deleted'.
Can anyone see what I am doing wrong? there is a deleted column in both tables, but not in the link table.
The where property behavior for many-to-many is very strange...
In order to debug this, activate the Hibernate logging is primordial.
Refer you to this post: http://www.rupeshk.org/blog/index.php/2009/07/coldfusion-orm-how-to-log-sql/
Take this example:
Article.cfc
/**
* #output false
* #persistent true
* #table article
*/
component {
property name="id" fieldtype="id";
property name="title";
property
name="tags" singularname="tag"
fieldtype="many-to-many" cfc="Tag" linktable="link_article_tag" fkcolumn="articleId"
inversejoincolumn="tagId" where=" deleted = 0 "
;
}
Tag.cfc
/**
* #output false
* #persistent true
* #table tag
*/
component {
property name="id" fieldtype="id";
property name="name";
property name="deleted" dbdefault="0";
property
name="articles" singularname="article"
fieldtype="many-to-many" cfc="Article" linktable="link_article_tag" fkcolumn="tagId"
inversejoincolumn="articleId"
;
}
When I try to list all articles like this ormExecuteQuery('from Article'), see what is appened in the hibernate logs:
select
tags0_.articleId as articleId6_1_,
tags0_.tagId as tagId1_,
tag1_.id as id0_0_,
tag1_.name as name0_0_,
tag1_.deleted as deleted0_0_
from
link_article_tag tags0_
inner join
tag tag1_
on tags0_.tagId=tag1_.id
where
tags0_.deleted = 0
Damned! WTF :| tags0_ == join table ... You see what's wrong?
In order to understand this behavior, I'm going to activate HBMXML generation in Application.cfc with this.ormSettings.saveMapping = true
Here is the files:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class entity-name="Tag" lazy="true"
name="cfc:www.app.models.test.Tag" table="tag">
<id name="id" type="string">
<column length="255" name="id"/>
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="deleted" type="string">
<column default="0" name="deleted"/>
</property>
<bag name="articles" table="link_article_tag">
<key column="tagId"/>
<many-to-many class="cfc:www.app.models.test.Article" column="articleId"/>
</bag>
</class>
</hibernate-mapping>
What we can see: The where attribute is set at the bag level, not at the to many-to-many. If I edit like this:
<bag name="tags" table="link_article_tag">
<key column="articleId"/>
<many-to-many class="cfc:www.app.models.test.Tag" column="tagId" where=" deleted = 0 "/>
</bag>
The generated SQL become:
select
tags0_.articleId as articleId62_1_,
tags0_.tagId as tagId1_,
tag1_.id as id59_0_,
tag1_.name as name59_0_,
tag1_.deleted as deleted59_0_
from
link_article_tag tags0_
inner join
tag tag1_
on tags0_.tagId=tag1_.id
where
tag1_.deleted = 0
This method works but is not good for code maintenance and readability.
If anyone has a better solution, I'm interested.
So far, the only way around this that I have found is to override the getter using ORMExecuteQuery(). There I can query the objects directly and look for things such as this. Personally, I prefer to work in cfscript, so my code would look something like this:
public array function getSettings() {
return ORMExecuteQuery("SELECT s FROM template t JOIN t.settings s WHERE t.id=:id AND s.deleted=:deleted", {
deleted=false, id=this.getId()
});
}
N.B. – EXAMPLE NOT TESTED
Of course, you don't have to use the parameters as I have, you could just use deleted=false, but that's up to you (I like using parameters, personally).
Also, don't forget the singularName attribute on many-to-many properties.
On a related note, I've had issues using properties on both objects. You really only need to use them on the template object, in this case. Think about it this way: A template needs to know its settings, but the settings don't need to know about the template they belong to – using properties on both objects in this way can lead to errors, in some cases.

HiLo NHibernate id generator implementation

I would like to use "hilo" generator but there is no any complete example how to create "specific" table as NH documentation says, and which values pass to it.
The following code fragments taken from NH tutorial
public class Cat
{
private Int64 id;
private string name;
private char sex;
private float weight;
public Cat()
{}
public virtual Int64 Id
{
get { return id; }
set { id = value; }
}
....
}
Mapper
<hibernate-mapping ...>
<class name="Cat" table="Cat">
<id name="Id" >
<column name="CatId" sql-type="Int64" not-null="true"/>
<generator class="hilo"/>
</id>
<property name="Name">
<column name="Name" length="16" not-null="true" />
</property>
....
</class>
</hibernate-mapping>
DB table "Cat"
CatId bigint NOT NULL
Name varchar(16) NOT NULL
Sex char(1) NULL
Weight real NULL
doesn't create anything in the database by default.
Parameters in the "id" node
<param name="table">hi_value</param>
<param name="column">next_value</param>
<param name="max_lo">100</param>
gives "Invalid object name 'hi_value'" error message, without them I'm getting "Invalid object name 'hibernate_unique_key'."
Cuid.Comb that is shown in their tutorial works good but gives 99.12% of fragmentation when I added in a loop 20K cat objects.
Can somebody point me to an example of "hilo" implementation or give a tip what I'm missing?
Thanks.
This solution solved my problem. It's fairly simple, don't know why on nhibernate site there is no tiny example like that.
You may be running into NH-2687.

nHibernate join query

i have two tables (graph representation - one table is nodes, other is link between nodes), and i want to write this query in nHibernate:
SELECT
distinct(t.id), t.NodeName, e.Fk_linkOne, e.Fk_linkTwo, e.RelationName
FROM Nodes t
INNER JOIN NodeRelation e ON t.Id=e.Fk_linkOne OR t.Id=e.Fk_linkTwo
where (e.Fk_linkOne =84 OR e.Fk_linkTwo=84 ) AND t.Id!=84
I did not find how to connect two tables wiht join, that have OR in it..
ICriteria criteriaSelect = Session
.CreateCriteria(typeof(NodeRelation ), "nodeRelations")
.CreateCriteria("nodeRelations.Node", "node",
NHibernate.SqlCommand.JoinType.InnerJoin)
You can only define your joins as per the associations you have defined in your mappings. As far as I know you can't define OR style relationships in Nhibernate. Consider using a self referential style graph representation.
public class Node
{
public IList<Node> Parents { get; set; }
public IList<Node> Children { get; set; }
}
<bag name="Parents" table="Node_Relation">
<key column="ChildId" />
<many-to-many class="Node" column="ParentId" />
</bag>
<bag name="Children" table="Node_Relation">
<key column="ParentId" />
<many-to-many class="Node" column="ChildId" />
</bag>
You should be using DetachedCriteria to get the same done. I am not sure about your query but I will jsut give a shot.
var dc1= DetachedCriteria.For(typeof( NodeRelation )).Add(Restrictions.Eq("Fk_linkOne", 84))
.SetProjection(Projections.Property("Fk_linkOne"));
var dc2= DetachedCriteria.For(typeof( NodeRelation )).Add(Restrictions.Eq("Fk_linkTwo", 84))
.SetProjection(Projections.Property("Fk_linkTwo"));
Session.CreateCriteria(typeof(Nodes))
.Add(Subqueries.PropertyIn("Id", dc1))
.Add(Subqueries.PropertyIn("Id", dc2))
.Add(Restrictions.Eq("Id", 84)).List<Nodes>;
Hope the above query is corrrect. please let me know if you cant get it to work after obs trying smethings and let me know wat u tried.
It always depends on your classes and not so much on your tables. Remember, you are using a ORM and you are working with a class model.
Assumed that your classes look like this:
class Node
{
List<Node> Relations { get; private set; }
List<Node> InverseRelations { get; private set; }
}
You may map it like this:
<class name="Node">
<!-- .... -->
<bag name="Relations" table="NodeRelation">
<key name="Fk_linkOne">
<many-to-many class="Node" column="Fk_linkTwo"/>
</bag>
<bag name="InverseRelations" table="NodeRelation" inverse="true">
<key name="Fk_linkTwo">
<many-to-many class="Node" column="Fk_linkOne"/>
</bag>
</class>
This way you get asymetrical relations (this means: when Node A relates to Node B, B isn't necessarily related to A, except of the InverseRelation of course). I don't know what you actually need, so this is an assumption based on your database design.
Your query may look like this:
from Node n
where
:x in elements(n.Relations)
or :x in elements(n.InverseRelations)
Note: x is an entity type, not just an id (you need to load it using session.Load<Node>(84)),
Another way for the samy query:
select distinct n
from Node n
inner join n.Relations e1
inner join n.InverseRelations e2
where e1.id = 84 or e2.id = 84
Or another way without the use of the inverse relations:
select n
from Node n, Node n2 inner join n.Relations e
where
(n = n2 and e.id = 84)
OR (n = e and n2.id = 84)
In criteria I would take the second solution and write it like this:
session.CreateCriteria<Node>("n")
.SetProjection(Projections.Distinct("n"))
.CreateCriteria("Relations", "e1")
.CreateCriteria("InverseRelations", "e2")
.Add(Expression.Or(
Expression.Eq("e1.id", 84),
Expression.Eq("e2.id", 84));

Hibernate can't load Custom SQL collection

There is a table Item like,
code,name
01,parent1
02,parent2
0101,child11
0102,child12
0201,child21
0202,child22
Create a java object and hbm xml to map the table.The Item.parent is a Item whose code is equal to the first two characters of its code :
class Item{
String code;
String name;
Item parent;
List<Item> children;
.... setter/getter....
}
<hibernate-mapping>
<class name="Item" table="Item">
<id name="code" length="4" type="string">
<generator class="assigned" />
</id>
<property name="name" column="name" length="50" not-null="true" />
<many-to-one name="parent" class="Item" not-found="ignore">
<formula>
<![CDATA[
(select i.code,r.name from Item i where (case length(code) when 4 then i.code=SUBSTRING(code,1,2) else false end))
]]>
</formula>
</many-to-one>
<bag name="children"></bag>
</class>
</hibernate-mapping>
I try to use formula to define the many-to-one relationship,but it doesn't work!Is there something wrong?Or is there other method?
Thanks!
ps,I use mysql database.
add 2010/05/23
Pascal's answer is right,but the "false" value must be replaced with other expression,like "1=2".Because the "false" value would be considered to be a column of the table.
select i.code
from Item i
where (
case length(code)
when 4 then i.code=SUBSTRING(code,1,2)
else 1=2
end)
And I have another question about the children "bag" mapping.There isn't formula configuration option for "bag",but we can use "loader" to load a sql-query.I configure the "bag" as following.But it get a list whose size is 0.What's wrong with it?
<class>
... ...
<bag name="children">
<key />
<one-to-many class="Item"></one-to-many>
<loader query-ref="getChildren"></loader>
</bag>
</class>
<sql-query name="getChildren">
<load-collection alias="r" role="Item.children" />
<![CDATA[(select {r.*} from Item r join Item o where
o.code=:code and
(
case length(o.code)
when 2 then (length(r.code)=4 and SUBSTRING(r.code,1,2)=o.code)
else 1=2
end ))]]>
</sql-query>
According to the documentation, you're supposed to return the value of the computed foreign key, nothing more:
formula (optional): an SQL expression that defines the value for a computed foreign key.
So I would expect a query like this:
select i.code
from Item i
where (
case length(code)
when 4 then i.code=SUBSTRING(code,1,2)
else false
end)
Disclaimer: not tested.

NHibernate - need help with ICriteria query

I am having trouble getting my query by criteria to work.
I want to filter the UserPublications collection by userId but it is not filtering. The ClientPublications collection has filtered correctly though.
Any advice?
Thanks in advance.
public IList<ClientReport> GetAvailableClientReports(int userId)
{
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(ClientReport))
.CreateCriteria("ClientPublications")
.Add(Expression.Eq("IsDownloaded", true))
.SetResultTransformer(CriteriaUtil.DistinctRootEntity)
.AddOrder(Order.Asc("Name"))
.CreateCriteria("UserPublications")
.CreateAlias("ClientUser", "user")
.Add(Expression.Eq("user.UserId", userId));
return GetByCriteria(criteria);
}
If you mapped the UserId property as "Id" in your mapping file (which you probably do if you used the same conventions as in this question), it should be:
.Add(Expression.Eq("user.Id", userId))
The Id property is a special case in NHibernate
why don't you create an alias for UserPublications and add the expression there? like
.CreateCriteria("UserPublications", "up")
.Add(Expression.Eq("up.ClientUser.UserId", userId));
or maybe
.CreateCriteria("UserPublications", "up")
.CreateAlias("up.ClientUser", "user")
.Add(Expression.Eq("user.UserId", userId));
as far as i can see calling
.CreateAlias("ClientUser", "user")
depends on NH's ability to detect where ClientUser exists and create the join which may not be working (bug or otherwise)
For future ref, I got it working by adding a filter in the mapping file
First define the filter in the parent class mapping:
<filter-def name="userFilter">
<filter-param name="userId" type="System.Int32"/>
</filter-def>
Then define filter further in the mapping to the collection
<bag name="UserPublications" access="property" lazy="true" cascade="all-delete-orphan">
<key column="ClientPublicationID"/>
<one-to-many class="ReportMgr.Model.ClientUserPublication, ReportMgr.Model" />
<filter name="userFilter" condition="ClientUserID = :userId"></filter>
</bag>
Then enable the filter and specify the parameter value just before executing the ICriteria query:
NHibernateSession.EnableFilter("userFilter").SetParameter("userId", userId);
ICriteria criteria = NHibernateSession.CreateCriteria(typeof(ClientReport))
.CreateCriteria("ClientPublications")
blah blah blah
return GetByCriteria(criteria);