EzDevInfo.com

nhibernate interview questions

Top nhibernate frequently asked interview questions

What are First and Second Level caching in Hibernate?

Can anyone explain in simple words what First and Second Level caching in Hibernate are?


Source: (StackOverflow)

How to persist an enum using NHibernate

Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum.

I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.


Source: (StackOverflow)

Advertisements

What's the Hi/Lo algorithm?

What's the Hi/Lo algorithm?

I've found this in the NHibernate documentation (it's one method to generate unique keys, section 5.1.4.2), but I haven't found a good explanation of how it works.

I know that Nhibernate handles it, and I don't need to know the inside, but I'm just curious.


Source: (StackOverflow)

NHibernate vs LINQ to SQL

As someone who hasn't used either technology on real-world projects I wonder if anyone knows how these two complement each other and how much their functionalities overlap?


Source: (StackOverflow)

Entity Framework 4 vs NHibernate [closed]

A lot has been talked about Entity Framework first version on the web (also on stackoverflow) and it is clear that it was not a good choice when we already have better alternative like NHibernate. But I can't find a good comparison of Entity Framework 4 and NHibernate. We can say that today NHibernate is the leader among all .NET ORMs, but can we expect Entity Framework 4 to displace NHibernate from this position. I think if Microsoft has really injected very good features in EF4 it can give good competition to NHibernate as it has Visual Studio integration, easier to work with and preference is always given to MS products in most shops.


Source: (StackOverflow)

nHibernate, No row with the given identifier exists

I have a mapping along the lines of this.

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model.Entities" schema="etl" assembly="Model" default-lazy="false">
  <class name="Model.Entities.DataField, Model" table="mdm_field">
    <id name="FieldId" column="field_id" type="int">
      <generator class="native" />
    </id>
    <many-to-one name="KeyField" class="Model.Entities.Key, Model" column="field_id" />
  </class>
</hibernate-mapping>

Now in the database the field_id in the mdm_field table sometimes has a value that does not exist in the related key_field table, so it is basically broken referential integrity. Because of this when I load the entity I get an error "No row with the given identifier exists". How do I configure the mapping to work with this situation so it will not die on this situation.


Source: (StackOverflow)

Best way to save a ordered List to the Database while keeping the ordering

I was wondering if anyone has a good solution to a problem I've encountered numerous times during the last years.

I have a shopping cart and my customer explicitly requests that it's order is significant. So I need to persist the order to the DB.

The obvious way would be to simply insert some OrderField where I would assign the number 0 to N and sort it that way.

But doing so would make reordering harder and I somehow feel that this solution is kinda fragile and will come back at me some day.

