Unit testing NHibernate Postgresql with SQLite. Sequence generator problem - c#

Can Sqlite NHibernate id generator be made compatible with Postgresql? I'm planning to unit test my NHibernate Postgresql project based on this http://ayende.com/Blog/archive/2009/04/28/nhibernate-unit-testing.aspx
If there is no compatible id generator, is there a way to signal NHibernate to ignore id generator when it is using different dialect?
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="RuntimeNhibernate" namespace="RuntimeNhibernate" >
<class name="Blog" table="blog">
<id name="BlogId" column="blog_id">
<!-- can this be ignored when using different dialect.. -->
<generator class="sequence">
<param name="sequence">blog_id_seq</param>
</generator>
<!-- ...can this -->
</id>
<property name="AllowsComments" column="allows_comments"/>
<property name="CreatedAt" column="created_at"/>
<property name="Subtitle" column="subtitle"/>
<property name="Title" column="title"/>
</class>
</hibernate-mapping>
Error when using Sqlite dialect on Postgresql-specific mapping:
NHibernate.MappingException: could not instantiate id generator: sequence --->
NHibernate.MappingException: Dialect does not support sequences

My suggestion is that you use a DB-agnostic generator, like HiLo.

Related

NHibernate SchemaExport.Execute does not create table

Learning NHibernate by following this tutorial Your first NHibernate based application and I got to the point where you call
new SchemaExport(cfg).Execute(true, true, false);
in a test method to export the schema (create the Product table) for verifying NHibernate was set up correctly
[Test]
public void Can_generate_schema()
{
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Product).Assembly);
new SchemaExport(cfg).Execute(true, true, false);
}
The mapping
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyFirstNHibernateProject" namespace="MyFirstNHibernateProject.Domain">
<class name="Product">
<id name="Id">
<generator class="guid"></generator>
</id>
<property name="Name"></property>
<property name="Category"></property>
<property name="Discontinued"></property>
</class>
</hibernate-mapping>
The configuration
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
<property name="connection.connection_string">Data Source=MyFirstNHibernateProject.sdf</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
The test passed and I can even see the output sql that create table but the table is not being created in the database (sql server compact), I refreshed the db in server explorer and it is still empty.
I have checked these posts
NHibernate SchemaExport not creating table
NHibernate SchemaExport does not create tables when “script” is false
NHibernate does not create Tables
but none of them solve my problem.
any ideas?
I would suggest to use full path in the connection string:
// instead of this
<property name="connection.connection_string"
>Data Source=MyFirstNHibernateProject.sdf</property>
// we should use
<property name="connection.connection_string"
>Data Source=C:\MyFirstNHibernateProject\MyFirstNHibernateProject.sdf</property>
Where the "C:\MyFirstNHibernateProject\" should be the full path to the "MyFirstNHibernateProject.sdf"
Also, in case you are suing CE 4.0 I would suggest to use this dialect:
<property name="dialect">NHibernate.Dialect.MsSqlCe40Dialect</property>

Need access to table with string based primary key in nHibernate

I am trying to map a SQL Server database with nHibernate that is full of tables with varchar primary keys that are generated by external software and I need update/read (no insert) access.
I cannot find a way to get past the following error:
XXXX.Tests.GMCRepository_Fixture.Can_get_existing_GMC_by_parameter'
failed: NHibernate.MappingException :
XXXX.Domain.Mappings.GMC2.hbm.xml(4,6): XML validation error: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate- mapping-2.2'.
Research has suggested this error is relating to there not being a valid primary key (id) defined.
Mapping XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="XXXX.Domain" namespace="XXXX.Domain" xmlns="urn:nhibernate-mapping-2.2" schema="GM.dbo">
<class name="GMC2" table="C2" lazy="true" >
<property name="PARAMETER">
<column name="PARAMETER" sql-type="varchar" not-null="true" />
</property>
...
<id name="Recid">
<column name="recid" sql-type="varchar" not-null="true" />
</id>
</class>
</hibernate-mapping>
Thanks for your help!
I believe that the convention is to have the ID mapping as the first thing under the class declaration.
Also as part of the Id mapping you need to specify the Generator of the ID. In your case I think you will need the assigned generator added to your ID mapping. Your class mapping will look something like this.
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="XXXXCRMAPI.Domain" namespace="XXXXCRMAPI.Domain" xmlns="urn:nhibernate-mapping-2.2" schema="GoldMine.dbo">
<class name="GMContact2" table="CONTACT2" lazy="true" >
<id name="Recid">
<generator type="assigned" />
<column name="recid" sql-type="varchar" not-null="true" />
</id>
<property name="Accountno">
<column name="ACCOUNTNO" sql-type="varchar" not-null="true" />
</property>
...
</class>
</hibernate-mapping>

Select latest group by in nhibernate

