Search Results

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

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

  • Hibernate query for multiple items in a collection

    - by aarestad
    I have a data model that looks something like this: public class Item { private List<ItemAttribute> attributes; // other stuff } public class ItemAttribute { private String name; private String value; } (this obviously simplifies away a lot of the extraneous stuff) What I want to do is create a query to ask for all Items with one OR MORE particular attributes, ideally joined with arbitrary ANDs and ORs. Right now I'm keeping it simple and just trying to implement the AND case. In pseudo-SQL (or pseudo-HQL if you would), it would be something like: select all items where attributes contains(ItemAttribute(name="foo1", value="bar1")) AND attributes contains(ItemAttribute(name="foo2", value="bar2")) The examples in the Hibernate docs didn't seem to address this particular use case, but it seems like a fairly common one. The disjunction case would also be useful, especially so I could specify a list of possible values, i.e. where attributes contains(ItemAttribute(name="foo", value="bar1")) OR attributes contains(ItemAttribute(name="foo", value="bar2")) -- etc. Here's an example that works OK for a single attribute: return getSession().createCriteria(Item.class) .createAlias("itemAttributes", "ia") .add(Restrictions.conjunction() .add(Restrictions.eq("ia.name", "foo")) .add(Restrictions.eq("ia.attributeValue", "bar"))) .list(); Learning how to do this would go a long ways towards expanding my understanding of Hibernate's potential. :)

    Read the article

  • How to write a Criteria Query when there's an <any> association

    - by Bevan
    I'm having some trouble constructing the correct Criteria to do a particular query - after an afternoon of consultation with Professor Google, I'm hoping that someone can point me in the right direction. I have two entities of interest: OutputTsDef and NamedAttribute What I'm trying to do is to find all OutputTsDef that have a particular NamedAttribute value. I can write a detached Criteria to find all NamedAttributes that have a given name and value: var attributesCriteria = DetachedCriteria.For<INamedAttribute>() .Add(Expression.Eq("Name", "some name")) .Add(Expression.Eq("Value", "some value")); How do I inject this in to a query for OutputTsDef to restrict the results? var criteria = nHibernateSession.CreateCriteria(typeof(IOutputTsDefEntity)); // What do I write here? var results = criteria.List(); NamedAttribute looks like this - note the use of [Any] as we can have NamedAttributes on many kinds of entity. [AttributeIdentifier("DbKey", Name = "Id.Column", Value = "NamedAttributeID")] [Class(Table = "NamedAttributes")] public class NamedAttribute : BusinessEntity, INamedAttribute { [Any(0, Name = "Entity", MetaType = "System.String", IdType = "System.Int32")] [MetaValue(1, Class = "Sample.OutputTsDef, Sample.Entities", Value = "OTD")] [MetaValue(2, Class = "Sample.OutputTimeSeriesAttributesEntity, Sample.Entities", Value = "OTA")] [Column(3, Name = "OwnerType")] [Column(4, Name = "OwnerKey")] public virtual IBusinessEntity Entity { get; set; } [Property(Column = "Name")] public virtual string Name { get; set; } [Property(Column = "Value")] public virtual string Value { get; set; } ... omitted ... } In regular SQL, I'd just include an extra "where" clause like this: where OutputTsDefId in ( select distinct OwnerKey from NamedAttributes where Name = ? and Value = ? and OwnerType = 'OTD' ) What am I missing? (Question also posted to the NHUsers mailing list - I'll copy any useful information from there, here.)

    Read the article

  • NHibernate complex order query

    - by manu08
    Here's my simplified domain public class Notification { public Guid ID { get; set; } public string Name { get; set; } public IEnumerable<Location> Locations { get; set; } } public class Location { public Guid Id { get; set; } public string Name { get; set; } public decimal Longitude { get; set; } public decimal Latitude { get; set; } } Notifications and Locations have a many-to-many relationship (defined in table LocationsOnNotification). What I'd like to do is query for the nearest 10 Notifications from a given longitude and latitude. I've been trying to use ICriteria, but I'm not sure how to specify the ordering correctly: return Session.CreateCriteria<Notification>() .SetFirstResult(firstIndex) .SetMaxResults(maxResults) .AddOrder(Order.Asc( WHAT GOES HERE! )) .List<Notification>(); What I've been thinking of so far is adding a formula property to the Location mapping; something like this: <property name='Distance' formula='lots of geometry'/> But I'm not sure if that can take in parameters (since I'd need to pass in the user's location to calculate the distance), plus I'm not sure how to specify it in the Order.Asc clause given that it's a property on a many-to-many association class. Any ideas? Or perhaps I should take a different approach altogether. Thanks in advance!

    Read the article

  • NHibernate Criteria question

    - by Jeneatte Jolie
    I have a person object, which can have unlimited number of first names. So the first names are another object. ie person --- name             --- name             --- name What I want to do is write an nhiberate query using which will get me a person who has certain names. so one query might be find someone whose names are alison and jane and philippa, then next query may be one to find someone whose names are alison and jane. I only want to return people who have all the names I'm search on. So far I've got ICriteria criteria = session.CreateCriteria(typeof (Person)); criteria.CreateAlias("Names", "name"); ICriterion expression = null; foreach (string name in namesToFind) { if (expression == null) { expression = Expression.Like("name.Value", "%" + name + "%"); } else { expression = Expression.Or( expression, Expression.Like("name.Value", "%" + name + "%")); } } if (expression != null) criteria.Add(expression); But this is returning every person with ANY of the names I'm searching on, not ALL the names. Can anyone help me out with this? Thanks!

    Read the article

  • Hibernate: Querying objects by attributes of inherited classes

    - by MichaelD
    Hi all, I ran into a problem with Hibernate concerning queries on classes which use inheritance. Basically I've the following class hierarchy: @Entity @Table( name = "recording" ) class Recording { ClassA attributeSet; ... } @Entity @Inheritance( strategy = InheritanceType.JOINED ) @Table( name = "classA" ) public class ClassA { String Id; ... } @Entity @Table( name = "ClassB1" ) @PrimaryKeyJoinColumn( name = "Id" ) public class ClassB1 extends ClassA { private Double P1300; private Double P2000; } @Entity @Table( name = "ClassB2" ) @PrimaryKeyJoinColumn( name = "Id" ) public class ClassB2 extends ClassA { private Double P1300; private Double P3000; } The hierarchy is already given like this and I cannot change it easily. As you can see ClassB1 and ClassB2 inherit from ClassA. Both classes contain a set of attributes which sometimes even have the same names (but I can't move them to ClassA since there are possible more sub-classes which do not use them). The Recording class references one instance of one of this classes. Now my question: What I want to do is selecting all Recording objects in my database which refer to an instance of either ClassB1 or ClassB2 with e.g. the field P1300 == 15.5 (so this could be ClassB1 or ClassB2 instances since the P1300 attribute is declared in both classes). What I tried is something like this: Criteria criteria = session.createCriteria(Recording.class); criteria.add( Restrictions.eq( "attributeSet.P1300", new Double(15.5) ) ); criteria.list(); But since P1300 is not an attribute of ClassA hibernate throws an exception telling me: could not resolve property: P1300 of: ClassA How can I tell hibernate that it should search in all subclasses to find the attribute I want to filter? Thanks MichaelD

    Read the article

  • Get Nhibernate entity and complete it from a web service.

    - by Nour Sabouny
    Hi every one. let's say that i have an order system. each "Order" references a "Customer" Object. when i fill the orders list in Data Access Layer, the customer object should be brought from a Customer Web Service "WCF". so i didn't map the Customer property in the Order mapping class, Id(o => o.OrderID).GeneratedBy.Identity(); //References(o => o.Customer).Not.Nullable().Column("CustomerID"); HasMany(o => o.Details).KeyColumn("OrderID").Cascade.AllDeleteOrphan(); Map(c => c.CustomerID).Not.Nullable(); and asked the nhibernate session to get me the orders list. and tried to loop on every order in the list to fill it's customer property, doe's any body have a good idea for this ???? IList<Order> lst = Session.CreateCriteria<Order>().List<Order>(); foreach (Order order in lst) order.Customer = serviceProxy.GetCustomerByID(order.CustomerID);

    Read the article

  • Using nHibernate to map two different data models to one entity model

    - by Dan
    I have two different data models that map to the same Car entity. I needed to create a second entity called ParkedCar, which is identical to Car (and therefore inherits from it) in order to stop nhibernate complaining that two mappings exists for the same entity. public class Car { protected Car() { IsParked = false; } public virtual int Id { get; set; } public bool IsParked { get; internal set; } } public class ParkedCar : Car { public ParkedCar() { IsParked = true; } //no additional properties to car, merely exists to support mapping and signify the car is parked } The only issue is that when I come to retrieve a Car from the database using the Criteria API like so: SessionProvider.OpenSession.Session.CreateCriteria<Car>() .Add(Restrictions.Eq("Id", 123)) .List<Car>(); The query brings back Car Entities that are from the ParkedCar data model. Its as if nhibernate defaults to the specialised entity. And the mappings are defiantly looking in the right place: <class name="Car" xmlns="urn:nhibernate-mapping-2.2" table="tblCar"> <class name="ParkedCar" xmlns="urn:nhibernate-mapping-2.2" table="tblParkedCar" > How do I stop this?

    Read the article

  • Nhibernate, can i improve my MAPPING or Query

    - by dbones
    take this simple example A staff class which references other instances of the staff class public class Staff { public Staff() { Team = new List<Staff>(); } public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual IList<Staff> Team { get; set; } public virtual Staff Manager { get; set; } } The Fluent Mapping public class StaffMap : ClassMap<Staff> { public StaffMap() { Id(x => x.Id); Map(x => x.Name); References(x => x.Manager).Column("ManagerId"); HasMany(x => x.Team).KeyColumn("ManagerId").Inverse(); } } Now I want to run a query, which will load all the Staff and eager load the manager and Team members. This is what I came up with IList<Staff> resutls = session.CreateCriteria<Staff>() .SetFetchMode("Team", FetchMode.Eager) .SetResultTransformer(Transformers.DistinctRootEntity) .List<Staff>(); however the SQL (does what i want) has duplicate columns, 2 team2_.ManagerId and 2 team2_.Id SELECT this_.Id as Id0_1_, this_.Name as Name0_1_, this_.ManagerId as ManagerId0_1_, team2_.ManagerId as ManagerId3_, team2_.Id as Id3_, team2_.Id as Id0_0_, team2_.Name as Name0_0_, team2_.ManagerId as ManagerId0_0_ FROM [SelfRef].[dbo].[Staff] this_ left outer join [SelfRef].[dbo].[Staff] team2_ on this_.Id=team2_.ManagerId The question is, should this be happening? did i do something wrong in the query or map? or is it a feature of the HHib im using (which is Version 2.1.0.4000)? many thanks in advance

    Read the article

  • NHibernate Criteria Find by Id

    - by user315648
    Hello, I have 2 entities: public class Authority : Entity { [NotNull, NotEmpty] public virtual string Name { get; set; } [NotNull] public virtual AuthorityType Type { get; set; } } public class AuthorityType : Entity { [NotNull, NotEmpty] public virtual string Name { get; set; } public virtual string Description { get; set; } } Now I wish to find all authorities from repository by type. I tried doing it like this: public IList<Authority> GetAuthoritiesByType(int id) { ICriteria criteria = Session.CreateCriteria(typeof (Authority)); criteria.Add(Restrictions.Eq("Type.Id", id)); IList<Authority> authorities = criteria.List<Authority>(); return authorities; } However, I'm getting an error that something is wrong with the SQL ("could not execute query". The innerexception is following: {"Invalid column name 'TypeFk'.\r\nInvalid column name 'TypeFk'."} Any advice ? Any other approach ? Best wishes, Andrew

    Read the article

  • Ordering the results of a Hibernate Criteria query by using information of the child entities of the

    - by pkainulainen
    I have got two entities Person and Book. Only one instance of a specific book is stored to the system (When a book is added, application checks if that book is already found before adding a new row to the database). Relevant source code of the entities is can be found below: @Entity @Table(name="persons") @SequenceGenerator(name="id_sequence", sequenceName="hibernate_sequence") public class Person extends BaseModel { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_sequence") private Long id = null; @ManyToMany(targetEntity=Book.class) @JoinTable(name="persons_books", joinColumns = @JoinColumn( name="person_id"), inverseJoinColumns = @JoinColumn( name="book_id")) private List<Book> ownedBooks = new ArrayList<Book>(); } @Entity @Table(name="books") @SequenceGenerator(name="id_sequence", sequenceName="hibernate_sequence") public class Book extends BaseModel { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_sequence") private Long id = null; @Column(name="name") private String name = null; } My problem is that I want to find persons, which are owning some of the books owned by a specific persons. The returned list of persons should be ordered by using following logic: The person owning most of the same books should be at the first of the list, second person of the the list does not own as many books as the first person, but more than the third person. The code of the method performing this query is added below: @Override public List<Person> searchPersonsWithSimilarBooks(Long[] bookIds) { Criteria similarPersonCriteria = this.getSession().createCriteria(Person.class); similarPersonCriteria.add(Restrictions.in("ownedBooks.id", bookIds)); //How to set the ordering? similarPersonCriteria.addOrder(null); return similarPersonCriteria.list(); } My question is that can this be done by using Hibernate? And if so, how it can be done? I know I could implement a Comparator, but I would prefer using Hibernate to solve this problem.

    Read the article

  • data is not inserting in my db table [closed]

    - by Sarojit Chakraborty
    Please see my below(SubjectDetailsDao.java) code of addZoneToDb method. My debugger is nicely running upto ** session.getTransaction().commit();** code. but after that debugger stops,I do not know why it stops after that line? .And because of this i am unable to insert my data into my database table. I don't know what to do.Why it is not inserting my data into my database table? Plz help me for this. H Now i am getting this Error: Struts Problem Report Struts has detected an unhandled exception: Messages: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; File: org/hibernate/validator/event/ValidateEventListener.java Line number: 172 Stacktraces java.lang.reflect.InvocationTargetException sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) java.lang.Thread.run(Thread.java:722) java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172) org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:156) org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:49) org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234) org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) v.esoft.dao.SubjectdetailsDAO.SubjectdetailsDAO.addZoneToDb(SubjectdetailsDAO.java:185) v.esoft.actions.LoginAction.datatobeinsert(LoginAction.java:53) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) ............................... ............................... SubjectDetailsDao.java(I have problem in addZoneToDb) package v.esoft.dao.SubjectdetailsDAO; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import com.opensymphony.xwork2.ActionSupport; import v.esoft.connection.HibernateUtil; import v.esoft.pojos.Subjectdetails; public class SubjectdetailsDAO extends ActionSupport { private static Session session = null; private static SessionFactory sessionFactory = null; static Transaction transaction = null; private String currentDate; SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd"); private java.util.Date currentdate; public SubjectdetailsDAO() { sessionFactory = HibernateUtil.getSessionFactory(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); currentdate = new java.util.Date(); currentDate = formatter.format(currentdate); } public List getAllCustomTempleteRoutinesForGrid() { List list = new ArrayList(); try { session = sessionFactory.openSession(); list = session.createCriteria(Subjectdetails.class).addOrder(Order.desc("subjectId")).list(); } catch (Exception e) { System.out.println("Exepetion in getAllCustomTempleteRoutines" + e); } finally { try { // HibernateUtil.shutdown(); } catch (Exception e) { System.out.println("Exception In getExerciseListByLoginId Resource closing :" + e); } } return list; } //**showing list on grid private static List<Subjectdetails> custLst=new ArrayList<Subjectdetails>(); static int total=50; static { SubjectdetailsDAO cts = new SubjectdetailsDAO(); Iterator iterator1 = cts.getAllCustomTempleteRoutinesForGrid().iterator(); while (iterator1.hasNext()) { Subjectdetails get = (Subjectdetails) iterator1.next(); custLst.add(get); } } /****************************************update Routines List by WorkId************************************/ public int updatesub(Subjectdetails s) { int updated = 0; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); Query query = session.createQuery("UPDATE Subjectdetails set subjectName = :routineName1 WHERE subjectId=:workoutId1"); query.setString("routineName1", s.getSubjectName()); query.setInteger("workoutId1", s.getSubjectId()); updated = query.executeUpdate(); if (updated != 0) { } transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { System.out.println("Exception in addUser() Rollback :" + e1); } } } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In addUser Resource closing :" + e); } } return updated; } /****************************************update Routines List by WorkId************************************/ public int addSubjectt(Subjectdetails s) { int inserted = 0; Subjectdetails ss=new Subjectdetails(); try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); ss. setSubjectName(s.getSubjectName()); session.save(ss); System.out.println("Successfully data insert in database"); inserted++; if (inserted != 0) { } transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { System.out.println("Exception in addUser() Rollback :" + e1); } } } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In addUser Resource closing :" + e); } } return inserted; } /******************************************Get all Routines List by LoginID************************************/ public List getSubjects() { List list = null; try { session = sessionFactory.openSession(); list = session.createCriteria(Subjectdetails.class).list(); } catch (Exception e) { System.out.println("Exception in getRoutineList() :" + e); } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In getUserList Resource closing :" + e); } } return list; } //---\ public int addZoneToDb(String countryName, Integer loginId) { int inserted = 0; try { System.out.println("---------1--------"); Session session = HibernateUtil.getSessionFactory().openSession(); System.out.println("---------2------session--"+session); session.beginTransaction(); Subjectdetails country = new Subjectdetails(countryName, loginId, currentdate, loginId, currentdate); System.out.println("---------2------country--"+country); session.save(country); System.out.println("-------after save--"); inserted++; session.getTransaction().commit(); System.out.println("-------after commits--"); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { } } } finally { try { } catch (Exception e) { } } return inserted; } //-- public int nextId() { return total++; } public List<Subjectdetails> buildList() { return custLst; } public static int count() { return custLst.size(); } public static List<Subjectdetails> find(int o,int q) { return custLst.subList(o, q); } public void save(Subjectdetails c) { custLst.add(c); } public static Subjectdetails findById(Integer id) { try { for(Subjectdetails c:custLst) { if(c.getSubjectId()==id) { return c; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void update(Subjectdetails c) { for(Subjectdetails x:custLst) { if(x.getSubjectId()==c.getSubjectId()) { x.setSubjectName(c.getSubjectName()); } } } public void delete(Subjectdetails c) { custLst.remove(c); } public static List<Subjectdetails> findNotById(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()!=id) { temp.add(c); } } return temp; } public static List<Subjectdetails> findLesserAsId(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()<=id) { temp.add(c); } } return temp; } public static List<Subjectdetails> findGreaterAsId(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()>=id) { temp.add(c); } } return temp; } } Subjectdetails.hbm.xml <hibernate-mapping> <class name="vb.sofware.pojos.Subjectdetails" table="subjectdetails" catalog="vbsoftware"> <id name="subjectId" type="int"> <column name="subject_id" /> <generator class="increment"/> </id> <property name="subjectName" type="string"> <column name="subject_name" length="150" /> </property> <property name="createrId" type="java.lang.Integer"> <column name="creater_id" /> </property> <property name="createdDate" type="timestamp"> <column name="created_date" length="19" /> </property> <property name="updateId" type="java.lang.Integer"> <column name="update_id" /> </property> <property name="updatedDate" type="timestamp"> <column name="updated_date" length="19" /> </property> </class> </hibernate-mapping> My POJO - Subjectdetails.java package v.esoft.pojos; // Generated Oct 6, 2012 1:58:21 PM by Hibernate Tools 3.4.0.CR1 import java.util.Date; /** * Subjectdetails generated by hbm2java */ public class Subjectdetails implements java.io.Serializable { private int subjectId; private String subjectName; private Integer createrId; private Date createdDate; private Integer updateId; private Date updatedDate; public Subjectdetails( String subjectName) { //this.subjectId = subjectId; this.subjectName = subjectName; } public Subjectdetails() { } public Subjectdetails(int subjectId) { this.subjectId = subjectId; } public Subjectdetails(int subjectId, String subjectName, Integer createrId, Date createdDate, Integer updateId, Date updatedDate) { this.subjectId = subjectId; this.subjectName = subjectName; this.createrId = createrId; this.createdDate = createdDate; this.updateId = updateId; this.updatedDate = updatedDate; } public Subjectdetails( String subjectName, Integer createrId, Date createdDate, Integer updateId, Date updatedDate) { this.subjectName = subjectName; this.createrId = createrId; this.createdDate = createdDate; this.updateId = updateId; this.updatedDate = updatedDate; } public int getSubjectId() { return this.subjectId; } public void setSubjectId(int subjectId) { this.subjectId = subjectId; } public String getSubjectName() { return this.subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public Integer getCreaterId() { return this.createrId; } public void setCreaterId(Integer createrId) { this.createrId = createrId; } public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Integer getUpdateId() { return this.updateId; } public void setUpdateId(Integer updateId) { this.updateId = updateId; } public Date getUpdatedDate() { return this.updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } } And my Sql query is CREATE TABLE IF NOT EXISTS `subjectdetails` ( `subject_id` int(3) NOT NULL, `subject_name` varchar(150) DEFAULT NULL, `creater_id` int(5) DEFAULT NULL, `created_date` datetime DEFAULT NULL, `update_id` int(5) DEFAULT NULL, `updated_date` datetime DEFAULT NULL, PRIMARY KEY (`subject_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    Read the article

  • Inheritance - Could not initialize proxy - no Session.

    - by Ninu
    hello....i'm newbie developer.... i really need help at now... i just get started with Nhibernate thing at .Net... when i learn Inheritance and try it...it makes me confusing...why i get error like this : Initializing[AP.Core.Domain.AccountPayable.APInvoice#API03/04/2010/001]-Could not initialize proxy - no Session. this is my xml : <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="AP.Core.Domain.AccountPayable.APAdjustment, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="APAdjustment"> <id name="AdjustmentNumber" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="AdjustmentNumber" length="17" /> <generator class="assigned" /> </id> <property name="Amount" type="System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Amount" /> </property> <property name="TransactionDate" type="System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="TransactionDate" /> </property> <many-to-one class="AP.Core.Domain.AccountPayable.APInvoice, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="proxy" name="PurchaseInvoice"> <column name="PurchaseInvoice_id" not-null="true" /> </many-to-one> <joined-subclass name="AP.Core.Domain.AccountPayable.APCreditAdjustment, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="true" table="APCreditAdjustment"> <key> <column name="APAdjustment_id" /> </key> </joined-subclass> </class> </hibernate-mapping> and this is inheritance Class : Parent Class -- public class APAdjustment { #region :FIELD private string adjustmentNumber; private decimal amount; private DateTime transactionDate; private APInvoice purchaseInvoice; Child Class -- public class APCreditAdjustment : APAdjustment { public APCreditAdjustment(){ and this my Data access : public IList<APAdjustment> GetByNameAll() { ICriteria criteria = Nhibernatesession.CreateCriteria(typeof(APAdjustment)); return criteria.List<APAdjustment>() ; } My Problem is : when i load data with gridview ...it works...but i change the property to autogenerate="true" ...i missing "PurchaseInvoice" field...and i change to bind manually,and it works..when i edit that gridview ...i get this error... Initializing[AP.Core.Domain.AccountPayable.APInvoice#API03/04/2010/001]-Could not initialize proxy - no Session so then i change my xml ...lazy="no-proxy" ...it still work...but when edit again ...i get error again ..and i do "Comment out the selected lines" to my association "Many-to-one"...i really works it..but that's not i want... CAN ANYBODY HELP ME...??Plizz...:( Note : I almost forget it ,i use fluent hibernate to generate to database.From fluent Hibernate ..i put *.xml file ...so i'm work to xml NHibernate...not fluent hibernate thing...:)

    Read the article

  • Fluent NHibernate Self Referencing Many To Many

    - by Jeremy
    I have an entity called Books that can have a list of more books called RelatedBooks. The abbreviated Book entity looks something likes this: public class Book { public virtual long Id { get; private set; } public virtual IList<Book> RelatedBooks { get; set; } } Here is what the mapping looks like for this relationship HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks") .Cascade.SaveUpdate(); Here is a sample of the data that is then generated in the RelatedBooks table: BookId RelatedBookId 1 2 1 3 The problem happens when I Try to delete a book. If I delete the book that has an ID of 1, everything works ok and the RelatedBooks table has the two corresponding records removed. However if I try to delete the book with an ID of 3, I get the error "The DELETE statement conflicted with the REFERENCE constraint "FK5B54405174BAB605". The conflict occurred in database "Test", table "dbo.RelatedBooks", column 'RelatedBookId'". Basically what is happening is the Book cannot be deleted because the record in the RelatedBooks table that has a RelatedBookId of 3 is never deleted. How do I get that record to be deleted when I delete a book? EDIT After changing the Cascade from SaveUpdate() to All(), the same problem still exists if I try to delete the Book with an ID of 3. Also with Cascade set to All(), if delete the Book with and ID of 1, then all 3 books (ID's: 1, 2 and 3) are deleted so that won't work either. Looking at the SQL that is executed when the Book.Delete() method is called when I delete the Book with an ID of 3, it looks like the SELECT statement is looking at the wrong column (which I assume means that the SQL DELETE statment would make the same mistake, therefore never removing that record). Here is the SQL for the RelatedBook SELECT relatedboo0_.BookId as BookId3_ , relatedboo0_.RelatedBookId as RelatedB2_3_ , book1_.Id as Id14_0_ FROM RelatedBooks relatedboo0_ left outer join [Book] book1_ on relatedboo0_.RelatedBookId=book1_.Id WHERE relatedboo0_.BookId=3 The WHERE statment should look something like this for thie particular case: WHERE relatedboo0_.RelatedBookId = 3 SOLUTION Here is what I had to do to get it working for all cases Mapping: HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks"); Code: var book = currentSession.Get<Book>(bookId); if (book != null) { //Remove all of the Related Books book.RelatedBooks.Clear(); //Get all other books that have this book as a related book var booksWithRelated = currentSession.CreateCriteria<Book>() .CreateAlias("RelatedBooks", "br") .Add(Restrictions.Eq("br.Id", book.Id)) .List<Book>(); //Remove this book as a Related Book for all other Books foreach (var tempBook in booksWithRelated) { tempBook.RelatedBooks.Remove(book); tempBook.Save(); } //Delete the book book.Delete(); }

    Read the article

  • org.hibernate.TransientObjectException during Criteria.list()

    - by rancidfishbreath
    I have seen posts all over the internet that talk about how to fix the TransientObjectExceptions during save/update/delete but I am having this problem when calling list on my Criteria. I have two objects A and B. A has a field named b which is of type B. In my mapping b is mapped as a many-to-one. This all runs in a larger persistence framework (the framework is kind of like Core Data) and so I don't use any cascades in my hibernate mappings since cascades are handled at a higher level. This is the interesting code surrounding my criteria: A a = new A(); B b = new B(); a.setB(b); session.save("B", b); // Actually handled by the higher level session.save("A", a); // framework, this is just for clarity // transaction committed and session closed ... // new session opened Criteria criteria = session.createCriteria(A.class); criteria.add(Restrictions.eq("b", b)); List<?> objects = criteria.list(); Basically I am looking for all objects of type A such that A.b equals a particular instance of b (I actually tried restructuring a query so that I was passing in the id of b just to make sure that b wasn't causing me problems). Here is the stack trace that occurs when I call criteria.list(): org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: B at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:244) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:449) at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:141) at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1769) at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1740) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1612) at org.hibernate.loader.Loader.doQuery(Loader.java:717) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270) at org.hibernate.loader.Loader.doList(Loader.java:2294) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2172) at org.hibernate.loader.Loader.list(Loader.java:2167) at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1706) at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347) Here is my mapping: <class entity-name="A" lazy="false"> <tuplizer entity-mode="dynamic-map" class="MyTuplizer" /> <id type="long" column="id"> <generator class="native" /> </id> <many-to-one name="b" entity-name="B" column="b_id" lazy="false" /> </class> <class entity-name="B" lazy="false"> <tuplizer entity-mode="dynamic-map" class="MyTuplizer" /> <id type="long" column="id"> <generator class="native" /> </id> </class> Can anyone help me figure out why I would be getting a TransientObjectException during a fetch? Preferably I would like to find a solution that does not rely on cascades since they tend to mask problems that occur in the higher level framework.

    Read the article

  • NHibernate criteria query question

    - by Chris
    I have 3 related objects (Entry, GamePlay, Prize) and I'm trying to find the best way to query them for what I need using NHibernate. When a request comes in, I need to query the Entries table for a matching entry and, if found, get a) the latest game play along with the first game play that has a prize attached. Prize is a child of GamePlay and each Entry object has a GamePlays property (IList). Currently, I'm working on a method that pulls the matching Entry and eagerly loads all game plays and associated prizes, but it seems wasteful to load all game plays just to find the latest one and any that contain a prize. Right now, my query looks like this: var entry = session.CreateCriteria<Entry>() .Add(Restrictions.Eq("Phone", phone)) .AddOrder(Order.Desc("Created")) .SetFetchMode("GamePlays", FetchMode.Join) .SetMaxResults(1).UniqueResult<Entry>(); Two problems with this: It loads all game plays up front. With 365 days of data, this could easily balloon to 300k of data per query. It doesn't eagerly load the Prize child property for each game. Therefore, my code that loops through the GamePlays list looking for a non-null Prize must make a call to load each Prize property I check. I'm not an nhibernate expert, but I know there has to be a better way to do this. Ideally, I'd like to do the following (pseudocode): entry = findEntry(phoneNumber) lastPlay = getLatestGamePlay(Entry) firstWinningPlay = getFirstWinningGamePlay(Entry) The end result of course is that I have the entry details, the latest game play, and the first winning game play. The catch is that I want to do this in as few database calls as possible, otherwise I'd just execute 3 separate queries. The object definitions look like: public class Entry { public Guid Id {get;set;} public string Phone {get;set;} public IList<GamePlay> GamePlays {get;set;} // ... other properties } public class GamePlay { public Guid Id {get;set;} public Entry Entry {get;set;} public Prize Prize {get;set;} // ... other properties } public class Prize { public Guid Id {get;set;} // ... other properties } The proper NHibernate mappings are in place, so I just need help figuring out how to set up the criteria query (not looking for HQL, don't use it).

    Read the article

  • Working with Hibernate Queries

    - by jschoen
    I am new to hibernate queries, and trying to get a grasp on how everything works. I am using Hibernate 3 with Netbeans 6.5. I have a basic project set up and have been playing around with how to do everything. I started with essentially a search query. Where the user can enter values into one or more fields. The table would be Person with the columns first_name, middle_name, last_name for the sake of the example. The first way I found was to have a method that took firstName, middleName, and lastName as parameters: Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); String query = "from Person where (first_name = :firstName or :firstName is null) "+ "and (middle_name = :middleName or :middleName is null) " "and (last_name = :lastname or :lastName is null)"; Query q = session.createQuery(query); q.setString("firstName", firstName); q.setString("middleName", middleName); q.setString("lastName", lastName); List<Person> results = (List<Person>) q.list(); This did not sit well with me, since it seemed like I should not have to write that much, and well, that I was doing it wrong. So I kept digging and found another way: Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); Criteria crit = session.createCriteria(Person.class); if (firstName != null) { crit.add(Expression.ge("firstName", firstName); } if (middleName != null) { crit.add(Expression.ge("middleName", middleName); } if (lastName != null) { crit.add(Expression.ge("lastName", lastName); } List<Person> results = (List<Person>) crit.list(); So what I am trying to figure out is which way is the preferred way for this type of query? Criteria or Query? Why? I am guessing that Criteria is the preferred way and you should only use Query when you need to write it by hand for performance type reasons. Am I close?

    Read the article

  • How to do a proper search with nhibernate

    - by Denis Rosca
    Hello everyone, i'm working on a small project that is supposed to allow basic searches of the database. Currently i'm using nhibernate for the database interaction. In the database i have 2 tables: Person and Address. The Person table has a many-to-one relationship with Address. The code i've come up with for doing searches is: public IList<T> GetByParameterList(List<QueryParameter> parameterList) { if (parameterList == null) { return GetAll(); } using (ISession session = NHibernateHelper.OpenSession()) { ICriteria criteria = session.CreateCriteria<T>(); foreach (QueryParameter param in parameterList) { switch (param.Constraint) { case ConstraintType.Less: criteria.Add(Expression.Lt(param.ParameterName, param.ParameterValue)); break; case ConstraintType.More: criteria.Add(Expression.Gt(param.ParameterName, param.ParameterValue)); break; case ConstraintType.LessOrEqual: criteria.Add(Expression.Le(param.ParameterName, param.ParameterValue)); break; case ConstraintType.EqualOrMore: criteria.Add(Expression.Ge(param.ParameterName, param.ParameterValue)); break; case ConstraintType.Equals: criteria.Add(Expression.Eq(param.ParameterName, param.ParameterValue)); break; case ConstraintType.Like: criteria.Add(Expression.Like(param.ParameterName, param.ParameterValue)); break; } } try { IList<T> result = criteria.List<T>(); return result; } catch { //TODO: Implement some exception handling throw; } } } The query parameter is a helper object that i use to create criterias and send it to the dal, it looks like this: public class QueryParameter { public QueryParameter(string ParameterName, Object ParameterValue, ConstraintType constraintType) { this.ParameterName = ParameterName; this.ParameterValue = ParameterValue; this.Constraint = constraintType; } public string ParameterName { get; set; } public Object ParameterValue { get; set; } public ConstraintType Constraint { get; set; } } Now this works well if i'm doing a search like FirstName = "John" , but not when i try to give a parameter like Street = "Some Street". It seems that nhibernate is looking for a street column in the Person table but not in the Address table. Any idea on how should i change my code for so i could do a proper search? Tips? Maybe some alternatives? Disclaimer: i'm kind of a noob so please be gentle ;) Thanks, Denis.

    Read the article

  • How can I provide values for non-grouped columns in NHibernate?

    - by ddc0660
    I have a criteria query: Session.CreateCriteria<Sell043Report>() .SetProjection(.ProjectionList() .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.location)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.agent)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.cusip)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.SettlementDate)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.salePrice)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.foreignFx)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.batchNumber)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.origSaleDate)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.planName)) .Add(LambdaProjection.GroupProperty<Sell043Report>(r => r.dateTimeAdded)) .Add(LambdaProjection.Sum<Sell043Report>(r => r.shares)) .Add(LambdaProjection.Sum<Sell043Report>(r => r.netMoney)) .Add(LambdaProjection.Sum<Sell043Report>(r => r.grossMoney)) .Add(LambdaProjection.Sum<Sell043Report>(r => r.taxWithheld)) .Add(LambdaProjection.Sum<Sell043Report>(r => r.fees))) .List<Sell043Report>(); that generates the following SQL: SELECT this_.location as y0_, this_.agent as y1_, this_.cusip as y2_, this_.SettlementDate as y3_, this_.salePrice as y4_, this_.foreignFx as y5_, this_.batchNumber as y6_, this_.origSaleDate as y7_, this_.planName as y8_, this_.dateTimeAdded as y9_, sum(this_.shares) as y10_, sum(this_.netMoney) as y11_, sum(this_.grossMoney) as y12_, sum(this_.taxWithheld) as y13_, sum(this_.fees) as y14_ FROM MIS_IPS_Sell043Report this_ GROUP BY this_.location, this_.agent, this_.cusip, this_.SettlementDate, this_.salePrice, this_.foreignFx, this_.batchNumber, this_.origSaleDate, this_.planName, this_.dateTimeAdded however the Sell043Report table has additional columns than those listed in the SELECT statement so I'm receiving this error when attempting to get a list of Sell043Reports: System.ArgumentException: The value "System.Object[]" is not of type "xyz.Sell043Report" and cannot be used in this generic collection. I suspect the problem is that I'm not selecting all of the columns for a Sell043Report and so it doesn't know how to map the dataset to the object. I'm trying to achieve something like this: SELECT this_.location as y0_, this_.agent as y1_, this_.cusip as y2_, this_.SettlementDate as y3_, this_.salePrice as y4_, this_.foreignFx as y5_, this_.batchNumber as y6_, this_.origSaleDate as y7_, this_.planName as y8_, this_.dateTimeAdded as y9_, sum(this_.shares) as y10_, sum(this_.netMoney) as y11_, sum(this_.grossMoney) as y12_, sum(this_.taxWithheld) as y13_, sum(this_.fees) as y14_, '' as Address1, '' as Address2 // etc FROM MIS_IPS_Sell043Report this_ GROUP BY this_.location, this_.agent, this_.cusip, this_.SettlementDate, this_.salePrice, this_.foreignFx, this_.batchNumber, this_.origSaleDate, this_.planName, this_.dateTimeAdded How can I do this using NHibernate?

    Read the article

  • NHibernateUnitOfWork + ASP.Net MVC

    - by Felipe
    Hi Guys, hows it going? I'm in my first time with DDD, so I'm begginer! So, let's take it's very simple :D I developed an application using asp.net mvc 2 , ddd and nhibernate. I have a domain model in a class library, my repositories in another class library, and an asp.net mvc 2 application. My Repository base class, I have a construct that I inject and dependency (my unique ISessionFactory object started in global.asax), the code is: public class Repository<T> : IRepository<T> where T : Entidade { protected ISessionFactory SessionFactory { get; private set; } protected ISession Session { get { return SessionFactory.GetCurrentSession(); } } protected Repository(ISessionFactory sessionFactory) { SessionFactory = sessionFactory; } public void Save(T entity) { Session.SaveOrUpdate(entity); } public void Delete(T entity) { Session.Delete(entity); } public T Get(long key) { return Session.Get<T>(key); } public IList<T> FindAll() { return Session.CreateCriteria(typeof(T)).SetCacheable(true).List<T>(); } } And After I have the spefic repositories, like this: public class DocumentRepository : Repository<Domain.Document>, IDocumentRepository { // constructor public DocumentRepository (ISessionFactory sessionFactory) : base(sessionFactory) { } public IList<Domain.Document> GetByType(int idType) { var result = Session.CreateQuery("from Document d where d.Type.Id = :IdType") .SetParameter("IdType", idType) .List<Domain.Document>(); return result; } } there is not control of transaction in this code, and it's working fine, but, I would like to make something to control this repositories in my controller of asp.net mvc, something simple, like this: using (var tx = /* what can I put here ? */) { try { _repositoryA.Save(objA); _repositoryB.Save(objB); _repositotyC.Delete(objC); /* ... others tasks ... */ tx.Commit(); } catch { tx.RollBack(); } } I've heared about NHibernateUnitOfWork, but i don't know :(, How Can I configure NHibernateUnitOfWork to work with my repositories ? Should I change the my simple repository ? Sugestions are welcome! So, thanks if somebody read to here! If can help me, I appretiate! PS: Sorry for my english! bye =D

    Read the article

  • hibernate annotation- extending base class - values are not being set - strange error

    - by gt_ebuddy
    I was following Hibernate: Use a Base Class to Map Common Fields and openjpa inheritance tutorial to put common columns like ID, lastModifiedDate etc in base table. My annotated mappings are as follow : BaseTable : @MappedSuperclass public abstract class BaseTable { @Id @GeneratedValue @Column(name = "id") private int id; @Column(name = "lastmodifieddate") private Date lastModifiedDate; ... Person table - @Entity @Table(name = "Person ") public class Person extends BaseTable implements Serializable{ ... Create statement generated : create table Person (id integer not null auto_increment, lastmodifieddate datetime, name varchar(255), primary key (id)) ; After I save a Person object to db, Person p = new Person(); p.setName("Test"); p.setLastModifiedDate(new Date()); .. getSession().save(p); I am setting the date field but, it is saving the record with generated ID and LastModifiedDate = null, and Name="Test". Insert Statement : insert into Person (lastmodifieddate, name) values (?, ?) binding parameter [1] as [TIMESTAMP] - <null> binding parameter [2] as [VARCHAR] - Test Read by ID query : When I do hibernate query (get By ID) as below, It reads person by given ID. Criteria c = getSession().createCriteria(Person.class); c.add(Restrictions.eq("id", id)); Person person= c.list().get(0); //person has generated ID, LastModifiedDate is null select query select person0_.id as id8_, person0_.lastmodifieddate as lastmodi8_, person0_.name as person8_ from Person person0_ - Found [1] as column [id8_] - Found [null] as column [lastmodi8_] - Found [Test] as column [person8_] ReadAll query : //read all Query query = getSession().createQuery("from " + Person.class.getName()); List allPersons=query.list(); Corresponding SQL for read all select query select person0_.id as id8_, person0_.lastmodifieddate as lastmodi8_, person0_.name as person8_ from Person person0_ - Found [1] as column [id8_] - Found [null] as column [lastmodi8_] - Found [Test] as column [person8_] - Found [2] as column [id8_] - Found [null] as column [lastmodi8_] - Found [Test2] as column [person8_] But when I print out the list in console, its being more weird. it is selecting List of Person object with ID fields = all 0 (why all 0 ?) LastModifiedDate = null Name fields have valid values I don't know whats wrong here. Could you please look at it? FYI, My Hibernate-core version : 4.1.2, MySQL Connector version : 5.1.9 . In summary, There are two issues here Why I am getting All ID Fields =0 when using read all? Why the LastModifiedDate is not being inserted?

    Read the article

  • nhibernate says 'mapping exception was unhandled' no persister for: MyNH.Domain.User

    - by mrblah
    Hi, I am using nHibernate and fluent. I created a User.cs: public class User { public virtual int Id { get; set; } public virtual string Username { get; set; } public virtual string Password { get; set; } public virtual string Email { get; set; } public virtual DateTime DateCreated { get; set; } public virtual DateTime DateModified { get; set; } } Then in my mappinds folder: public class UserMapping : ClassMap<User> { public UserMapping() { WithTable("ay_users"); Not.LazyLoad(); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Username).Not.Nullable().WithLengthOf(256); Map(x => x.Password).Not.Nullable().WithLengthOf(256); Map(x => x.Email).Not.Nullable().WithLengthOf(100); Map(x => x.DateCreated).Not.Nullable(); Map(x => x.DateModified).Not.Nullable(); } } Using the repository pattern for the nhibernate blog: public class UserRepository : Repository<User> { } public class Repository<T> : IRepository<T> { public ISession Session { get { return SessionProvider.GetSession(); } } public T GetById(int id) { return Session.Get<T>(id); } public ICollection<T> FindAll() { return Session.CreateCriteria(typeof(T)).List<T>(); } public void Add(T product) { Session.Save(product); } public void Remove(T product) { Session.Delete(product); } } public interface IRepository<T> { T GetById(int id); ICollection<T> FindAll(); void Add(T entity); void Remove(T entity); } public class SessionProvider { private static Configuration configuration; private static ISessionFactory sessionFactory; public static Configuration Configuration { get { if (configuration == null) { configuration = new Configuration(); configuration.Configure(); configuration.AddAssembly(typeof(User).Assembly); } return configuration; } } public static ISessionFactory SessionFactory { get { if (sessionFactory == null) sessionFactory = Configuration.BuildSessionFactory(); return sessionFactory; } } private SessionProvider() { } public static ISession GetSession() { return SessionFactory.OpenSession(); } } My config: <?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string">Server=.\SqlExpress;Initial Catalog=TestNH;User Id=dev;Password=123</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration> I created a console application to test the output: static void Main(string[] args) { Console.WriteLine("starting..."); UserRepository users = new UserRepository(); User user = users.GetById(1); Console.WriteLine("user is null: " + (null == user)); if(null != user) Console.WriteLine("User: " + user.Username); Console.WriteLine("ending..."); Console.ReadLine(); } Error: nhibernate says 'mapping exception was unhandled' no persister for: MyNH.Domain.User What could be the issue, I did do the mapping?

    Read the article

  • LINQ Generic Query with inherited base class?

    - by sah302
    I am trying to write some generic LINQ queries for my entities, but am having issue doing the more complex things. Right now I am using an EntityDao class that has all my generics and each of my object class Daos (such as Accomplishments Dao) inherit it, am example: using LCFVB.ObjectsNS; using LCFVB.EntityNS; namespace AccomplishmentNS { public class AccomplishmentDao : EntityDao<Accomplishment>{} } Now my entityDao has the following code: using LCFVB.ObjectsNS; using LCFVB.LinqDataContextNS; namespace EntityNS { public abstract class EntityDao<ImplementationType> where ImplementationType : Entity { public ImplementationType getOneByValueOfProperty(string getProperty, object getValue) { ImplementationType entity = null; if (getProperty != null && getValue != null) { //Nhibernate Example: //ImplementationType entity = default(ImplementationType); //entity = Me.session.CreateCriteria(Of ImplementationType)().Add(Expression.Eq(getProperty, getValue)).UniqueResult(Of InterfaceType)() LCFDataContext lcfdatacontext = new LCFDataContext(); //Generic LINQ Query Here lcfdatacontext.GetTable<ImplementationType>(); lcfdatacontext.SubmitChanges(); lcfdatacontext.Dispose(); } return entity; } public bool insertRow(ImplementationType entity) { if (entity != null) { //Nhibernate Example: //Me.session.Save(entity, entity.Id) //Me.session.Flush() LCFDataContext lcfdatacontext = new LCFDataContext(); //Generic LINQ Query Here lcfdatacontext.GetTable<ImplementationType>().InsertOnSubmit(entity); lcfdatacontext.SubmitChanges(); lcfdatacontext.Dispose(); return true; } else { return false; } } } }             I have gotten the insertRow function working, however I am not even sure how to go about doing getOnebyValueOfProperty, the closest thing I could find on this site was: http://stackoverflow.com/questions/2157560/generic-linq-to-sql-query How can I pass in the column name and the value I am checking against generically using my current set-up? It seems like from that link it's impossible since using a where predicate because entity class doesn't know what any of the properties are until I pass them in. Lastly, I need some way of setting a new object as the return type set to the implementation type, in nhibernate (what I am trying to convert from) it was simply this line that did it: ImplentationType entity = default(ImplentationType); However default is an nhibernate command, how would I do this for LINQ? EDIT: getOne doesn't seem to work even when just going off the base class (this is a partial class of the auto generated LINQ classes). I even removed the generics. I tried: namespace ObjectsNS { public partial class Accomplishment { public Accomplishment getOneByWhereClause(Expression<Action<Accomplishment, bool>> singleOrDefaultClause) { Accomplishment entity = new Accomplishment(); if (singleOrDefaultClause != null) { LCFDataContext lcfdatacontext = new LCFDataContext(); //Generic LINQ Query Here entity = lcfdatacontext.Accomplishments.SingleOrDefault(singleOrDefaultClause); lcfdatacontext.Dispose(); } return entity; } } } Get the following error: Error 1 Overload resolution failed because no accessible 'SingleOrDefault' can be called with these arguments: Extension method 'Public Function SingleOrDefault(predicate As System.Linq.Expressions.Expression(Of System.Func(Of Accomplishment, Boolean))) As Accomplishment' defined in 'System.Linq.Queryable': Value of type 'System.Action(Of System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean))' cannot be converted to 'System.Linq.Expressions.Expression(Of System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean))'. Extension method 'Public Function SingleOrDefault(predicate As System.Func(Of Accomplishment, Boolean)) As Accomplishment' defined in 'System.Linq.Enumerable': Value of type 'System.Action(Of System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean))' cannot be converted to 'System.Func(Of LCFVB.ObjectsNS.Accomplishment, Boolean)'. 14 LCF Okay no problem I changed: public Accomplishment getOneByWhereClause(Expression<Action<Accomplishment, bool>> singleOrDefaultClause) to: public Accomplishment getOneByWhereClause(Expression<Func<Accomplishment, bool>> singleOrDefaultClause) Error goes away. Alright, but now when I try to call the method via: Accomplishment accomplishment = new Accomplishment(); var result = accomplishment.getOneByWhereClause(x=>x.Id = 4) It doesn't work it says x is not declared. I also tried getOne, and various other Expression =(

    Read the article

  • NHibernate Mapping and Querying Where Tables are Related But No Foreign Key Constraint

    - by IanT8
    I'm fairly new to NHibernate, and I need to ask a couple of questions relating to a very frequent scenario. The following simplified example illustrates the problem. I have two tables named Equipment and Users. Users is a set of system administrators. Equipment is a set of machinery. Tables: Users table has UserId int and LoginName nvarchar(64). Equipment table has EquipId int, EquipType nvarchar(64), UpdatedBy int. Behavior: System administrators can make changes to Equipment, and when they do, the UpdatedBy field of Equipment is "normally" set to their User Id. Users can be deleted at any time. New Equipment items have an UpdatedBy value of null. There's no foreign key constraint on Equipment.UpdatedBy which means: Equipment.UpdatedBy can be null. Equipment.UpdatedBy value can be = existing User.UserId value Equipment.UpdatedBy value can be = non-existent User.UserId value To find Equipment and who last updated the Equipment, I might query like this: select E.EquipId, E.EquipName, U.UserId, U.LoginName from Equipment E left outer join Users U on. E.UpdatedBy = U.UserId Simple enough. So how to do that in NHibernate? My mappings might be as follows: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Data" assembly="Data"> <class name="User" table="Users"> <id name="Id" column="UserId" unsaved-value="0"> <generator class="native" /> </id> <property name="LoginName" unique="true" not-null="true" /> </class> <class name="Equipment" table="Equipment"> <id name="Id" column="EquipId" type="int" unsaved-value="0"> <generator class="native" /> </id> <property name="EquipType" /> <many-to-one name="UpdatedBy" class="User" column="UpdatedBy" /> </class> </hibernate-mapping> So how do I get all items of equipment and who updated them? using (ISession session = sessionManager.OpenSession()) { List<Data.Equipment> equipList = session .CreateCriteria<Data.Equipment>() // Do I need to SetFetchmode or specify that I // want to join onto User here? If so how? .List<Data.Equipment>(); foreach (Data.Equipment item in equipList) { Debug.WriteLine("\nEquip Id: " + item.Id); Debug.WriteLine("Equip Type: " + item.EquipType); if (item.UpdatedBy.Country != null) Debug.WriteLine("Updated By: " + item.UpdatedBy.LoginName); else Debug.WriteLine("Updated by: Nobody"); } } When Equipment.UpdatedBy = 3 and there is no Users.UserId = 3, the above fail I also have a feeling that the generated SQL is a select all from Equipment followed by many select columns from Users where UserId = n whereas I'd expected NHibernate to left join as per my plain ordinary SQL and do one hit. If I can tell NHibernate to do the query in one hit, how do I do that? Time is of the essence on my project, so any help you could provide is gratefully received. If you're speculating about how NHibernate might work in this scenario, please say you're not absolutely sure. Many thanks.

    Read the article

  • Need help to properly remove duplicates in NHibernate

    - by Michael D. Kirkpatrick
    Here is the problem I am having. I have a database with over 100 records in it. I am paging through the data to get 9 results at a time. When I added a check to see if items are active, it caused the results to start doubling up. A little background: "Product" is the actual product line "ProductSkus" are the actual products that exist in the product line When there is more then 1 ProductSku within Product, it causes a duplicate entry to be returned. See the NHibernate Query below: result = this.Session.CreateCriteria<Model.Product>() .Add(Expression.Eq("IsActive", true)) .AddOrder(new Order("Name", true)) .SetFirstResult(indexNumber).SetMaxResults(maxNumber) // This part of the query duplicates the products .CreateAlias("ProductSkus", "ProdSkus", JoinType.InnerJoin) .Add(Expression.Eq("ProdSkus.IsActive", true)) .CreateAlias("ProductToSubcategory", "ProdToSubcat") .CreateAlias("ProdToSubcat.ProductSubcategory", "ProdSubcat") .Add(Expression.Eq("ProdSubcat.ID", subCatId)) // This part takes out the duplicate products - Removes too many items... // Turns out that with .SetFirstResult(indexNumber).SetMaxResults(maxNumber) // it gets 9 records back then the duplicates are removed. // Example: // Total Records over 100 // Max = 9 // 4 Duplicates removed // Yields 5 records when there should be 9 // Why??? This line is ran in NHibernate on the data after it has been extracted from the SQL server. .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer()) .List<Model.Product>(); I added the DistinctRootEntityResultTransformer to clean up the duplicates. The problem is that it pulls 9 records back that contains duplicates. DistinctRootEntityResultTransformer then cleans up the duplicates in the 9 records. I am basically needing a distinct statement to be ran on the SQL server to begin with. However, distinct on SQL is not going to work since NHibernate by default wants to add every field from every table in the select part of the statement. I am only using the fields that belong to the root table to begin with (Model.Product). If I can tell NHibernate to not add the fields to the joined tables into the select part of the statement along with adding Distinct, it would work. I use NHibernare Profiler to see the actual query: SELECT top 9 this_.ID as ID351_3_, this_.Name as Name351_3_, this_.Description as Descript3_351_3_, this_.IsActive as IsActive351_3_, this_.ManufacturerID as Manufact5_351_3_, prodskus1_.ID as ID373_0_, prodskus1_.Description as Descript2_373_0_, prodskus1_.PartNumber as PartNumber373_0_, prodskus1_.Price as Price373_0_, prodskus1_.IsKit as IsKit373_0_, prodskus1_.IsActive as IsActive373_0_, prodskus1_.IsFeaturedProduct as IsFeatur7_373_0_, prodskus1_.DateAdded as DateAdded373_0_, prodskus1_.Weight as Weight373_0_, prodskus1_.TimesViewed as TimesVi10_373_0_, prodskus1_.TimesOrdered as TimesOr11_373_0_, prodskus1_.ProductID as ProductID373_0_, prodskus1_.OverSizedBoxID as OverSiz13_373_0_, prodtosubc2_.ID as ID362_1_, prodtosubc2_.MasterSubcategory as MasterSu2_362_1_, prodtosubc2_.ProductID as ProductID362_1_, prodtosubc2_.ProductSubcategoryID as ProductS4_362_1_, prodsubcat3_.ID as ID352_2_, prodsubcat3_.Name as Name352_2_, prodsubcat3_.ProductCategoryID as ProductC3_352_2_, prodsubcat3_.ImageID as ImageID352_2_, prodsubcat3_.TriggerShow as TriggerS5_352_2_ FROM Product this_ inner join ProductSku prodskus1_ on this_.ID = prodskus1_.ProductID and (prodskus1_.IsActive = 1) inner join ProductToSubcategory prodtosubc2_ on this_.ID = prodtosubc2_.ProductID inner join ProductSubcategory prodsubcat3_ on prodtosubc2_.ProductSubcategoryID = prodsubcat3_.ID WHERE this_.IsActive = 1 /* @p0 */ and prodskus1_.IsActive = 1 /* @p1 */ and prodsubcat3_.ID = 3 /* @p2 */ ORDER BY this_.Name asc If I hand modify the query and run it directly on the SQL server I get the result set I want (I removed all the extra fields in the select section and added DISTINCT): SELECT DISTINCT top 9 this_.ID as ID351_3_, this_.Name as Name351_3_, this_.Description as Descript3_351_3_, this_.IsActive as IsActive351_3_, this_.ManufacturerID as Manufact5_351_3_, FROM Product this_ inner join ProductSku prodskus1_ on this_.ID = prodskus1_.ProductID and (prodskus1_.IsActive = 1) inner join ProductToSubcategory prodtosubc2_ on this_.ID = prodtosubc2_.ProductID inner join ProductSubcategory prodsubcat3_ on prodtosubc2_.ProductSubcategoryID = prodsubcat3_.ID WHERE this_.IsActive = 1 /* @p0 */ and prodskus1_.IsActive = 1 /* @p1 */ and prodsubcat3_.ID = 3 /* @p2 */ ORDER BY this_.Name asc The big question I now must ask is... What must I change in the NHibernate Query to ultimately get the exact same result? Thanks in advance.

    Read the article

  • NHibernate, and odd "Session is Closed!" errors

    - by Sekhat
    Note: Now that I've typed this out, I have to apologize for the super long question, however, I think all the code and information presented here is in some way relevant. Okay, I'm getting odd "Session Is Closed" errors, at random points in my ASP.NET webforms application. Today, however, it's finally happening in the same place over and over again. I am near certain that nothing is disposing or closing the session in my code, as the bits of code that use are well contained away from all other code as you'll see below. I'm also using ninject as my IOC, which may / may not be important. Okay, so, First my SessionFactoryProvider and SessionProvider classes: SessionFactoryProvider public class SessionFactoryProvider : IDisposable { ISessionFactory sessionFactory; public ISessionFactory GetSessionFactory() { if (sessionFactory == null) sessionFactory = Fluently.Configure() .Database( MsSqlConfiguration.MsSql2005.ConnectionString(p => p.FromConnectionStringWithKey("QoiSqlConnection"))) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<JobMapping>()) .BuildSessionFactory(); return sessionFactory; } public void Dispose() { if (sessionFactory != null) sessionFactory.Dispose(); } } SessionProvider public class SessionProvider : IDisposable { ISessionFactory sessionFactory; ISession session; public SessionProvider(SessionFactoryProvider sessionFactoryProvider) { this.sessionFactory = sessionFactoryProvider.GetSessionFactory(); } public ISession GetCurrentSession() { if (session == null) session = sessionFactory.OpenSession(); return session; } public void Dispose() { if (session != null) { session.Dispose(); } } } These two classes are wired up with Ninject as so: NHibernateModule public class NHibernateModule : StandardModule { public override void Load() { Bind<SessionFactoryProvider>().ToSelf().Using<SingletonBehavior>(); Bind<SessionProvider>().ToSelf().Using<OnePerRequestBehavior>(); } } and as far as I can tell work as expected. Now my BaseDao<T> class: BaseDao public class BaseDao<T> : IDao<T> where T : EntityBase { private SessionProvider sessionManager; protected ISession session { get { return sessionManager.GetCurrentSession(); } } public BaseDao(SessionProvider sessionManager) { this.sessionManager = sessionManager; } public T GetBy(int id) { return session.Get<T>(id); } public void Save(T item) { using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(item); transaction.Commit(); } } public void Delete(T item) { using (var transaction = session.BeginTransaction()) { session.Delete(item); transaction.Commit(); } } public IList<T> GetAll() { return session.CreateCriteria<T>().List<T>(); } public IQueryable<T> Query() { return session.Linq<T>(); } } Which is bound in Ninject like so: DaoModule public class DaoModule : StandardModule { public override void Load() { Bind(typeof(IDao<>)).To(typeof(BaseDao<>)) .Using<OnePerRequestBehavior>(); } } Now the web request that is causing this is when I'm saving an object, it didn't occur till I made some model changes today, however the changes to my model has not changed the data access code in anyway. Though it changed a few NHibernate mappings (I can post these too if anyone is interested) From as far as I can tell, BaseDao<SomeClass>.Get is called then BaseDao<SomeOtherClass>.Get is called then BaseDao<TypeImTryingToSave>.Save is called. it's the third call at the line in Save() using (var transaction = session.BeginTransaction()) that fails with "Session is Closed!" or rather the exception: Session is closed! Object name: 'ISession'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ObjectDisposedException: Session is closed! Object name: 'ISession'. And indeed following through on the Debugger shows the third time the session is requested from the SessionProvider it is indeed closed and not connected. I have verified that Dispose on my SessionFactoryProvider and on my SessionProvider are called at the end of the request and not before the Save call is made on my Dao. So now I'm a little stuck. A few things pop to mind. Am I doing anything obviously wrong? Does NHibernate ever close sessions without me asking to? Any workarounds or ideas on what I might do? Thanks in advance

    Read the article

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