(I use C# 3,5 with NHibernate and SQL Server 2005)

Thank you


Source: (StackOverflow)

How does TransactionScope roll back transactions?

I'm writing an integration test where I will be inserting a number of objects into a database and then checking to make sure whether my method retrieves those objects.

My connection to the database is through NHibernate...and my usual method of creating such a test would be to do the following:

NHibernateSession.BeginTransaction();

//use nhibernate to insert objects into database
//retrieve objects via my method
//verify actual objects returned are the same as those inserted

NHibernateSession.RollbackTransaction();

However, I've recently found out about TransactionScope which apparently can be used for this very purpose...

Some example code I've found is as follows:

public static int AddDepartmentWithEmployees(Department dept)
{

    int res = 0;

    DepartmentAdapter deptAdapter = new DepartmentAdapter();
    EmployeeAdapter empAdapter = new EmployeeAdapter();
    using (TransactionScope txScope = new TransactionScope())
    {

        res += deptAdapter.Insert(dept.DepartmentName);
        //Custom method made to return Department ID 
        //after inserting the department "Identity Column"
        dept.DepartmentID = deptAdapter.GetInsertReturnValue();
        foreach(Employee emp in dept.Employees)
        {

            emp.EmployeeDeptID = dept.DepartmentID;
            res += empAdapter.Insert(emp.EmployeeName, emp.EmployeeDeptID);

        }
        txScope.Complete();

    }
    return res;

}

I believe that if I don't include the line txScope.Complete() that the data inserted will be rolled back. But unfortunately I don't understand how that is possible... how does the txScope object keep a track of the deptAdapter and empAdapter objects and their transactions on the database.

I feel like I'm missing a bit of information here...am I really able to replace my BeginTransaction() and RollbackTransaction() calls by surrounding my code using TransactionScope?

If not, how then does TransactionScope work to roll back transactions?


Source: (StackOverflow)

How to update database table schemas with NHibernate schema generation?

I'm trying to figure out how to use NHibernate configuration with mapping to update table schemas, rather than dropping and recreating them.

Currently I'm using the NHibernate.Tool.hbm2ddl.SchemaExport obj with FluentNHibernate to generate the database schema for a mysql database. While I can't say it's a huge problem, whenever I call SchemaExport.Execute on the database, it's going to drop all the tables and then recreate them.

What would be way cooler is if I could just have it update the existing table structures retaining data where possible. But I don't really want to use a commerical product, or a code generator, because I don't like code generation in general, and I don't need this enough that I would consider paying for it. So hopefully any answer would keep these caveats in mind.


Source: (StackOverflow)

Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List

I have a class called ReportRequest as:

public class ReportRequest
{
    Int32 templateId;
    List<Int32> entityIds;

    public virtual Int32? Id
    {
        get;
        set;
    }

    public virtual Int32 TemplateId
    {
        get { return templateId; }
        set { templateId = value; }
    }

    public virtual List<Int32> EntityIds
    {
        get { return entityIds; }
        set { entityIds = value; }
    }

    public ReportRequest(int templateId, List<Int32> entityIds)
    {
        this.TemplateId = templateId;
        this.EntityIds = entityIds;
    }
}

It is mapped using Fluent Hibernate as:

public class ReportRequestMap : ClassMap<ReportRequest>
{
    public ReportRequestMap()
    {
        Id(x => x.Id).UnsavedValue(null).GeneratedBy.Native();
        Map(x => x.TemplateId).Not.Nullable();            
        HasMany(x => x.EntityIds).Table("ReportEntities").KeyColumn("ReportRequestId").Element("EntityId").AsBag().Cascade.AllDeleteOrphan();
    }
}

Now, I create an object of this class as

ReportRequest objReportRequest = new ReportRequest(2, new List<int>() { 11, 12, 15 });

and try to Save the object in database using

session.Save(objReportRequest);

I get the following error: "Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag1[System.Int32]' to type 'System.Collections.Generic.List1[System.Int32]'."

I am not sure if I have mapped the property EntityIds correctly. Please guide.

Thank you!


Source: (StackOverflow)

Fetch vs FetchMany in NHibernate Linq provider

NHibernate eager loading can be done using Fetch and FetchMany, as described here http://mikehadlow.blogspot.com/2010/08/nhibernate-linq-eager-fetching.html

What is the difference between these two methods and under what circumstance would each be used?


Source: (StackOverflow)

Linq to NHibernate [closed]

I have been looking around for some example projects or tutorials on Linq to Nhibernate.

Does anyone know of any good ones?


Source: (StackOverflow)

Best way to convert IList or IEnumerable to Array

I have a HQL query that can generate either an IList of results, or an IEnumerable of results.

However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.

Is there any better way? I went with the CopyTo-approach.


Source: (StackOverflow)

Subsonic Vs NHibernate

What is the concensus on when to use one of these tools adversed to the other? I find Subsonic very useful in terms of getting things done quickly, but on large projects it tends not to scale, and its ties your domain model to your database model. That is where Nhibernate comes in as it gives you lightweight POCOs that are unrelated to your database model, but the setup time is much longer.


Source: (StackOverflow)

When to use inverse=false on NHibernate / Hibernate OneToMany relationships?

I have been trying to get to grips with Hibernate's inverse attribute, and it seems to be just one of those things that is conceptually difficult.

The gist that I get is that when you have a parent entity (e.g. Parent) that has a collection of Child objects using a one-to-many mapping, setting inverse=true on the mapping tells Hibernate that 'the other side (the Child) has responsibility to update itself to maintain the foreign key reference in its table'.

Doing this appears to have 2 benefits when it comes to adding Children to the collection in your code, and then saving the Parent (with cascade-all set): you save an unneccessary hit on the database (because without inverse set, Hibernate thinks it has two places to update the FK relationship), and according to the official docs:

If the column of a association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true".

This all seems to make sense so far. What I don't get is this: when would you NOT want to use inverse=true on a one-to-many relationship?


Source: (StackOverflow)