I have Canine and CanineHandler objects in my application. The CanineHandler object has a PersonID (which references a completely different database), an EffectiveDate (which specifies when a handler started with the canine), and a FK reference to the Canine (CanineID).
Given a specific PersonID, I want to find all canines they're currently responsible for. The (simplified) query I'd use in SQL would be:
Select Canine.*
from Canine
inner join CanineHandler on(CanineHandler.CanineID=Canine.CanineID)
inner join
(select CanineID,Max(EffectiveDate) MaxEffectiveDate
from caninehandler
group by CanineID) as CurrentHandler
on(CurrentHandler.CanineID=CanineHandler.CanineID
and CurrentHandler.MaxEffectiveDate=CanineHandler.EffectiveDate)
where CanineHandler.HandlerPersonID=#PersonID
Edit: Added mapping files below:
<class name="CanineHandler" table="CanineHandler" schema="dbo">
<id name="CanineHandlerID" type="Int32">
<generator class="identity" />
</id>
<property name="EffectiveDate" type="DateTime" precision="16" not-null="true" />
<property name="HandlerPersonID" type="Int64" precision="19" not-null="true" />
<many-to-one name="Canine" class="Canine" column="CanineID" not-null="true" access="field.camelcase-underscore" />
</class>
<class name="Canine" table="Canine">
<id name="CanineID" type="Int32">
<generator class="identity" />
</id>
<property name="Name" type="String" length="64" not-null="true" />
...
<set name="CanineHandlers" table="CanineHandler" inverse="true" order-by="EffectiveDate desc" cascade="save-update" access="field.camelcase-underscore">
<key column="CanineID" />
<one-to-many class="CanineHandler" />
</set>
<property name="IsDeleted" type="Boolean" not-null="true" />
</class>
I haven't tried yet, but I'm guessing I could do this in HQL. I haven't had to write anything in HQL yet, so I'll have to tackle that eventually anyway, but my question is whether/how I can do this sub-query with the criterion/subqueries objects.
I got as far as creating the following detached criteria:
DetachedCriteria effectiveHandlers = DetachedCriteria.For<Canine>()
.SetProjection(Projections.ProjectionList()
.Add(Projections.Max("EffectiveDate"),"MaxEffectiveDate")
.Add(Projections.GroupProperty("CanineID"),"handledCanineID")
);
but I can't figure out how to do the inner join. If I do this:
Session.CreateCriteria<Canine>()
.CreateCriteria("CanineHandler", "handler", NHibernate.SqlCommand.JoinType.InnerJoin)
.List<Canine>();
I get an error "could not resolve property: CanineHandler of: OPS.CanineApp.Model.Canine". Obviously I'm missing something(s) but from the documentation I got the impression that should return a list of Canines that have handlers (possibly with duplicates). Until I can make this work, adding the subquery isn't going to work...
I've found similar questions, such as Only get latest results using nHibernate but none of the answers really seem to apply with the kind of direct result I'm looking for.
Any help or suggestion is greatly appreciated.
Joining to a derived table, CurrentHandler in your example, won't work in HQL the last time I checked. Try mapping a stored procedure that lets you write whatever SQL you like. Here's what a mapped stored procedure looks like:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="S2.BP.NHSupport" namespace="S2.BP.Model">
<sql-query name="spGoGetMyDogs" callable="true">
<return-scalar column="PersonID" type="int" />
exec spGoGetMyDogs #PersonID=:personID
</sql-query>
</hibernate-mapping>
Then you can pass your PersonID parameter in and have NH map the results back to your objects with a transformer like so:
public IEnumerable<Canine> LetTheDogsOut(int personID) {
return nhSession.GetNamedQuery("spGoGetMyDogs")
.SetInt32("personID", personID)
.SetResultTransformer(Transformers.AliasToBean(typeof(Canine)))
.List<Canine>();
}

NHibernate and multiple databases

I'm trying to solve pretty easy problem. I want to establish connection to 2 totally different databases ( but both mysql ). Now I tried to solve this by creating multiple config files and then creating multiple sessions. Everything works until I reached relations.
I have 2 tables in 2 databases:
db1
- News
db2
- News_Authors
I added News to db1 config and News_Authors to db2 config. When I try to build simple one-to-one relation error, I receive:
An association from the table songs refers to an unmapped class: db1.News_Authors
News.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="project.News, project" table="news" lazy="false">
<id name="id" column="id" type="integer" length="11">
<generator class="native" />
</id>
<property name="title" type="String" length="255" />
<property name="authorid" type="integer" length="5" />
<one-to-one name="NewsAuthor" cascade="all-delete-orphan" lazy="proxy" column="authorid" unique="true" />
</class>
</hibernate-mapping>
News_Authors.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="project.News_Authors, project" table="news_authors" lazy="false">
<id name="id" column="id" type="integer" length="11">
<generator class="native" />
</id>
<property name="name" type="String" length="255" />
</class>
</hibernate-mapping>
config
I added this to enable mappings. Now If I set both in one config files, everything works...
<mapping resource="project.News.hbm.xml" assembly="project" />
So how could I during creating of session also "notify" nhibernate that I have multiple sessions? Or should I pick totally another approach?
One other possible solution would be to create views in one of the sql server databases to reference the tables in the other. Views map just like tables and its easy to do a view that returns something like:
select * from db2.News_Authors
in the db1 database.
this way you would only need a single .hbm.xml file that maps to one of the two databases.
Hope this helps,
-Max
What you are after is not multiple sessions but multiple session factories. See this for more details.
The key here is that you don't have to initialize your session factory through config file - you can do it programatically. And it's just a step to have two session factories.

