Search Results

Search found 156 results on 7 pages for 'createcriteria'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • NHibernate query CreateCriteria

    - by Jacob
    Is it possible to chose what columns I want in return from Session.CreateCriteria() ? egz.: var x = session.CreateCriteria(); x.CreateAlias("EmployeePosition", "employeePosition"); x.Add(Restrictions.Eq("employeePosition.Name", "Developer")); and is there a way to add something like "select LastName" to avoid downloading the whole row.

    Read the article

  • Using EhCache for session.createCriteria(...).list()

    - by James Smith
    I'm benchmarking the performance gains from using a 2nd level cache in Hibernate (enabling EhCache), but it doesn't seem to improve performance. In fact, the time to perform the query slightly increases. The query is: session.createCriteria(MyEntity.class).list(); The entity is: @Entity @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class MyEntity { @Id @GeneratedValue private long id; @Column(length=5000) private String data; //---SNIP getters and setters--- } My hibernate.cfg.xml is: <!-- all the normal stuff to get it to connect & map the entities plus:--> <property name="hibernate.cache.region.factory_class"> net.sf.ehcache.hibernate.EhCacheRegionFactory </property> The MyEntity table contains about 2000 rows. The problem is that before adding in the cache, the query above to list all entities took an average of 65 ms. After the cache, they take an average of 74 ms. Is there something I'm missing? Is there something extra that needs to be done that will increase performance?

    Read the article

  • How to set offset in GORM when using createCriteria?

    - by firnnauriel
    I'm just wondering if it's possible for 'createCriteria' to specify the paginateParams (i.e. offset) similar to dynamic finder (findAll, etc.) Note that this code is not working since 'offset' is not documented in http://www.grails.org/doc/1.2.1/ref/Domain%20Classes/createCriteria.html def c = SnbrItemActDistance.createCriteria() def results = c.list { eq('iid', newsId) ge('distance', cap) maxResults(count) offset(offset) order('distance', 'desc') }

    Read the article

  • Load collections eagerly in NHibernate using Criteria API

    - by Zuber
    I have an entity A which HasMany entities B and entities C. All entities A, B and C have some references x,y and z which should be loaded eagerly. I want to read from the database all entities A, and load the collections of B and C eagerly using criteria API. So far, I am able to fetch the references in 'A' eagerly. But when the collections are loaded, the references within them are lazily loaded. Here is how I do it AllEntities_A = _session.CreateCriteria(typeof(A)) .SetFetchMode("x", FetchMode.Eager) .SetFetchMode("y", FetchMode.Eager) .List<A>().AsQueryable(); The mapping of entity A using Fluent is as shown below. _B and _C are private ILists for B & C respectively in A. Id(c => c.SystemId); Version(c => c.Version); References(c => c.x).Cascade.All(); References(c => c.y).Cascade.All(); HasMany<B>(Reveal.Property<A>("_B")) .AsBag() .Cascade.AllDeleteOrphan() .Not.LazyLoad() .Inverse() .Cache.ReadWrite().IncludeAll(); HasMany<C>(Reveal.Property<A>("_C")) .AsBag() .Cascade.AllDeleteOrphan() .LazyLoad() .Inverse() .Cache.ReadWrite().IncludeAll(); I don't want to make changes to the mapping file, and would like to load the entire entity A eagerly. i.e. I should get a List of A's where there will be List of B's and C's whose reference properties will also be loaded eagerly

    Read the article

  • How do I setup a Criteria in nHibernate to query against multiple values

    - by AWC
    I want to query for a set of results based on the contents of a list, I've managed to do this for a single instance of the class Foo, but I'm unsure how I would do this for a IList<Foo>. So for a single instance of the class Foo, this works: public ICriteria CreateCriteria(IList<Foo> foo) { return session .CreateCriteria<Component>() .CreateCriteria("Versions") .CreateCriteria("PublishedEvents") .Add(Restrictions.And(Restrictions.InsensitiveLike("Name", foo.Name, MatchMode.Anywhere), Restrictions.InsensitiveLike("Type", foo.Type, MatchMode.Anywhere))) .SetCacheable(true); } But how do I do this when the method parameter is a list of Foo? public ICriteria CreateCriteria(IList<Foo> foos) { return session .CreateCriteria<Component>() .CreateCriteria("Versions") .CreateCriteria("PublishedEvents") .Add(Restrictions.And(Restrictions.InsensitiveLike("Name", foo.Name, MatchMode.Anywhere), Restrictions.InsensitiveLike("Type", foo.Type, MatchMode.Anywhere))) .SetCacheable(true); }

    Read the article

  • Is there any difference in which order I createCriteria and beginTransaction using Hibernate?

    - by user2519543
    Just wondering is there any difference when I beginTransaction [org.hibernate] before or after creating Criteria/Query etc.? example 1: ... Transaction tx= session.beginTransaction(); Criteria c = session.createCriteria(class); result = c.uniqueResult(); tx.commit(); ... example 2: ... Criteria c = session.createCriteria(class); Transaction tx= session.beginTransaction(); result = c.uniqueResult(); tx.commit(); ... Thanks.

    Read the article

  • Using NHibernate Criteria API to select sepcific set of data together with a count

    - by mfloryan
    I have the following domain set up for persistence with NHibernate: I am using the PaperConfiguration as the root aggregate. I want to select all PaperConfiguration objects for a given Tier and AcademicYearConfiguration. This works really well as per the following example: ICriteria criteria = session.CreateCriteria<PaperConfiguration>() .Add(Restrictions.Eq("AcademicYearConfiguration", configuration)) .CreateCriteria("Paper") .CreateCriteria("Unit") .CreateCriteria("Tier") .Add(Restrictions.Eq("Id", tier.Id)) return criteria.List<PaperConfiguration>(); (Perhaps there is a better way of doing this though). Yet also need to know how many ReferenceMaterials there are for each PaperConfiguration and I would like to get it in the same call. Avoid HQL - I already have an HQL solution for it. I know this is what projections are for and this question suggests an idea but I can't get it to work. I have a PaperConfigurationView that has, instead of IList<ReferenceMaterial> ReferenceMaterials the ReferenceMaterialCount and was thinking along the lines of ICriteria criteria = session.CreateCriteria<PaperConfiguration>() .Add(Restrictions.Eq("AcademicYearConfiguration", configuration)) .CreateCriteria("Paper") .CreateCriteria("Unit") .CreateCriteria("Tier") .Add(Restrictions.Eq("Id", tier.Id)) .SetProjection( Projections.ProjectionList() .Add(Projections.Property("IsSelected"), "IsSelected") .Add(Projections.Property("Paper"), "Paper") // and so on for all relevant properties .Add(Projections.Count("ReferenceMaterials"), "ReferenceMaterialCount") .SetResultTransformer(Transformers.AliasToBean<PaperConfigurationView>()); return criteria.List< PaperConfigurationView >(); unfortunately this does not work. What am I doing wrong? The following simplified query: ICriteria criteria = session.CreateCriteria<PaperConfiguration>() .CreateCriteria("ReferenceMaterials") .SetProjection( Projections.ProjectionList() .Add(Projections.Property("Id"), "Id") .Add(Projections.Count("ReferenceMaterials"), "ReferenceMaterialCount") ).SetResultTransformer(Transformers.AliasToBean<PaperConfigurationView>()); return criteria.List< PaperConfigurationView >(); creates this rather unexpected SQL: SELECT this_.Id as y0_, count(this_.Id) as y1_ FROM Domain.PaperConfiguration this_ inner join Domain.ReferenceMaterial referencem1_ on this_.Id=referencem1_.PaperConfigurationId The above query fails with ADO.NET error as it obviously is not a correct SQL since it is missing a group by or the count being count(referencem1_.Id) rather than (this_.Id). NHibernate mappings: <class name="PaperConfiguration" table="PaperConfiguration"> <id name="Id" type="Int32"> <column name="Id" sql-type="int" not-null="true" unique="true" index="PK_PaperConfiguration"/> <generator class="native" /> </id> <!-- IPersistent --> <version name="VersionLock" /> <!-- IAuditable --> <property name="WhenCreated" type="DateTime" /> <property name="CreatedBy" type="String" length="50" /> <property name="WhenChanged" type="DateTime" /> <property name="ChangedBy" type="String" length="50" /> <property name="IsEmeEnabled" type="boolean" not-null="true" /> <property name="IsSelected" type="boolean" not-null="true" /> <many-to-one name="Paper" column="PaperId" class="Paper" not-null="true" access="field.camelcase"/> <many-to-one name="AcademicYearConfiguration" column="AcademicYearConfigurationId" class="AcademicYearConfiguration" not-null="true" access="field.camelcase"/> <bag name="ReferenceMaterials" generic="true" cascade="delete" lazy="true" inverse="true"> <key column="PaperConfigurationId" not-null="true" /> <one-to-many class="ReferenceMaterial" /> </bag> </class> <class name="ReferenceMaterial" table="ReferenceMaterial"> <id name="Id" type="Int32"> <column name="Id" sql-type="int" not-null="true" unique="true" index="PK_ReferenceMaterial"/> <generator class="native" /> </id> <!-- IPersistent --> <version name="VersionLock" /> <!-- IAuditable --> <property name="WhenCreated" type="DateTime" /> <property name="CreatedBy" type="String" length="50" /> <property name="WhenChanged" type="DateTime" /> <property name="ChangedBy" type="String" length="50" /> <property name="Name" type="String" not-null="true" /> <property name="ContentFile" type="String" not-null="false" /> <property name="Position" type="int" not-null="false" /> <property name="CommentaryName" type="String" not-null="false" /> <property name="CommentarySubjectTask" type="String" not-null="false" /> <property name="CommentaryPointScore" type="String" not-null="false" /> <property name="CommentaryContentFile" type="String" not-null="false" /> <many-to-one name="PaperConfiguration" column="PaperConfigurationId" class="PaperConfiguration" not-null="true"/> </class>

    Read the article

  • NHibernate Query across multiple tables

    - by Dai Bok
    I am using NHibernate, and am trying to figure out how to write a query, that searchs all the names of my entities, and lists the results. As a simple example, I have the following objects; public class Cat { public string name {get; set;} } public class Dog { public string name {get; set;} } public class Owner { public string firstname {get; set;} public string lastname {get; set;} } Eventaully I want to create a query , say for example, which and returns all the pet owners with an name containing "ted", OR pets with a name containing "ted". Here is an example of the SQL I want to execute: SELECT TOP 10 d.*, c.*, o.* FROM owners AS o INNER JOIN dogs AS d ON o.id = d.ownerId INNER JOIN cats AS c ON o.id = c.ownerId WHERE o.lastname like '%ted%' OR o.firstname like '%ted%' OR c.name like '%ted%' OR d.name like '%ted%' When I do it using Criteria like this: var criteria = session.CreateCriteria<Owner>() .Add( Restrictions.Disjunction() .Add(Restrictions.Like("FirstName", keyword, MatchMode.Anywhere)) .Add(Restrictions.Like("LastName", keyword, MatchMode.Anywhere)) ) .CreateCriteria("Dog").Add(Restrictions.Like("Name", keyword, MatchMode.Anywhere)) .CreateCriteria("Cat").Add(Restrictions.Like("Name", keyword, MatchMode.Anywhere)); return criteria.List<Owner>(); The following query is generated: SELECT TOP 10 d.*, c.*, o.* FROM owners AS o INNER JOIN dogs AS d ON o.id = d.ownerId INNER JOIN cats AS c ON o.id = c.ownerId WHERE o.lastname like '%ted%' OR o.firstname like '%ted%' AND d.name like '%ted%' AND c.name like '%ted%' How can I adjust my query so that the .CreateCriteria("Dog") and .CreateCriteria("Cat") generate an OR instead of the AND? thanks for your help.

    Read the article

  • Cannot Cache NHibernate Future Criteria Results

    - by Emilian
    I have the following code: public void FuturesQuery() { using (var session = SessionFactory.OpenSession()) { var blogs = session.CreateCriteria<Blog>() .SetMaxResults(5) .SetCacheable(true) .SetCacheMode(CacheMode.Normal) .SetCacheRegion("BlogQuery") .Future<Blog>(); var countOfBlogs = session.CreateCriteria<Blog>() .SetProjection(Projections.Count(Projections.Id())) .SetCacheable(true) .SetCacheMode(CacheMode.Normal) .SetCacheRegion("BlogQuery") .FutureValue<int>(); Console.WriteLine("Number of blogs: {0}", countOfBlogs.Value); foreach (var blog in blogs) { Console.WriteLine(blog.Title); } } using (var session = SessionFactory.OpenSession()) { var blogs = session.CreateCriteria<Blog>() .SetMaxResults(5) .SetCacheable(true) .SetCacheMode(CacheMode.Normal) .SetCacheRegion("BlogQuery") .Future<Blog>(); var countOfBlogs = session.CreateCriteria<Blog>() .SetProjection(Projections.Count(Projections.Id())) .SetCacheable(true) .SetCacheMode(CacheMode.Normal) .SetCacheRegion("BlogQuery") .FutureValue<int>(); Console.WriteLine("Number of blogs: {0}", countOfBlogs.Value); foreach (var blog in blogs) { Console.WriteLine(blog.Title); } } } I was expecting that the second time I query for blogs and count of blogs I will get values from cache but instead the queries hit the database. If I don't use Futures I get the expected results. Does this means that results from Criteria using futures cannot be cached?

    Read the article

  • How can I use Hibernate Criteria's to query nested tables?

    - by cbmeeks
    I've looked all over SO and Google but I guess I'm not using the right search terms or something. Anyway, say I have three tables: Companies ----------------------------------------- id name user_id Users ----------------------------------------- id username usertype_id UserTypes ----------------------------------------- id typeofuser So ACME would be a company, it would have a user Moe and Moe would be a usertype of Stooge. In SQL, I would do something like: select * from companies c join users u on (u.id = c.user_id) join usertypes ut on (ut.id = u.usertype_id) where ut.typeofuser = 'Stooge' But I can't seem to figure out how to do that in a Criteria. I have tried: Criteria crit = io.getSession().createCriteria(Company.class); List<Company> list = crit.createCriteria("users") .createCriteria("usertypes") .add(Restriction.eq("typeofuser", "Stooge").list(); But I get back way too many records. And the results don't even come close to being accurate. I've also tried: Criteria crit = io.getSession().createCriteria(Company.class); List<Company> list = crit.createAlias("users", "u") .createAlias("u.usertypes", "ut") .add(Restriction.eq("ut.typeofuser", "Stooge").list(); Seems to bring back the exact same result set. I actually have read the user manual. And when I nest only one level deep (ie, searching by users is fine) but when I get two layers deep, I can't quite get it. And the manual is no help. I just can't relate cats and kittens to business objects. Maybe they should use cats, kittens and fleas? :-/ Thanks for any suggestions.

    Read the article

  • Finding parents where child collection does not contain an item with a specific property value

    - by Colin Bowern
    I am trying to get a list of parents where the child collection does not contain an item of a specific type. The LINQ equivalent would be something like: dataset.Where(x => x.Items.FirstOrDefault(y => y.Type.Code == "ABC") == null) The object model is Parent Child (Items) Type Code If Parent is my aggregate root, how would I model this in NHibernate criteria/query? Here's my first attempt: var results = session.CreateCriteria<Parent>() .CreateCriteria("Items") .CreateCriteria("Type") .Add(Restrictions.Not(Restrictions.Eq("Code", "ABC"))) .SetResultTransformer(Transformers.DistinctRootEntity) .List<Parent>(); This doesn't seem to return the right entities - it just returns them all.

    Read the article

  • Nhibernate criteria query inserts an extra order by expression when using JoinType.LeftOuterJoin and Projections

    - by Aaron Palmer
    Why would this nhibernate criteria query produce the sql query below? return Session.CreateCriteria(typeof(FundingCategory), "fc") .CreateCriteria("FundingPrograms", "fp") .CreateCriteria("Projects", "p", JoinType.LeftOuterJoin) .Add(Restrictions.Disjunction() .Add(Restrictions.Eq("fp.Recipient.Id", recipientId)) .Add(Restrictions.Eq("p.Recipient.Id", recipientId)) ) .SetProjection(Projections.ProjectionList() .Add(Projections.GroupProperty("fc.Name"), "fcn") .Add(Projections.Sum("fp.ObligatedAmount"), "fpo") .Add(Projections.Sum("p.ObligatedAmount"), "po") ) .AddOrder(Order.Desc("fpo")) .AddOrder(Order.Desc("po")) .AddOrder(Order.Asc("fcn")) .List<object[]>(); SELECT this_.Name as y0_, sum(fp1_.ObligatedAmount) as y1_, sum(p2_.ObligatedAmount) as y2_ FROM fundingCategories this_ inner join fundingPrograms fp1_ on this_.fundingCategoryId = fp1_.fundingCategoryId left outer join projects p2_ on fp1_.fundingProgramId = p2_.fundingProgramId WHERE (fp1_.recipientId = 6 /* @p0 */ or p2_.recipientId = 6 /* @p1 */) GROUP BY this_.Name ORDER BY p2_.name asc, y1_ desc, y2_ desc, y0_ asc It is incorrectly putting the p2_name asc into the ORDER BY statement, and causing it to crash. This only happens when I use JoinType.LeftOuterJoin on my Projects criteria. Is this a known nhibernate bug? I'm using nhibernate 2.0.1.4000. Thanks for any insight.

    Read the article

  • nHibernate query by example with multiple associated objects

    - by BurnWithLife
    I'm trying to use nhibernate's query by example to build dynamic queries. I'm stuck on how to code for an example object with multiple associations. Here's an example from NHibernate in Action. Its a User object with Items. Example exampleUser = Example.Create(u).IgnoreCase().EnableLike(MatchMode.Anywhere); Example exampleItem = Example.Create(i).IgnoreCase().EnableLike(MatchMode.Anywhere); return GetSession().CreateCriteria(typeof(User)) .Add( exampleUser ) .CreateCriteria("Items") .Add( exampleItem ) .List<User>(); If the User object has let's say a Category object as a property, how could I add that in to the above example? If i put another CreateCriteria at the end it refers to the Items, not the User.

    Read the article

  • Finding parents where child collection does not contain an item

    - by Colin Bowern
    I am trying to get a list of parents where the child collection does not contain an item of a specific type. The LINQ equivalent would be something like: dataset.Where(x => x.Items.FirstOrDefault(y => y.Type.Code == "ABC") == null) The object model is Parent Child (Items) Type Code If Parent is my aggregate root, how would I model this in NHibernate criteria/query? Here's my first attempt: var results = session.CreateCriteria<Parent>() .CreateCriteria("Items") .CreateCriteria("Type") .Add(Restrictions.Not(Restrictions.Eq("Code", "ABC"))) .SetResultTransformer(Transformers.DistinctRootEntity) .List<Parent>(); This doesn't seem to return the right entities - it just returns them all.

    Read the article

  • Create Custom Criterion in NHibernate?

    - by vbullinger
    I'm still a bit of a n00b when it comes to NHibernate. Let's say I have the following: var myCriteria = this.Session.CreateCriteria(typeof(SomeModel)).Add(Restrictions.Eq("SomeProperty", someValue); Then, let's say I want to add criteria in a way that's reusable. Meaning, I want to make a custom criterion. I'm seeing very, very little information online on this. Specifically, I'd like to turn the following: var myCriteria = this.Session.CreateCriteria(typeof(SomeModel)) .Add(Restrictions.Eq("SomeProperty", someValue) .CreateAlias("SomeClass", "alias", JoinType.LeftOuterJoin) .Add(Restrictions.Eq("alias.SomeOtherProperty", someOtherValue)); Into the following: var myCriteria = this.Session.CreateCriteria(typeof(SomeModel)) .Add(Restrictions.Eq("SomeProperty", someValue) .Add(this.GetAliasCriterion()); Thus extracting .CreateAlias("SomeClass", "alias", JoinType.LeftOuterJoin).Add(Restrictions.Eq("alias.SomeOtherProperty", someOtherValue)); into a method. Is this possible? How does this work?

    Read the article

  • Strongly typed properties with NHIbernate

    - by Alexander Shapovalov
    Hello, I am using NHibernate in my project, but I dont like to use typed properties for selecting items from database. Is it possible to have instead of session.CreateCriteria(typeof(IEntry)).AddOrder(Order.Desc("Alias")) somthing like this session.CreateCriteria(typeof(IEntry)).AddOrder(Order.Desc(x=>x.Alias)) Thanks, Alexander. http://atomiccms.com

    Read the article

  • How to achieve an eagerly loaded, filtered child collection with the NHibernate criteria API

    - by vakman
    Is it possible to use the criteria api to load a set of parent objects along with a filtered, eagerly loaded set of child objects? I'm trying to query a list of categories and at the same time load the categories products that start with the letter M. The query below gives me the results I want but the Products are not eagerly loaded, that is NHibernate performs additional queries when I enumerate the Product collection: var categoriesWithProducts = session.CreateCriteria<Category>() .SetFetchMode("Products", FetchMode.Eager) .CreateCriteria("Products") .Add(Expression.Like("Name", "M%")) .List<Category>(); What am I missing here?

    Read the article

  • hibernate criteria OneToMany, ManyToOne and List

    - by jrsokolow
    Hi, I have three entities ClassA, ClassB and ClassC. ClassA { ... @Id @GeneratedValue @Column(name = "a_id") private long id; ... @OneToMany(cascade={CascadeType.ALL}) @JoinColumn(name="a_id") private List<ClassB> bbb; ... } ClassB { ... @ManyToOne private ClassC ccc; ... } ClassC { ... private String name; ... } I want to filter by hibernate criteria ClassA by 'name' member of ClassC. So I want to obtain by hibernate criteria list of ClassA objects which have inside ClassC objects with specified name. Problem is that access to ClassC objects is through ClassB list. I tried something like this but it does not work: crit.createCriteria("bbb").createCriteria("ccc").add(Restrictions.ilike("name", name, MatchMode.ANYWHERE)); I will be grateful for help.

    Read the article

  • Grails: Problem with nested associations in criteria builder

    - by Mr.B
    I have a frustrating problem with the criteria builder. I have an application in which one user has one calendar, and a calendar has many entries. Seems straightforward enough, but when I try to get the calendar entries for a given user, I can't access the user property (MissingMethodException). Here's the code: def getEntries(User user) { def entries = Entries.createCriteria().list() { calendar { user { eq("user.id", user.id) } } } } I have even tried the following variation: def getEntries(User user) { def entries = Entries.createCriteria().list() { calendar { eq("user", user) } } } That did not raise an exception, but didn't work either. Here's the relevant parts of the domain classes: class Calendar { static belongsTo = [user: User] static hasMany = [entries: Entries] ... } class User { Calendar calendar ... } class Entry { static belongsTo = [calendar: Calendar] ... } When Googling I came across a similar problem noted in early 2008: http://jira.codehaus.org/browse/GRAILS-1412 But according to that link this issue should have been solved long ago. What am I doing wrong?

    Read the article

  • NHibernate.Linq to Criteria API translation help needed

    - by Arnis L.
    I'm not sure how to add paging to this: Session.Linq<Article>() .Where(art => art.Tags.Any(t => t.Name == tag)).ToList(). So i decided to use Criteria API. var rowCount = Session.CreateCriteria(typeof(Article)) .SetProjection(Projections.RowCount()).FutureValue<Int32>(); var res = Session.CreateCriteria(typeof(Article)) .Add(/* any help with this? :) */) .SetFirstResult(page * pageSize) .SetMaxResults(pageSize) .AddOrder(new Order("DatePublish", true)) .Future<Article>(); totalCount = rowCount.Value; Any help appreciated.

    Read the article

  • NHibernate FetchMode.Lazy

    - by RyanFetz
    I have an object which has a property on it that has then has collections which i would like to not load in a couple situations. 98% of the time i want those collections fetched but in the one instance i do not. Here is the code I have... Why does it not set the fetch mode on the properties collections? [DataContract(Name = "ThemingJob", Namespace = "")] [Serializable] public class ThemingJob : ServiceJob { [DataMember] public virtual Query Query { get; set; } [DataMember] public string Results { get; set; } } [DataContract(Name = "Query", Namespace = "")] [Serializable] public class Query : LookupEntity<Query>, DAC.US.Search.Models.IQueryEntity { [DataMember] public string QueryResult { get; set; } private IList<Asset> _Assets = new List<Asset>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Asset> Assets { get { return _Assets; } set { _Assets = value; } } private IList<Theme> _Themes = new List<Theme>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Theme> Themes { get { return _Themes; } set { _Themes = value; } } private IList<Affinity> _Affinity = new List<Affinity>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Affinity> Affinity { get { return _Affinity; } set { _Affinity = value; } } private IList<Word> _Words = new List<Word>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Word> Words { get { return _Words; } set { _Words = value; } } } using (global::NHibernate.ISession session = NHibernateApplication.GetCurrentSession()) { global::NHibernate.ICriteria criteria = session.CreateCriteria(typeof(ThemingJob)); global::NHibernate.ICriteria countCriteria = session.CreateCriteria(typeof(ThemingJob)); criteria.AddOrder(global::NHibernate.Criterion.Order.Desc("Id")); var qc = criteria.CreateCriteria("Query"); qc.SetFetchMode("Assets", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Themes", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Affinity", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Words", global::NHibernate.FetchMode.Lazy); pageIndex = Convert.ToInt32(pageIndex) - 1; // convert to 0 based paging index criteria.SetMaxResults(pageSize); criteria.SetFirstResult(pageIndex * pageSize); countCriteria.SetProjection(global::NHibernate.Criterion.Projections.RowCount()); int totalRecords = (int)countCriteria.List()[0]; return criteria.List<ThemingJob>().ToPagedList<ThemingJob>(pageIndex, pageSize, totalRecords); }

    Read the article

  • How can you query for an object using one of its properties' id

    - by James Smith
    I have two entities, say, House and People, where multiple people can live in one house. It's a unidirectional link where each Person has a field for which House they belong to, so the Person table has a column named house_id. I need to be able to return all the Person objects who belong to a certain House, but I only have the id of the house. This can be done like this: House house = houseDAO.findById(houseId); List people = session.createCriteria(Person.class).add(Restrictions.eq("house", house)).list(); But since I don't need the house, that's adding an unnecessary query. I've tried to do: session.createCriteria(Person.class).add(Restrictions.eq("house_id", houseId)).list(); But that doesn't work because house_id is not a property, it's a database column. I could just add an sql restriction, but is there a hibernate way of doing this?

    Read the article

  • NHibernate FetchMode

    - by Sandra
    Hi All, I have an object Parent which has a list of Children: class Parent {Id, Name, IList children} class Child {Id, Name} I need to select all parents where there is a condition for their children but I do not want to get duplicate rows (don't want the children details to appear in select list) Here is the code: session.CreateCriteria(typeof(Parent)) .SetFetchMode("children", FetchMode.Select); .CreateCriteria("children").Add(Subqueries.PropertyIn("Id", {1,2,3,4})) .List(); The query adds all proprties of child class to select list which results in duplicate Parents. Is there any way I can select all parents without having the child details in the select list? Thanks

    Read the article

  • fluent nhibernate one to many mapping

    - by Sammy
    I am trying to figure out what I thought was just a simple one to many mapping using fluent Nhibernate. I hoping someone can point me to the right directory to achieve this one to many relations I have an articles table and a categories table Many Articles can only belong to one Category Now my Categores table has 4 Categories and Articles has one article associated with cateory1 here is my setup. using FluentNHibernate.Mapping; using System.Collections; using System.Collections.Generic; namespace FluentMapping { public class Article { public virtual int Id { get; private set; } public virtual string Title { get; set; } public virtual Category Category{get;set;} } public class Category { public virtual int Id { get; private set; } public virtual string Description { get; set; } public virtual IList<Article> Articles { get; set; } public Category() { Articles=new List<Article>(); } public virtual void AddArticle(Article article) { article.Category = this; Articles.Add(article); } public virtual void RemoveArticle(Article article) { Articles.Remove(article); } } public class ArticleMap:ClassMap<Article> { public ArticleMap() { Table("Articles"); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Title); References(x => x.Category).Column("CategoryId").LazyLoad(); } public class CategoryMap:ClassMap<Category> { public CategoryMap() { Table("Categories"); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Description); HasMany(x => x.Articles).KeyColumn("CategoryId").Fetch.Join(); } } } } if I run this test [Fact] public void Can_Get_Categories() { using (var session = SessionManager.Instance.Current) { using (var transaction = session.BeginTransaction()) { var categories = session.CreateCriteria(typeof(Category)) //.CreateCriteria("Articles").Add(NHibernate.Criterion.Restrictions.EqProperty("Category", "Id")) .AddOrder(Order.Asc("Description")) .List<Category>(); } } } I am getting 7 Categories due to Left outer join used by Nhibernate any idea what I am doing wrong in here? Thanks [Solution] After a couple of hours reading nhibernate docs I here is what I came up with var criteria = session.CreateCriteria(typeof (Category)); criteria.AddOrder(Order.Asc("Description")); criteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); var cats1 = criteria.List<Category>(); Using Nhibernate linq provider var linq = session.Linq<Category>(); linq.QueryOptions.RegisterCustomAction(c => c.SetResultTransformer(new DistinctRootEntityResultTransformer())); var cats2 = linq.ToList();

    Read the article

  • NHibernate query with Projections.Cast to DateTime

    - by stiank81
    I'm experimenting with using a string for storing different kind of data types in a database. When I do queries I need to cast the strings to the right type in the query itself. I'm using .Net with NHibernate, and was glad to learn that there exists functionality for this. Consider the simple class: public class Foo { public string Text { get; set; } } I successfully use Projections.Cast to cast to numeric values, e.g. the following query correctly returns all Foos with an interger stored as int - between 1-10. var result = Session.CreateCriteria<Foo>() .Add(Restrictions.Between(Projections.Cast(NHibernateUtil.Int32, Projections.Property("Text")), 1, 10)) .List<Foo>(); Now if I try using this for DateTime I'm not able to make it work no matter what I try. Why?! var date = new DateTime(2010, 5, 21, 11, 30, 00); AddFooToDb(new Foo { Text = date.ToString() } ); // Will add it to the database... var result = Session .CreateCriteria<Foo>() .Add(Restrictions.Eq(Projections.Cast(NHibernateUtil.DateTime, Projections.Property("Text")), date)) .List<Foo>();

    Read the article

1 2 3 4 5 6 7  | Next Page >