Search Results

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

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

  • NHibernate: how to do lookup a specific date in Nhibernate

    - 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

  • Hibernate, select by id or unique column

    - by Nican
    I am using hibernate for Java, and I want to be able to select users by id or by name from the database. Nice thing about Hibernate is that it caches the result by id, but I seem to be unable to make it cache by name. static Session openSession = Factory.openSession(); public static User GetUser(int Id) { return (User) openSession.get(User.class, new Integer(Id)); } public static User GetUser( String Name ){ return (User) openSession.createCriteria( User.class ). add( Restrictions.eq("username", Name) ). uniqueResult(); } If I use GetUser(1) many times, hibernate will only show that it executed the first time. But every time I use GetUser("user1"), hibernate shows that it is executing a new query to database. What would be the best way to have the string identifier be cached also?

    Read the article

  • How does hibernate use an empty string for an equality restriction?

    - by Stephen
    I have a column that potentially has some bad data and I can't clean it up, so I need to check for either null or empty string. I'm doing a Hibernate Criteria query so I've got the following that returns incorrectly right now: Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Criteria myCriteria = session.createCriteria(Object); ... myCriteria.add(Restrictions.or(Restrictions.isNull("stringColumn"), Restrictions.eq("stringColumn", ""))); List<Objects> list = myCriteria.list(); I can't get it to properly return the results I'd expect. So as an experiment I changed the second restriction to read: Restrictions.eq("stringColumn", "''") And it started returning the expected results, so is hibernate incorrectly translating my empty string (e.g. "") into a SQL empty string (e.g. ''), or am I just doing this wrong?

    Read the article

  • How to render Max(Substring) 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: 12345.10 where 12345 is the invoice number, and 10 refers to the current year (2010). So I need to calculate the Max function only over the first 5 digits. How can I do it?

    Read the article

  • Hibernate Criteria API: get n random rows

    - by hadrien
    I can't figure out how to fetch n random rows from a criteria instance: Criteria criteria = session.createCriteria(Table.class); criteria.add(Restrictions.eq('fieldVariable', anyValue)); ... Then what? I can't find any doc with Criteria API Does it mean I should use HQL instead? Thanx! EDIT: I get the number of rows by: int max = criteria.setProjecxtion(Projections.rowCount()).uniqueResult(); How do I fetch n random rows with indexes between 0 and max? Thx again!

    Read the article

  • Hibernate criterion Projection alias not being used

    - by sbzoom
    Do Hibernate Projection aliases even work? I could swear it just doesn't. At least, it doesn't do what I would expect it to do. Here is the java: return sessionFactory.getCurrentSession().createCriteria( PersonProgramActivity.class ).setProjection( Projections.projectionList().add( Projections.alias( Projections.sum( "numberOfPoints" ), "number_of_points" ) ).add( Projections.groupProperty( "person.id" ) ) ).setFirstResult( start ).setFetchSize( size ).addOrder( Order.desc( "numberOfPoints" ) ).list(); Here is the SQL that it generates: select sum(this_.number_of_points) as y0_, this_.person_id as y1_ from PERSON_PROGRAM_ACTIVITY this_ group by this_.person_id order by this_.number_of_points desc It doesn't seem to use the alias at all. I would think setting the alias would mean that "sum(this_.number_of_points)" would be aliased as "number_of_points" and not "y0_". Is there some trick I am missing? Thanks.

    Read the article

  • out-of-the-box way to get an idmap from hibernate for a given entity?

    - by Geert-Jan
    Over and over again I notive myself getting a list from hibernate, and the first thing next is put it in an idmap like: List<House> entities = s.createCriteria(House.class).list(); Map<String,House> entitymap = new HashMap<String,House>(); for(TA_entity e:entities){ entitymap.put(e.getId(), e); } Is there a way to get this directly out of hibenerate? afterall Hibernate is familiar with the id.

    Read the article

  • Noob question about hibernate criteria

    - by Dimitri
    Hello, I have a class called User which has 2 properties : login/password. I am trying to authenticate a user in my application using hibernate criteria but my request doesn't work. [EDIT] The returned value is NULL. I have two users in my database for testing. Here is my code : @Override public User authenticate(String login, String password) throws NullPointerException { Session session = this.getSession(); User user = (User) session .createCriteria(User.class) .add( Restrictions.and( Property.forName("login").eq(login), Property.forName("password").eq(password) )).uniqueResult(); if (user == null){ throw new NullPointerException("User not found"); } return user; } Can someone tells me what is wrong with my code? Happy new Year 2011 !!

    Read the article

  • Criteria: search for two different entity classes...

    - by RoCMe
    Hi! I have a "super entity" SuperEntity and three entities ChildEntity1, ..., ChildEntity3 which extends the super class. It's easy to search for all entities in the database, i.e. we could use session.createCriteria(SuperEntity.class); It's no problem to search for one specific entity type, too, just replace the SuperEntity with any of the children to look for entities of that type. But I have a problem when allowing 'multiple choice' for the types. I.e., it could be neccessary to search all entities of type 1 and 2, but not of type 3. A first idea was to create two independent queries and join the results in a final list - but that would destroy the paging which uses offset and limit functionality of the database... Is there a possibility in Criteria to join two different queries in one single result list? Kind regards, RoCMe

    Read the article

  • Non-empty list with null elements returned from Hibernate query

    - by John
    Hi, I'm new to hibernate so not sure if this is an expected behaviour, anyway: Session session = (Session)entityManager.getDelegate(); Criteria criteria = session.createCriteria(myRequest.class); criteria.add(Restrictions.eq("username", username)); criteria.setProjection(Projections.max("accesscount")); List<myRequest> results = criteria.list(); The returned results is a non-empty list with a single null element. I can't think of any reason why it should behave this way, any idea if this is the expected behaviour or have I done something wrong? System is on hibernate/Syabse. Thanks.

    Read the article

  • Hibernate and mssql inner join rowcount

    - by ez2sarang
    I am struggling with Hibernate Criteria. My aim is to create the following request using Hibernate Criteria : select count(*) as y0_ from PInterface this_ inner join Product product2_ on this_.product_id=product2_.id where this_.product_interface_type_id=? Here is my code: @Entity @Table(name = "PInterface") public class PInterface { @Id @GeneratedValue @Column(name = "id", nullable = false, insertable = false, updatable = false) private int id; @Column(name = "product_id") private int productId; @Column(name = "product_interface_type_id") private int type; @ManyToOne(optional=false) @JoinColumn(name = "product_id", referencedColumnName = "id", insertable=false, updatable=false) private Product product; } @Entity @Table(name = "Product") public class Product { @Id @GeneratedValue @Column(name = "id", nullable = false, insertable = false, updatable = false) private int id; private String name; } //Criteria is : Object criteria = sessionFactory.getCurrentSession() .createCriteria(PInterface.class) .add(Restrictions.eq("type", 1)) .setProjection(Projections.rowCount()) .uniqueResult() ; However, the results ... select count(*) as y0_ from PInterface this_ where this_.product_interface_type_id=? Where Inner join? Thank you for help!

    Read the article

  • hibernate criteria list problem [migrated]

    - by user1022676
    I have a user dao @Entity @Table(name="EBIGUSERTIM") public class EbigUser { private String id; private Integer source; private String entryscheme; private String fullName; private String email; private Long flags; private String status; private String createdBy; private Date createdStamp; private String modifiedBy; private Date modifiedStamp; @Id @Column(name="ID") public String getId() { return id; } public void setId(String id) { this.id = id; } @Id @Column(name="SOURCE") public Integer getSource() { return source; } public void setSource(Integer source) { this.source = source; } @Column(name="ENTRYSCHEME") public String getEntryscheme() { return entryscheme; } public void setEntryscheme(String entryscheme) { this.entryscheme = entryscheme; } @Column(name="FULLNAME") public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Column(name="EMAIL") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name="FLAGS") public Long getFlags() { return flags; } public void setFlags(Long flags) { this.flags = flags; } @Column(name="STATUS") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Column(name="CREATEDBY") public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Column(name="CREATEDSTAMP") public Date getCreatedStamp() { return createdStamp; } public void setCreatedStamp(Date createdStamp) { this.createdStamp = createdStamp; } @Column(name="MODIFIEDBY") public String getModifiedBy() { return modifiedBy; } public void setModifiedBy(String modifiedBy) { this.modifiedBy = modifiedBy; } @Column(name="MODIFIEDSTAMP") public Date getModifiedStamp() { return modifiedStamp; } public void setModifiedStamp(Date modifiedStamp) { this.modifiedStamp = modifiedStamp; } i am selecting 2 rows out of the db. The sql works select * from ebigusertim where id='blah'. It returns 2 distinct rows. When i query the data using hibernate, it appears that the object memory is not being allocated for each entry in the list. Thus, i get 2 entries in the list with the same object. Criteria userCriteria = session.createCriteria(EbigUser.class); userCriteria.add(Restrictions.eq("id", id)); userlist = userCriteria.list();

    Read the article

  • Many to Many delete in NHibernate two parents with common association

    - by Joshua Grippo
    I have 3 top level entities in my app: Circuit, Issue, Document Circuits can contain Documents and Issues can contain Documents. When I delete a Circuit, I want it to delete the documents associated with it, unless it is used by something else. I would like this same behavior with Issues. I have it working when the only association is in the same table in the db, but if it is in another table, then it fails due to foreign key constraints. ex 1(This will cascade properly, because there is only a foreign constraint from Circuit to Document) Document1 exists. Circuit1 exists and contains a reference to Document1. If I delete Circuit1 then it deletes Document1 with it. ex 2(This will cascade properly, because there is only a foreign constraint from Circuit to Document.) Document1 exists. Circuit1 exists and contains a reference to Document1. Circuit2 exists and contains a reference to Document1. If I delete Circuit1 then it is deleted, but Document1 is not deleted because Circuit2 exists. If I then delete Circuit2, then Document1 is deleted. ex 3(This will throw an error, because when it deletes the Circuit it sees that there are no other circuits that reference the document so it tries to delete the document. However it should not, because there is an Issue that has a foreign constraint to the document.) Document 1 exists. Circuit1 exists and contains a reference to Document1. Issue1 exists and contains a reference to Document1. If I delete Circuit1, then it fails, because it tries to delete Document1, but Issues1 still has a reference. DB: This think won't let upload an image, so here is the ERD to the DB: http://lh3.ggpht.com/_jZWhe7NXay8/TROJhOd7qlI/AAAAAAAAAGU/rkni3oEANvc/CircuitIssues.gif Model: public class Circuit { public virtual int CircuitID { get; set; } public virtual string CJON { get; set; } public virtual IList<Document> Documents { get; set; } } public class Issue { public virtual int IssueID { get; set; } public virtual string Summary { get; set; } public virtual IList<Model.Document> Documents { get; set; } } public class Document { public virtual int DocumentID { get; set; } public virtual string Data { get; set; } } Mapping Files: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="Model"> <class name="Circuit" table="Circuit"> <id name="CircuitID"> <column name="CircuitID" not-null="true"/> <generator class="identity" /> </id> <property name="CJON" column="CJON" type="string" not-null="true"/> <bag name="Documents" table="CircuitDocument" cascade="save-update,delete-orphan"> <key column="CircuitID"/> <many-to-many class="Document"> <column name="DocumentID" not-null="true"/> </many-to-many> </bag> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="Model"> <class name="Issue" table="Issue"> <id name="IssueID"> <column name="IssueID" not-null="true"/> <generator class="identity" /> </id> <property name="Summary" column="Summary" type="string" not-null="true"/> <bag name="Documents" table="IssueDocument" cascade="save-update,delete-orphan"> <key column="IssueID"/> <many-to-many class="Document"> <column name="DocumentID" not-null="true"/> </many-to-many> </bag> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="Model"> <class name="Document" table="Document"> <id name="DocumentID"> <column name="DocumentID" not-null="true"/> <generator class="identity" /> </id> <property name="Data" column="Data" type="string" not-null="true"/> </class> </hibernate-mapping> Code: using (ISession session = sessionFactory.OpenSession()) { var doc = new Model.Document() { Data = "Doc" }; var circuit = new Model.Circuit() { CJON = "circ" }; circuit.Documents = new List<Model.Document>(new Model.Document[] { doc }); var issue = new Model.Issue() { Summary = "iss" }; issue.Documents = new List<Model.Document>(new Model.Document[] { doc }); session.Save(circuit); session.Save(issue); session.Flush(); } using (ISession session = sessionFactory.OpenSession()) { foreach (var item in session.CreateCriteria<Model.Circuit>().List<Model.Circuit>()) { session.Delete(item); } //this flush fails, because there is a reference to a child document from issue session.Flush(); foreach (var item in session.CreateCriteria<Model.Issue>().List<Model.Issue>()) { session.Delete(item); } session.Flush(); }

    Read the article

  • Hibernate criteria query to match against all child collection elements

    - by Andrew Harrison
    Hi, This question is very similar to link text but the responses were minimal to that question. I have a parent class with a Set of child entities. The child entities are just a wrapper for a string and live in a different table to the parent entity. I want to have a criteria query that returns the parent entities when all the members of the set of child entities return true to a condition. This condition is matching against one of a list of strings. Here's where I am: Criteria c = criteria(); Criteria ands = c.createCriteria("ands"); Disjunction dis = Restrictions.disjunction(); for (String value : values) { dis.add(Restrictions.like("value", "%" + value + "%")); } ands.add(dis); return list(c); "ands" is the set of entities with a "value" field that is a string. "criteria()" creates a criteria for the parent class. "list()" just calls criteria.list(); This is just matching against any of the elements, rather than all. Hope this makes sense. Any help much appreciated.

    Read the article

  • NHibernate L2 Cache - fluent nHibernate configuration

    - by AWC
    I've managed to configure the L2 cache for Get\Load in FHN, but it's not working for queries configured using the ICriteria interface - it doesn't cache the results from these queries. Does anyone know why? The configurations are as follows: ICriteria: return unitOfWork .CurrentSession .CreateCriteria(typeof(Country)) .SetCacheable(true); Entity Mapping: public sealed class CountryMap : ClassMap<Country>, IMap { public CountryMap() { Table("Countries"); Not.LazyLoad(); Cache.ReadWrite().IncludeAll(); Id(x => x.Id); Map(x => x.TwoLetter); Map(x => x.ThreeLetter); Map(x => x.Name); } } And the session factory configuration for the database property: return () => MsSqlConfiguration.MsSql2005 .ConnectionString(BuildConnectionString()) .ShowSql() .Cache(c => c.UseQueryCache() .QueryCacheFactory<StandardQueryCacheFactory>() .ProviderClass(configuration.RepositoryCacheType) .UseMinimalPuts()) .FormatSql() .UseReflectionOptimizer(); Cheers AWC

    Read the article

  • NHibernate. Distinct parent child fetching

    - by Andrew Kalashnikov
    Hello. I've got common NH mapping; <class name="Order, SummaryOrder.Core" table='order'> <id name="Id" unsaved-value="0" type="int"> <column name="id" not-null="true"/> <generator class="native"/> </id> <many-to-one name="Client" class="SummaryOrderClient, SummaryOrder.Core" column="summary_order_client_id" cascade="none"/> <many-to-one name="Provider" class="SummaryOrderClient, SummaryOrder.Core" column="summary_order_provider_id" cascade="none"/> <set name="Items" cascade="all"> <key column="order_id"/> <one-to-many class="OrderItem, Clients.Core" /> </set> </class> Want get list by this criteria ICriteria criteria = NHibernateStateLessSession.CreateCriteria(typeof(SummaryOrder.Core.Domains.Order)); ; criteria.Add(Restrictions.Or (Restrictions.Eq(String.Format("{0}.Id", SummaryOrder.Core.Domains.Order.Properties.Client), idClient), Restrictions.Eq(String.Format("{0}.Id", SummaryOrder.Core.Domains.Order.Properties.Provider), idClient))). SetResultTransformer(new DistinctRootEntityResultTransformer()). SetFetchMode(SummaryOrder.Core.Domains.Order.Properties.Items, FetchMode.Join); return criteria.List<SummaryOrder.Core.Domains.Order>() as List<SummaryOrder.Core.Domains.Order> But I've got duplicates.. When I execute One restriction (without OR) I got distinct collection of orders, but Restriction OR brakes my query. I wanna get distinct(at client yet) collection of orders. What's wrong. Please HELP!

    Read the article

  • Hibernate - query caching/second level cache does not work by value object containing subitems

    - by Zoltan Hamori
    Hi! I have been struggling with the following problem: I have a value object containing different panels. Each panel has a list of fields. Mapping: <class name="com.aviseurope.core.application.RACountryPanels" table="CTRY" schema="DBDEV1A" where="PEARL_CTRY='Y'" lazy="join"> <cache usage="read-only"/> <id name="ctryCode"> <column name="CTRY_CD_ID" sql-type="VARCHAR2(2)" not-null="true"/> </id> <bag name="panelPE" table="RA_COUNTRY_MAPPING" fetch="join" where="MANDATORY_FLAG!='N'"> <key column="COUNTRY_LOCATION_ID"/> <many-to-many class="com.aviseurope.core.application.RAFieldVO" column="RA_FIELD_MID" where="PANEL_ID='PE'"/> </bag> </class> I use the following criteria to get the value object: Session m_Session = HibernateUtil.currentSession(); m_Criteria = m_Session.createCriteria(RACountryPanels.class); m_Criteria.add(Expression.eq("ctryCode", p_Country)); m_Criteria.setCacheable(true); As I see the query cache contains only the main select like select * from CTRY where ctry_cd_id=? Both RACountryPanels and RAFieldVO are second level cached. If I check the 2nd level cache content I can see that it cointains the RAFields and the RACountryPanels as well and I can see the select .. from CTRY where ctry_cd_id=... in query cache region as well. When I call the servlet it seems that it is using the cache, but second time not. If I check the content of the cache using JMX, everything seems to be ok, but when I measure the object access time, it seems that it does not always use the cache. Cheers Zoltan

    Read the article

  • Hibernate ScrollableResults Do Not Return The Whole Set of Results

    - by mlaverd
    Some of the queries we run have 100'000+ results and it takes forever to load them and then send them to the client. So I'm using ScrollableResults to have a paged results feature. But we're topping at roughly 50k results (never exactly the same amount of results). I'm on an Oracle9i database, using the Oracle 10 drivers and Hibernate is configured to use the Oracle9 dialect. I tried with the latest JDBC driver (ojdbc6.jar) and the problem was reproduced. We also followed some advice and added an ordering clause, but the problem was reproduced. Here is a code snippet that illustrates what we do: Criteria crit = sess.createCriteria(ABC.class); crit.add(Restrictions.eq("property", value)); crit.setFetchSize(pageSize); crit.addOrder(Order.asc("property")); ScrollableResults sr = crit.scroll(); ... ... do{ for (Object entry : page) sess.evict(entry); //to avoid having our memory just explode out of proportion page.clear(); for (int i =0 ; i < pageSize && ! metLastRow; i++){ if (resultSet.next()) page.add(sr.get(0)); else metLastRow = true; } metLastRow = metLastRow?metLastRow:sr.isLast(); sendToClient(page); }while(!metLastRow); So, why is it that I get the result set to tell me its at the end when it should be having so much more results?

    Read the article

  • change custom mapping - sharp architecture/ fluent nhibernate

    - by csetzkorn
    I am using the sharp architecture which also deploys FNH. The db schema sql code is generated during the testing like this: [TestFixture] [Category("DB Tests")] public class MappingIntegrationTests { [SetUp] public virtual void SetUp() { string[] mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies(); configuration = NHibernateSession.Init( new SimpleSessionStorage(), mappingAssemblies, new AutoPersistenceModelGenerator().Generate(), "../../../../app/XXX.Web/NHibernate.config"); } [TearDown] public virtual void TearDown() { NHibernateSession.CloseAllSessions(); NHibernateSession.Reset(); } [Test] public void CanConfirmDatabaseMatchesMappings() { var allClassMetadata = NHibernateSession.GetDefaultSessionFactory().GetAllClassMetadata(); foreach (var entry in allClassMetadata) { NHibernateSession.Current.CreateCriteria(entry.Value.GetMappedClass(EntityMode.Poco)) .SetMaxResults(0).List(); } } /// <summary> /// Generates and outputs the database schema SQL to the console /// </summary> [Test] public void CanGenerateDatabaseSchema() { System.IO.TextWriter writeFile = new StreamWriter(@"d:/XXXSqlCreate.sql"); var session = NHibernateSession.GetDefaultSessionFactory().OpenSession(); new SchemaExport(configuration).Execute(true, false, false, session.Connection, writeFile); } private Configuration configuration; } I am trying to use: using FluentNHibernate.Automapping; using xxx.Core; using SharpArch.Data.NHibernate.FluentNHibernate; using FluentNHibernate.Automapping.Alterations; namespace xxx.Data.NHibernateMaps { public class x : IAutoMappingOverride<x> { public void Override(AutoMapping<Tx> mapping) { mapping.Map(x => x.text, "text").CustomSqlType("varchar(max)"); mapping.Map(x => x.url, "url").CustomSqlType("varchar(max)"); } } } To change the standard mapping of strings from NVARCHAR(255) to varchar(max). This is not picked up during the sql schema generation. I also tried: mapping.Map(x = x.text, "text").Length(100000); Any ideas? Thanks. Christian

    Read the article

  • Duplicate Items Using Join in NHibernate Map

    - by Colin Bowern
    I am trying to retrieve the individual detail rows without having to create an object for the parent. I have a map which joins a parent table with the detail to achieve this: Table("UdfTemplate"); Id(x => x.Id, "Template_Id"); Map(x => x.FieldCode, "Field_Code"); Map(x => x.ClientId, "Client_Id"); Join("UdfFields", join => { join.KeyColumn("Template_Id"); join.Map(x => x.Name, "COLUMN_NAME"); join.Map(x => x.Label, "DISPLAY_NAME"); join.Map(x => x.IsRequired, "MANDATORY_FLAG") .CustomType<YesNoType>(); join.Map(x => x.MaxLength, "DATA_LENGTH"); join.Map(x => x.Scale, "DATA_SCALE"); join.Map(x => x.Precision, "DATA_PRECISION"); join.Map(x => x.MinValue, "MIN_VALUE"); join.Map(x => x.MaxValue, "MAX_VALUE"); }); When I run the query in NH using: Session.CreateCriteria(typeof(UserDefinedField)) .Add(Restrictions.Eq("FieldCode", code)).List<UserDefinedField>(); I get back the first row three times as opposed to the three individual rows it should return. Looking at the SQL trace in NH Profiler the query appears to be correct. The problem feels like it is in the mapping but I am unsure how to troubleshoot that process. I am about to turn on logging to see what I can find but I thought I would post here in case someone with experience mapping joins knows where I am going wrong.

    Read the article

  • Applying the Hibernate filter attribute to a Bag with a many-to-many relationship

    - by David P
    Consider the following Hibernate mapping file: <hibernate-mapping ...> <class name="ContentPackage" table="contentPackages"> <id name="Id" column="id" type="int"><generator class="native" /></id> ... <bag name="Clips" table="contentAudVidLinks"> <key column="fk_contentPackageId"></key> <many-to-many class="Clip" column="fk_AudVidId"></many-to-many> <filter name="effectiveDate" condition=":asOfDate BETWEEN startDate and endDate" /> </bag> </class> </hibernate-mapping> When I run the following command: _session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); IList<ContentPackage> items = _session.CreateCriteria(typeof(ContentPackage)) .Add(Restrictions.Eq("Id", id)) .List<ContentPackage>(); The resulting SQL has the WHERE clause on the intermediate mapping table (contentAudVidLinks), rather than the "Clips" table even though I have added the filter attribute to the Bag of Clips. What am I doing wrong?

    Read the article

  • Criteria API - How to get records based on collection count?

    - by Cosmo
    Hello Guys! I have a Question class in ActiveRecord with following fields: [ActiveRecord("`Question`")] public class Question : ObcykaniDb<Question> { private long id; private IList<Question> relatedQuestions; [PrimaryKey("`Id`")] private long Id { get { return this.id; } set { this.id = value; } } [HasAndBelongsToMany(typeof(Question), ColumnRef = "ChildId", ColumnKey = "ParentId", Table = "RelatedQuestion")] private IList<Question> RelatedQuestions { get { return this.relatedQuestions; } set { this.relatedQuestions = value; } } } How do I write a DetachedCriteria query to get all Questions that have at least 5 related questions (count) in the RelatedQuestions collection? For now this gives me strange results: DetachedCriteria dCriteria = DetachedCriteria.For<Question>() .CreateCriteria("RelatedQuestions") .SetProjection(Projections.Count("Id")) .Add(Restrictions.EqProperty(Projections.Id(), "alias.Id")); DetachedCriteria dc = DetachedCriteria.For<Question>("alias").Add(Subqueries.Le(5, dCriteria)); IList<Question> results = Question.FindAll(dc); Any ideas what I'm doing wrong?

    Read the article

  • NHibernate Child items query using Parent Id

    - by thorkia
    So I have a set up similar to this questions: Parent Child Setup Everything works great when saving the parent and the children. However, I seem to have a problem when selecting the children. I can't seem to get all the children with a specific parent. This fails with: NHibernate.QueryException: could not resolve property: ParentEntity_id of: Test.Data.ChildEntity Here is my code: public IEnumerable<ChildEntity> GetByParent(ParentEntity parent) { using (ISession session = OrmHelper.OpenSession()) { return session.CreateCriteria<ChildEntity>().Add(Restrictions.Eq("ParentEntity_id ", parent.Id)).List<ChildEntity>(); } } Any help in building a proper function to get all the items would be appreciated. Oh, I am using Fluent NHibernate to construct the mappings - version 1 RTM and NHibernate 2.1.2 GA If you need more information, let me know. As per you request, my fluent mappings: public ParentEntityMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Code).UniqueKey("ukCode"); HasMany(x => x.ChildEntity).LazyLoad() .Inverse().Cascade.SaveUpdate(); } public ChildEntityMap() { Id(x => x.Id); Map(x => x.Amount); Map(x => x.LogTime); References(x => x.ParentEntity); } That maps to the following 2 tables: CREATE TABLE "ParentEntity" ( Id integer, Name TEXT, Code TEXT, primary key (Id), unique (Code) ) CREATE TABLE "ChildEntity" ( Id integer, Amount NUMERIC, LogTime DATETIME, ParentEntity_id INTEGER, primary key (Id) ) The data store in SQLite.

    Read the article

  • After rich:extendedDataTable sortby,otheractions are not getting executed

    - by user118802
    I have a RichFaces UI which are having sidebar menu and sidebar had 8 links. I am using Seam @DataModel and @Factory and hibernate criteria to populate all the 8 pages. In all the pages i have sortby functionality which is working fine. I am able to get all data in all the 8 pages and I can freely navigate around all the links/xhtmls. But if in one of the xhtmlpages if I do sorting or groupby after that I am unable to navigate to other pages.If I select any other link the same last query which is executed for sorting is getting executed. Is this an issue? or do I need add any configuration. Please help me in solving this issue. Below is the codesnippet one of the 8 xhtml <rich:column sortable="true" sortBy="#{p.regionid}" width="100px" label="Region Id"> <f:facet name="header"> <h:outputText value="Region Id" /> </f:facet> <h:outputText value="#{p.regionid}" /> </rich:column> <rich:column sortable="true" sortBy="#{p.region}" width="100px" label="Region Name"> <f:facet name="header"> <h:outputText value="Region Name" /> </f:facet> <h:outputText value="#{p.region}" /> </rich:column> Sidebar Action @DataModel("regions") private List<CoreRegion> listRegions; @Factory("regions") public void getRegions() { System.out.println("Inside get Regions"); Session userDatabase = HibernateUtil.getSession(); Criteria crit = userDatabase.createCriteria(CoreRegion.class); listRegions = crit.list();

    Read the article

  • Delete throws "deleted object would be re-saved by cascade"

    - by Greg
    I have following model: <class name="Person" table="Person" optimistic-lock="version"> <id name="Id" type="Int32" unsaved-value="0"> <generator class="native" /> </id> <!-- plus some properties here --> </class> <class name="Event" table="Event" optimistic-lock="version"> <id name="Id" type="Int32" unsaved-value="0"> <generator class="native" /> </id> <!-- plus some properties here --> </class> <class name="PersonEventRegistration" table="PersonEventRegistration" optimistic-lock="version"> <id name="Id" type="Int32" unsaved-value="0"> <generator class="native" /> </id> <property name="IsComplete" type="Boolean" not-null="true" /> <property name="RegistrationDate" type="DateTime" not-null="true" /> <many-to-one name="Person" class="Person" column="PersonId" foreign-key="FK_PersonEvent_PersonId" cascade="all-delete-orphan" /> <many-to-one name="Event" class="Event" column="EventId" foreign-key="FK_PersonEvent_EventId" cascade="all-delete-orphan" /> </class> There are no properties pointing to PersonEventRegistration either in Person nor in Event. When I try to delete an entry from PersonEventRegistration, I get the following error: "deleted object would be re-saved by cascade" The problem is, I don't store this object in any other collection - the delete code looks like this: public bool UnregisterFromEvent(Person person, Event entry) { var registrationEntry = this.session .CreateCriteria<PersonEventRegistration>() .Add(Restrictions.Eq("Person", person)) .Add(Restrictions.Eq("Event", entry)) .Add(Restrictions.Eq("IsComplete", false)) .UniqueResult<PersonEventRegistration>(); bool result = false; if (null != registrationEntry) { using (ITransaction tx = this.session.BeginTransaction()) { this.session.Delete(registrationEntry); tx.Commit(); result = true; } } return result; } What am I doing wrong here?

    Read the article

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