retrieve PK of mapped table with NHibernate

just started out with NHIbernate and have one question, probably a bit of a stupi one! ;-)
I have 2 tables, Email and Attachment, an email can have zero or more attachments. so I created a hbm file like this:
<set name="Attachments" table="Attachments">
<key column="EmailId" foreign-key="fk_Attachments_Emails"/>
<composite-element class="Foo.Emails.Attachment, Foo.Emails">
<!-- PROBLEM HERE!!! -->
<property name="Id" column="Id" type="long" />
<!-- END PROBLEM -->
<property name="Name" column="Name" type="String" length="50"/>
<property name="Mime" column="MimeType" type="String" length="50"/>
<property name="Size" column="Size" type="long" />
<property name="FilePath" column="FilePath" type="String" length="256"/>
<property name="Parsed" column="Parsed" type="Boolean" />
</composite-element>
</set>
As I want to be able to search for the attachments by PK (the Id column in the set) I included it, but now everytime I try to save an email with attachments I get an error from the db as Nhibernate tries to insert a value into the PK, which my db naturally wont allow.
So, my question is, can I extract the pk for the Attqachment table but stop Nhiberntate from writing it when inserting a an email/attachment? Should I swap to another container like ?? if so wold you be abler to provide an example as I struggling to find a one that I understand!
THanks for your help!
Perhaps a more practical example? Where you have an object structure like this:
Email
--EmailId
--EmailProperty1
--AttachmentCollection
Attachment
--AttachmentId
--ParentEmail
--AttachmentProperty1
mapped to a table structure like this (not how i'd name it, but it's for example):
email
--emailId int PK, identity
--emailProp1 varchar(50)
emailattachment
--attachmentId int PK, identity
--emailId int, FK to email table
--attachmentProp1 varchar(50)
<hibernate-mapping>
<class name="Email" table="email">
<id name="EmailId">
<!-- this tells NHibernate to use DB to generate id -->
<generator class="native"/>
</id>
<property name="EmailProperty1" column="emailProp1"/>
<bag name="AttachmentCollection" lazy="true" inverse="true">
<key column="emailId"/>
<one-to-many class="Foo.Emails.Attachment, Foo.Emails"/>
</bag>
</class>
<class name="Attachment" table="emailattachment">
<id name="AttachmentId">
<generator class="native"/>
</id>
<property="AttachmentProperty1" column="attachmentProp1"/>
<many-to-one name="ParentEmail" class="Foo.Emails.Email, Foo.Emails" lazy="proxy" column="emailId">
</class>
</hibernate-mapping>
In this map, you'd get the bi-directional relationship, and that generator tag is telling nhibernate that objects with a null Id property (you can also specify another "unsaved-value"), then you're inserting the object, else updating. Should fix your current problem.
Couple other things: examine closely what kind of containers you need to use when mapping (bag vs. set vs. list). There's an excellent writeup in hibernatingrhino's NHibernateFAQ.
Also, since you're new to NHibernate, I very, very greatly recommend the summer of nhibernate screencasts. The best tool I've found so far for learning.
I think you want an bi-directional relationship. This way you can navigate the association both ways. This includes generated keys... Here is an example:
<class name="Order" table="ORDERHEADER" lazy="false" >
<id name="OrderId" column="ORDERID" type="int">
<generator class="sequence">
<param name="sequence">"ORDERID_SEQ"</param>
</generator>
</id>
<property name="OrderType" column="ORDERTYPE" type="Int16"/>
<bag name="OrderDetail" table="ORDERDETAIL" lazy="false" inverse="true">
<key column="OrderId"/>
<one-to-many class="OrderDetail" />
</bag>
<class name="OrderDetail" table="ORDERDETAIL" lazy="false">
<id name="OrderDetailId" column="ORDERDETAILID" type="int">
<generator class="sequence">
<param name="sequence">"ORDERDTLID_SEQ"</param>
</generator>
</id>
<property name="OrderId" column="ORDERID" type="Int32"/>
<property name="ItemNumber" column="ITEMNUMBER" type="Int32"/>
<property name="OrderQuantity" column="ORDERQUANTITY" type="Int32"/>
<many-to-one name="Order" class="Order" column="OrderId" />

Categories