Search Results

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

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

  • Hibernate criteria -- alias

    - by Ignace
    Hello, I'm struggling a bit with the concept of alias in Hibernate. My situation is the following: Order @OneToMany(cascade=CascadeType.ALL,mappedBy="m_order") private Set<OrderDetail> m_details; OrderDetail @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="product_id") private Product m_product; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="order_id") private Order m_order; DAO c.createAlias("m_details", "detail").createCriteria("detail.m_product").add(Expression.idEq(productId)); So I want to search every order that contains a product. However, with this query it keeps returning 0 orders and I don't really see what I'm doing wrong. Thanks!

    Read the article

  • NHibernate Criteria - How to filter on combination of properties

    - by DavGarcia
    I needed to filter a list of results using the combination of two properties. A plain SQL statement would look like this: SELECT TOP 10 * FROM Person WHERE FirstName + ' ' + LastName LIKE '%' + @Term + '%' The ICriteria in NHibernate that I ended up using was: ICriteria criteria = Session.CreateCriteria(typeof(Person)); criteria.Add(Expression.Sql( "FirstName + ' ' + LastName LIKE ?", "%" + term + "%", NHibernateUtil.String)); criteria.SetMaxResults(10); It works perfectly, but I'm not sure if it is the ideal solution since I'm still learning about NHibernate's Criteria API. What are the recommended alternatives? Is there something besides Expression.Sql that would perform the same operation? I tried Expression.Like but couldn't figure out how to combine the first and last names. Should I map a FullName property to the formula "FirstName + ' ' + LastName" in the mapping class? Should I create a read only FullName property on the domain object then map it to a column?

    Read the article

  • Hibernate Subquery and DetachedCriteria

    - by dawez
    I have created a DetachedCriteria that is retrieving estates that have the isApproved and isPublished set to true. It is defined in this way: DetachedCriteria activePublishedCriteria = DetachedCriteria.forClass(Estate.class) .add(Restrictions.eq("isApproved", true)) .add(Restrictions.eq("isPublished", true)) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); I would like to reuse this criteria in some of the queries. In this case I would like to replace the isApproved and isPublished restrictions with the DetachedCriteria Criteria criteria = getSession().createCriteria(Estate.class) .createAlias("city", "c") .add(Restrictions.eq("c.id", cityID)) // the following 2 lines should be use the DetachedCriteria .add(Restrictions.eq("isApproved", true)) .add(Restrictions.eq("isPublished", true)) .setProjection(Projections.rowCount()); return (Integer) criteria.list().get(0); Is there a way to do this ? Tried to use .add.Subqueries.geAll(.... But cannot make it work properly. I could not find proper documentation on the Subqueries in Hibernate. Tips are welcomed.

    Read the article

  • NHibernate Projections to retrieve a Collection?

    - by Simon Söderman
    I´m having some trouble retrieving a collection of strings in a projection: say that I have the following classes public class WorkSet { public Guid Id { get; set; } public string Title { get; set; } public ISet<string> PartTitles { get; protected set; } } public class Work { public Guid Id { get; set; } public WorkSet WorkSet { get; set; } //a bunch of other properties } I then have a list of Work ids I want to retrieve WorkSet.Title, WorkSet.PartTitles and Id for. My tought was to do something like this: var works = Session.CreateCriteria<Work>() .Add(Restrictions.In("Id", hitIds)) .CreateAlias("WorkSet", "WorkSet") .SetProjection( Projections.ProjectionList() .Add(Projections.Id()) .Add(Projections.Property("WorkSet.Title")) .Add(Projections.Property("WorkSet.PartTitles"))) .List(); The Id and Title loads up just fine, but the PartTitles returns null. Suggestions please!

    Read the article

  • how to call sql string from nhibernate

    - by frosty
    i have the following method, at the moment it's return the whole sql string. How would i execute the following. using (ITransaction transaction = session.BeginTransaction()) { string sql = string.Format( @"DECLARE @Cost money SET @Cost = -1 select @Cost = MAX(Cost) from item_costings where Item_ID = {0} and {1} >= Qty1 and {1} <= Qty2 RETURN (@Cost)", itemId, quantity); string mystring = session .CreateSQLQuery(sql) .ToString(); transaction.Commit(); return mystring; } // EDIT here is the final version using criteria using (ISession session = NHibernateHelper.OpenSession()) { decimal cost = session .CreateCriteria(typeof (ItemCosting)) .SetProjection(Projections.Max("Cost")) .Add(Restrictions.Eq("ItemId", itemId)) .Add(Restrictions.Le("Qty1", quantity)) .Add(Restrictions.Ge("Qty2", quantity)) .UniqueResult<decimal>(); return cost; }

    Read the article

  • LIKE query for DateTime in NHibernate

    - by Anry
    For a column of type varchar I could write such a query: public IList<Order> GetByName(string orderName) { using (ISession session = NHibernateHelper.OpenSession()) { return session.CreateCriteria<Order>(). Add(Restrictions.Like("Name", string.Format("%{0}%", orderName))). List<Order>(); } } How do I write a similar LIKE-query for a column that has type datetime? public IList<Order> GetByDateTime(DateTime dateTime) { using (ISession session = NHibernateHelper.OpenSession()) { return //LIKE-query } } That is, if the method is passed the date and part-time (eg "25.03.2010 19"), then displays all orders are carried out in this period of time.

    Read the article

  • I need a groovy criteria to get all the elements after i make sort on nullable inner object

    - by user1773876
    I have two domain classes named IpPatient,Ward as shown below. class IpPatient { String ipRegNo Ward ward static constraints = { ward nullable:true ipRegNo nullable:false } } class Ward { String name; static constraints = { name nullable:true } } now i would like to create criteria like def criteria=IpPatient.createCriteria() return criteria.list(max:max , offset:offset) { order("ward.name","asc") createAlias('ward', 'ward', CriteriaSpecification.LEFT_JOIN) } At present IpPatient table has 13 records, where 8 records of IpPatient doesn't have ward because ward can be null. when i sort with wardName i am getting 5 records those contain ward. I need a criteria to get all the elements after i make sort on nullable inner object.

    Read the article

  • How to eager fetch a child collection while joining child collection entities to an association

    - by ShaneC
    Assuming the following fictional layout Dealership has many Cars has a Manufacturer I want to write a query that says get me a Dealership with a Name of X and also get the Cars collection but use a join against the manufacturer when you do so. I think this would require usage of ICriteria. I'm thinking something like this.. var dealershipQuery = Session.CreateCriteria< Dealership>("d") .Add(Restrictions.InsenstiveLike("d.Name", "Foo")) .CreateAlias("d.Cars", "c") .SetFetchMode("d.Cars", FetchMode.Select) .SetFetchMode("c.Manufacturer", FetchMode.Join) .UniqueResult< Dealership>(); But the resulting query looks nothing like I would have expected. I'm starting to think a DetachedCriteria may be required somewhere but I'm not sure. Thoughts?

    Read the article

  • Is it possible to create ICriteria/ICriterion from LINQ or HQL?

    - by adrin
    I am creating a method that can create filter understood by NHibernate (by filter i mean a set of ICriteria object for example) from my abstract filter object. public static IEnumerable<ICriterion> ToNhCriteria(this MyCriteria criteria) { // T4 generated function // lots of result.Add(Expression.Or(Expression.Eq(),Expression.Eq)) expression trees - hard to generate // Is there a way to generate HQL/Linq query here istead? } then i want to do something like session.CreateCriteria<Entity>().Add(myCriteria.ToNhCriteria()) to filter entities. The problem is that using Expression. methods (Expression.Or etc) is quite tedious (the method is generated and i have multiple or statements that have to be joined into an expression somehow). Is there a way to avoid using Expression.Or() and create ICrietrion / ICriteria using LINQ or HQL?

    Read the article

  • How to render Max(Substgring) with Lambda Extensions

    - by caifa
    Hi everybody. I'm using NHibernate with Lambda Extensions. I'd like to know how to nest a Max function with a Substring. The following statement retrieves Max("invoice_id") var ret = session .CreateCriteria<Invoice>() .SetProjection(Projections.Max("invoice_id")) .UniqueResult(); but in my case the field invoice_id is made in this way: 123452010 where 12345 is the invoice number, and 2010 is the current year. So I need to calculate the Max function only over the first 5 digits. How can I do it?

    Read the article

  • Nhibernate setting query time out period for commands and pessimistic locking

    - by Nagesh
    I wish to specify a specific command timeout (or LOCK_TIMEOUT) for an SQL and once this time out is reached an exception (or alert) has to be raised in nHibernate. The following is an example pseudo-code what I have written: using (var session = sessionFactory.OpenSession()) { using (var sqlTrans = session.BeginTransaction()) { ICriteria criteria = session.CreateCriteria(typeof(Foo)); criteria.SetTimeout(5); //Here is the specified command timout, eg: property SqlCommand.CommandTimeout Foo fooObject = session.Load<Foo>(primaryKeyIntegerValue, LockMode.Force); session.SaveOrUpdate(fooObject); sqlTrans.Commit(); } } In SQL server we used to achieve this using the following SQL: BEGIN TRAN SET LOCK_TIMEOUT 500 SELECT * FROM Foo WITH (UPDLOCK, ROWLOCK) WHERE PrimaryKeyID = 1000001 If PrimaryKeyID row would have locked in other transaction the following error message is being shown by SQL Server: Msg 1222, Level 16, State 51, Line 3 Lock request time out period exceeded Similarly I wish to show a lock time out or command time out information using nHibernate. Please help me to achieve this. Thanks in advance for your help.

    Read the article

  • Criteria hibernate

    - by apb
    my code session.createCriteria(Input.class); DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date startDate = (Date)format.parse("2005-01-01 00:00:00"); Date endDate = (Date)format.parse("2005-03-03 00:00:00"); crit.add(Expression.between ("inputDate", new Date(startDate.getTime()), new Date(endDate.getTime()))); This code return a list, but there is no element present in it. i think it doesn't match the condition. Anybody help.

    Read the article

  • Nhibernate Left Outer Join Return First Record of the Join

    - by Touch
    I have the following mappings of which Im trying to bring back 0 - 1 Media Id associated with a Product using a left join (I havnt included my attempt as it confuses the situation) ICriteria productCriteria = Session.CreateCriteria(typeof(Product)); productCriteria .CreateAlias("ProductCategories", "pc", JoinType.InnerJoin) .CreateAlias("pc.ParentCategory", "category") .CreateAlias("category.ParentCategory", "group") .Add(Restrictions.Eq("group.Id", 333)) .SetProjection( Projections.Distinct( Projections.ProjectionList() .Add(Projections.Alias(Projections.Property("Id"), "Id")) .Add(Projections.Alias(Projections.Property("Title"), "Title")) .Add(Projections.Alias(Projections.Property("Price"), "Price")) .Add(Projections.Alias(Projections.Property("media.Id"), "SearchResultMediaId")) // I NEED THIS ) ) .SetResultTransformer(Transformers.AliasToBean<Product>()); IList<Product> products = productCriteria .SetFirstResult(0) .SetMaxResults(10) .List<Product>(); I need the query to populate the SearchResultMediaId with Media.Id, I only want to bring back the first Media in a left outer join, as this is 1 to many association between Product and Media Product is mapped to Media in the following way mapping.HasManyToMany<Media>(x => x.Medias) .Table("ProductMedias") .ParentKeyColumn("ProductId") .ChildKeyColumn("MediaId") .Cascade.AllDeleteOrphan() .LazyLoad() .AsBag(); Any Help would be fantastic.

    Read the article

  • Basic date/time manipulation in NHiberate query

    - by Yann Trevin
    I'm trying to restrict my NHibernate query with some basic date/time manipulation. More specifically, I want to execute the following statement (pseudo-SQL): select * from article where created_on + lifespan >= sysdate with: created_on is mapped to a property of type DateTime. lifespan is mapped to a property of type TimeSpan. sysdate is the current date/time (of the database server or ofthe application host, I don't care) Is there any built-in way to do that by using the Criteria-API or HQL? return session .CreateCriteria<Article>() .Add( ? ) .List<Article>();

    Read the article

  • How do I use Criteria to make a join on a date field (in DB2) based on the year.

    - by HtmlTableGuru
    I have a java.util.Date field in my Object. I would like to use Criteria to select all rows that have a date field with a given year. The SQL would look like the following: SELECT * FROM GAME GM WHERE YEAR(GM.GAME_DATE) = 2010 How can I use Criteria to accomplish this? Thanks in advance. public Collection<Game> getGamesByDate(Date date){ Collection<Game> games = null; try { session.beginTransaction(); Criteria criteria = session.createCriteria(Game.class); criteria .... ... ... games = criteria.list(); } catch (HibernateException e) { e.printStackTrace(); } return games; }

    Read the article

  • Select columns from join table only without requiring a join

    - by Kent Boogaart
    Given these tables: create table Orders ( Id INT IDENTITY NOT NULL, primary key (Id) ) create table Items ( Id INT IDENTITY NOT NULL, primary key (Id) ) create table OrdersItems ( OrderId INT not null, ItemId INT not null, primary key (OrderId, ItemId) ) Is it possible to use HQL/criteria API to contruct a query that results in the following SQL: SELECT [OrderId], [ItemId] FROM [OrdersItems] I've tried both of these approaches: var hqlResults = session .CreateQuery("select order.id, item.id from Order order inner join order.Items item") .List(); var criteriaResults = session .CreateCriteria<Order>() .CreateAlias("Items", "item", NHibernate.SqlCommand.JoinType.None) .SetProjection(Projections.Property("id"), Projections.Property("item.id")) .List(); But both approaches insist on generating a join (or fail because the join isn't present, in using criteria), resulting in SQL such as: select order.Id, item.Id from Orders order inner join OrdersItems ordersItems on order.Id = ordersItems.ArticleId inner join Items item on ordersItems.CategoryId = item.Id Is there any way to have NHibernate generate a query that selects columns only from the join table, without requiring a join?

    Read the article

  • Deleting a Collection with NHibernate Using the Criteria API

    - by lomaxx
    I think I know what the answer to this question is probably going to be, but I thought I'd go ahead and ask it anyway. It appears that within NHibernate if I do something like this: IList<Customer> customers = Session.CreateCriteria(typeof(Customer)) .Add(Restrictions.Eq("Name", "Steve") .List<Customer>(); And I want to then delete that list of customers. From what I can tell the only way to do it is like this: foreach(var customer in customers) { Session.Delete(customer); } But what I'm wondering is if there's any way I can just go: Session.Delete(customers); And delete the entire collection with a single call?

    Read the article

  • Grails: Querying Associations causes groovy.lang.MissingMethodException

    - by Paul
    Hi, I've got an issue with Grails where I have a test app with: class Artist { static constraints = { name() } static hasMany = [albums:Album] String name } class Album { static constraints = { name() } static hasMany = [ tracks : Track ] static belongsTo = [artist: Artist] String name } class Track { static constraints = { name() lyrics(nullable: true) } Lyrics lyrics static belongsTo = [album: Album] String name } The following query (and a more advanced, nested association query) works in the Grails Console but fails with a groovy.lang.MissingMethodException when running the app with 'run-app': def albumCriteria = tunehub.Album.createCriteria() def albumResults = albumCriteria.list { like("name", receivedAlbum) artist { like("name", receivedArtist) } // Fails here maxResults(1) } Stacktrace: groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (tunehub.LyricsService$_getLyrics_closure1_closure2) values: [tunehub.LyricsService$_getLyrics_closure1_closure2@604106] Possible solutions: wait(), any(), wait(long), each(groovy.lang.Closure), any(groovy.lang.Closure), trim() at tunehub.LyricsService$_getLyrics_closure1.doCall(LyricsService.groovy:61) at tunehub.LyricsService$_getLyrics_closure1.doCall(LyricsService.groovy) (...truncated...) Any pointers?

    Read the article

  • Hibernate Criteria: Return different entity type than rooted entity?

    - by Gilean
    I have entities similar to: ProductLine: id, name ProductLineContents: content_id, product_line_id Content: id, text, updated_time What I'd like to do is: for each product line, get the latest content (so if theres two content entries associated to one product line, the latest updated_time is rturned, and if one content item is associated to two product lines, it is returned twice). Something similar to: select content.* from productline inner join productlinecontents inner join content; However I can't seem to figure out how to have Hibernate Criteria return a different entity than the original one it was created with. So if I wanted to start the criteria at the product line with createCriteria(ProductLine.class) along with the proper joins, then it only returns ProductLine objects, but I need Content objects. What's the best way to accomplish this? The actual data model is much more complex and can't be modified

    Read the article

  • NHibernate Criteria Transform Result

    - by isuruceanu
    Hi I have an SecurityGroup entity witch has Memebers and Application properties. Application is a lookup. So securityGroups is in many-to-many relationship with User table and one-to-many with LookupApplciation (FK) Now I want to select all application linked to a specific user. I have follow criteria: public IList<LookupApplication> GetApplicationByUser(User user) { return this.Session.CreateCriteria(typeof(SecurityGroup), "sg") .CreateAlias("Members", "u") .CreateAlias("Application", "al") .Add(Restrictions.Eq("u.Id", user.Id)) .List<LookupApplication>(); } It trows an exception The value "Edi.Advance.Core.Model.Security.SecurityGroup" is not of type "Edi.Advance.Core.Model.Lookups.LookupApplication" and cannot be used in this generic collection. Parameter name: value and it is right. How can I transform the result to IList<LookupApplication>? Thanks

    Read the article

  • fluent nhibernate not caching queries in asp.net mvc

    - by AWC
    I'm using a fluent nhibernate with asp.net mvc and I not seeing anything been cached when making queries against the database. I'm not currently using an L2 cache implementation. Should I see queries being cached without configuring an out of process L2 cache? Mapping are like this: Table("ApplicationCategories"); Not.LazyLoad(); Cache.ReadWrite().IncludeAll(); Id(x => x.Id); Map(x => x.Name).Not.Nullable(); Map(x => x.Description).Nullable(); Example Criteria: return session .CreateCriteria<ApplicationCategory>() .Add(Restrictions.Eq("Name", _name)) .SetCacheable(true); Everytime I make a request for an application cateogry by name it is hitting the database is this expected behaviour?

    Read the article

  • Have parameters in Dao methods to get entities the most efficient way for read-only access

    - by Blankman
    Allot of my use of hibernate, at least for that data that is presented on many parts of the web application, is for read-only purposes. I want to add some parameters to my Dao methods so I can modify the way hibernate pulls the data and how it handles transactions etc. Example usage: Data on the front page of my website is displayed to the users, it is read-only, so I want to avoid any session/entity tracking that hibernate usually does. This is data that is read-only, will not be changed in this transaction, etc. What would be the most performant way to pull the data? (the code below is c#/nhibernate, I'm implementing this in java as I learn it) public IList<Article> GetArticles() { return Session.CreateCriteria(typeof(Article)) // some where cluase }

    Read the article

  • NHibernate - define where condition

    - by t.kehl
    Hi. In my application the user can defines search-conditions. He can choose a column, set an operator (equals, like, greater than, less or equal than, etc.) and give in the value. After the user clicks on a button and the application should do a search on the database with the condition. I use NHibernate and ask me now, what is the efficientest way to do this with NHibernate. Should I create a query with it like (Column=Name, Operator=Like, Value=%John%) var a = session.CreateCriteria<Customer>(); a.Add(Restrictions.Like("Name", "%John%")); return a.List<Customer>(); Or should I do this with HQL: var q = session.CreateQuery("from Customer where " + where); return q.List<Customer >(); Or is there a more bether solution? Thanks for your help. Best Regards, Thomas

    Read the article

  • Need help optimizing a NHibernate criteria query that uses Restrictions.In(..)

    - by Chris F
    I'm trying to figure out if there's a way I can do the following strictly using Criteria and DetachedCriteria via a subquery or some other way that is more optimal. NameGuidDto is nothing more than a lightweight object that has string and Guid properties. public IList<NameGuidDto> GetByManager(Employee manager) { // First, grab all of the Customers where the employee is a backup manager. // Access customers that are primarily managed via manager.ManagedCustomers. // I need this list to pass to Restrictions.In(..) below, but can I do it better? Guid[] customerIds = new Guid[manager.BackedCustomers.Count]; int count = 0; foreach (Customer customer in manager.BackedCustomers) { customerIds[count++] = customer.Id; } ICriteria criteria = Session.CreateCriteria(typeof(Customer)) .Add(Restrictions.Disjunction() .Add(Restrictions.Eq("Manager", manager)) .Add(Restrictions.In("Id", customerIds))) .SetProjection(Projections.ProjectionList() .Add(Projections.Property("Name"), "Name") .Add(Projections.Property("Id"), "Guid")) // Transform results to NameGuidDto criteria.SetResultTransformer(Transformers.AliasToBean(typeof(NameGuidDto))); return criteria.List<NameGuidDto>(); }

    Read the article

  • NHibernate: how to do lookup a specific date

    - by Daoming Yang
    How I can lookup a specific date in Nhibernate? I'm currently using this to lookup one day's order. ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(Order)) .Add(Expression.Between("DateCreated", date.Date.AddDays(-1), date.Date.AddDays(1))) .AddOrder(NHibernate.Criterion.Order.Desc("OrderID")); I tried the following code, but they did bring the data for me. Expression.Eq("DateCreated", date) Expression.Like("DateCreated", date) Note: The pass in date value will be like this 2010-04-03 00:00:00, The actual date value in the database will be like this 2010-03-13 11:17:16.000 Can anyone let me know how to do this? Many thanks.

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >