Search Results

Search found 226 results on 10 pages for 'hql'.

Page 7/10 | < Previous Page | 3 4 5 6 7 8 9 10  | Next Page >

  • Hibernate Discriminator sort

    - by mrvreddy
    I am trying to sort the records when queried on discriminator column. I am doing a HQL/ Criteria query for retrieving all the records. Here is my class: abstract class A { ... } @DiscriminatorValue("B") class B extends A { } @DiscriminatorValue("C") class C extends A { } When I return the records, I want it sorted on the discriminator value.

    Read the article

  • How to solve following issue in java?

    - by lakshmi
    Im getting following error while running the query. org.hibernate.hql.ast.QuerySyntaxException: expecting CLOSE, found 'LIMIT' near line 1, column 194 [from com.claystone.db.Gpsdata where id.mobileunitid = '2090818044' and gpsdate in (select id.gpsdate from com.claystone.db.Gpsdata where id.mobileunitid = '2090818044' ORDER BY id.gpsdate DESC LIMIT 1 ) and gpsstatus='true'] This is my Query.Please give the suggession what is the mistake in this query? data=session.createQuery[from com.claystone.db.Gpsdata where id.mobileunitid = '2090818044' and gpsdate in (select id.gpsdate from com.claystone.db.Gpsdata where id.mobileunitid = '2090818044' ORDER BY id.gpsdate DESC LIMIT 1 ) and gpsstatus='true']

    Read the article

  • Select latest group by in nhibernate

    - by Kendrick
    I have Canine and CanineHandler objects in my application. The CanineHandler object has a PersonID (which references a completely different database), an EffectiveDate (which specifies when a handler started with the canine), and a FK reference to the Canine (CanineID). Given a specific PersonID, I want to find all canines they're currently responsible for. The (simplified) query I'd use in SQL would be: Select Canine.* from Canine inner join CanineHandler on(CanineHandler.CanineID=Canine.CanineID) inner join (select CanineID,Max(EffectiveDate) MaxEffectiveDate from caninehandler group by CanineID) as CurrentHandler on(CurrentHandler.CanineID=CanineHandler.CanineID and CurrentHandler.MaxEffectiveDate=CanineHandler.EffectiveDate) where CanineHandler.HandlerPersonID=@PersonID Edit: Added mapping files below: <class name="CanineHandler" table="CanineHandler" schema="dbo"> <id name="CanineHandlerID" type="Int32"> <generator class="identity" /> </id> <property name="EffectiveDate" type="DateTime" precision="16" not-null="true" /> <property name="HandlerPersonID" type="Int64" precision="19" not-null="true" /> <many-to-one name="Canine" class="Canine" column="CanineID" not-null="true" access="field.camelcase-underscore" /> </class> <class name="Canine" table="Canine"> <id name="CanineID" type="Int32"> <generator class="identity" /> </id> <property name="Name" type="String" length="64" not-null="true" /> ... <set name="CanineHandlers" table="CanineHandler" inverse="true" order-by="EffectiveDate desc" cascade="save-update" access="field.camelcase-underscore"> <key column="CanineID" /> <one-to-many class="CanineHandler" /> </set> <property name="IsDeleted" type="Boolean" not-null="true" /> </class> I haven't tried yet, but I'm guessing I could do this in HQL. I haven't had to write anything in HQL yet, so I'll have to tackle that eventually anyway, but my question is whether/how I can do this sub-query with the criterion/subqueries objects. I got as far as creating the following detached criteria: DetachedCriteria effectiveHandlers = DetachedCriteria.For<Canine>() .SetProjection(Projections.ProjectionList() .Add(Projections.Max("EffectiveDate"),"MaxEffectiveDate") .Add(Projections.GroupProperty("CanineID"),"handledCanineID") ); but I can't figure out how to do the inner join. If I do this: Session.CreateCriteria<Canine>() .CreateCriteria("CanineHandler", "handler", NHibernate.SqlCommand.JoinType.InnerJoin) .List<Canine>(); I get an error "could not resolve property: CanineHandler of: OPS.CanineApp.Model.Canine". Obviously I'm missing something(s) but from the documentation I got the impression that should return a list of Canines that have handlers (possibly with duplicates). Until I can make this work, adding the subquery isn't going to work... I've found similar questions, such as http://stackoverflow.com/questions/747382/only-get-latest-results-using-nhibernate but none of the answers really seem to apply with the kind of direct result I'm looking for. Any help or suggestion is greatly appreciated.

    Read the article

  • Restrict the class of an association in a Hibernate Criteria query

    - by D Lawson
    I have an object, 'Response' that has a property called 'submitter'. Submitters can be one of several different classes including Student, Teacher, etc... I would like to be able to execute a criteria query where I select only responses submitted by teachers - so this means putting a class restriction on an associated entity. Any ideas on this? I'd like to stay away from direct SQL or HQL.

    Read the article

  • How to test if a table is empty, using Hibernate

    - by landon9720
    Using Hibernate, what is the most efficient way to determine if a table is empty or non-empty? In other words, does the table have 0, or more than 0 rows? I could execute the HQL query select count(*) from tablename and then check if result is 0 or non-0, but this isn't optimal as I would be asking the database for more detail than I really need.

    Read the article

  • How to write native SQL queries in Hibernate without hardcoding table names and fields?

    - by serg555
    Sometimes you have to write some of your queries in native SQL rather than hibernate HQL. Is there a nice way to avoid hardcoding table names and fields and get this data from existing mapping? For example instead of: String sql = "select user_name from tbl_user where user_id = :id"; something like: String sql = "select " + Hibernate.getFieldName("user.name") + " from " + Hibernate.getTableName(User.class) + " where " + Hibernate.getFieldName("user.id") + " = :id";

    Read the article

  • Big Data – Learning Basics of Big Data in 21 Days – Bookmark

    - by Pinal Dave
    Earlier this month I had a great time to write Bascis of Big Data series. This series received great response and lots of good comments I have received, I am going to follow up this basics series with further in-depth series in near future. Here is the consolidated blog post where you can find all the 21 days blog posts together. Bookmark this page for future reference. Big Data – Beginning Big Data – Day 1 of 21 Big Data – What is Big Data – 3 Vs of Big Data – Volume, Velocity and Variety – Day 2 of 21 Big Data – Evolution of Big Data – Day 3 of 21 Big Data – Basics of Big Data Architecture – Day 4 of 21 Big Data – Buzz Words: What is NoSQL – Day 5 of 21 Big Data – Buzz Words: What is Hadoop – Day 6 of 21 Big Data – Buzz Words: What is MapReduce – Day 7 of 21 Big Data – Buzz Words: What is HDFS – Day 8 of 21 Big Data – Buzz Words: Importance of Relational Database in Big Data World – Day 9 of 21 Big Data – Buzz Words: What is NewSQL – Day 10 of 21 Big Data – Role of Cloud Computing in Big Data – Day 11 of 21 Big Data – Operational Databases Supporting Big Data – RDBMS and NoSQL – Day 12 of 21 Big Data – Operational Databases Supporting Big Data – Key-Value Pair Databases and Document Databases – Day 13 of 21 Big Data – Operational Databases Supporting Big Data – Columnar, Graph and Spatial Database – Day 14 of 21 Big Data – Data Mining with Hive – What is Hive? – What is HiveQL (HQL)? – Day 15 of 21 Big Data – Interacting with Hadoop – What is PIG? – What is PIG Latin? – Day 16 of 21 Big Data – Interacting with Hadoop – What is Sqoop? – What is Zookeeper? – Day 17 of 21 Big Data – Basics of Big Data Analytics – Day 18 of 21 Big Data – How to become a Data Scientist and Learn Data Science? – Day 19 of 21 Big Data – Various Learning Resources – How to Start with Big Data? – Day 20 of 21 Big Data – Final Wrap and What Next – Day 21 of 21 Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Big Data, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL

    Read the article

  • How to design highly scalable web services in Java?

    - by Kshitiz Sharma
    I am creating some Web Services that would have 2000 concurrent users. The services are offered for free and are hence expected to get a large user base. In the future it may be required to scale up to 50,000 users. There are already a few other questions that address the issue like - Building highly scalable web services However my requirements differ from the question above. For example - My application does not have a user interface, so images, CSS, javascript are not an issue. It is in Java so suggestions like using HipHop to translate PHP to native code are useless. Hence I decided to ask my question separately. This is my project setup - Rest based Web services using Apache CXF Hibernate 3.0 (With relevant optimizations like lazy loading and custom HQL for tune up) Tomcat 6.0 MySql 5.5 My questions are - Are there alternatives to Mysql that offer better performance for what I'm trying to do? What are some general things to abide by in order to scale a Java based web application? I am thinking of putting my Application in two tomcat instances with httpd redirecting the request to appropriate tomcat on basis of load. Is this the right approach? Separate tomcat instances can help but then database becomes the bottleneck since both applications access the same database? I am a programmer not a Db Admin, how difficult would it be to cluster a Mysql database (or, to cluster whatever database offered as an alternative to 1)? How effective are caching solutions like EHCache? Any other general best practices? Some clarifications - Could you partition the data? Yes we could but we're trying to avoid it. We need to run a lot of data mining algorithms and the design would evolve over time so we can't be sure what lines of partition should be there.

    Read the article

  • hibernate fail mapping two tables

    - by sebbalex
    Hi guys, I'd like to understand how it is possible: Until I was working with one table everything worked fine, when I have mapped another table it fails as shown below: Glassfish start: INFO: configuring from resource: /hibernate.cfg.xml INFO: Configuration resource: /hibernate.cfg.xml INFO: Reading mappings from resource : hibernate_centrale.hbm.xml //first table INFO: Mapping class: com.italtel.patchfinder.objects.centrale - centrale INFO: Reading mappings from resource : hibernate_impianti.hbm.xml //second table INFO: Mapping class: com.italtel.patchfinder.objects.Impianto - impianti INFO: Configured SessionFactory: null INFO: schema update complete INFO: Hibernate: select centrale0_.id as id0_, centrale0_.name as name0_, centrale0_.impianto as impianto0_, centrale0_.servizio as servizio0_ from centrale centrale0_ group by centrale0_.name INFO: Hibernate: select centrale0_.id as id0_, centrale0_.name as name0_, centrale0_.impianto as impianto0_, centrale0_.servizio as servizio0_ from centrale centrale0_ where centrale0_.name='ANCONA' order by centrale0_.name asc //Error org.hibernate.hql.ast.QuerySyntaxException: impianti is not mapped [from impianti where impianto='SD' order by modulo asc] at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:181) ..... config: table1 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.italtel.patchfinder.objects.Impianto" table="impianti"> <id column="id" name="id"> <generator class="increment"/> </id> <property name="impianto"/> <property name="modulo"/> </class> </hibernate-mapping> table2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.italtel.patchfinder.objects.centrale" table="centrale"> <id column="id" name="id"> <generator class="increment"/> </id> <property name="name"/> <property name="impianto"/> <property name="servizio"/> </class> </hibernate-mapping> connection stuff ... <property name="hbm2ddl.auto">update</property> <mapping resource="hibernate_centrale.hbm.xml"/> <mapping resource="hibernate_impianti.hbm.xml"/> </session-factory> </hibernate-configuration> Class: public List loadAll() { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); return session.createQuery("from centrale group by name").list(); } public List<centrale> loadImplants(String centrale) { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); return session.createQuery("from centrale where name='" + centrale + "' order by name asc").list(); } public List<Impianto> loadModules(String implant) { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); return session.createQuery("from impianti where impianto='" + implant + "' order by modulo asc").list(); } } Do you have some advice? Thanks in advance

    Read the article

  • Hibernate unable to instantiate default tuplizer - cannot find getter

    - by ZeldaPinwheel
    I'm trying to use Hibernate to persist a class that looks like this: public class Item implements Serializable, Comparable<Item> { // Item id private Integer id; // Description of item in inventory private String description; // Number of items described by this inventory item private int count; //Category item belongs to private String category; // Date item was purchased private GregorianCalendar purchaseDate; public Item() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public GregorianCalendar getPurchaseDate() { return purchaseDate; } public void setPurchasedate(GregorianCalendar purchaseDate) { this.purchaseDate = purchaseDate; } My Hibernate mapping file contains the following: <property name="puchaseDate" type="java.util.GregorianCalendar"> <column name="purchase_date"></column> </property> When I try to run, I get error messages indicating there is no getter function for the purchaseDate attribute: 577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20 577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 592 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/home_inventory 592 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****} 1078 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.1.45 1078 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.12 ( Revision: ${bzr.revision-id} ) 1103 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect 1107 [main] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 1109 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 1110 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 1110 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 1110 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 1110 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 1110 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 1111 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 1112 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 1113 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 1113 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 1113 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 1114 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 1117 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 1118 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled 1151 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:323) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:475) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84) at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:295) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385) at service.HibernateSessionFactory.currentSession(HibernateSessionFactory.java:53) at service.ItemSvcHibImpl.generateReport(ItemSvcHibImpl.java:78) at service.test.ItemSvcTest.testGenerateReport(ItemSvcTest.java:226) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at junit.framework.TestCase.runTest(TestCase.java:164) at junit.framework.TestCase.runBare(TestCase.java:130) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.runTest(TestSuite.java:230) at junit.framework.TestSuite.run(TestSuite.java:225) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:107) ... 29 more Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for puchaseDate in class domain.Item at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:328) at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:321) at org.hibernate.mapping.Property.getGetter(Property.java:304) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:299) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:158) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77) ... 34 more I'm new to Hibernate, so I don't know all the ins and outs, but I do have the getter and setter for the purchaseDate attribute. I don't know what I'm missing here - does anyone else? Thanks!

    Read the article

  • [hibernate - jpa ] good practices and bad practices

    - by blow
    Hi all, i have some questions about interaction with hibernate. openSession or getCurrentSession (without jta, thread insted)? How mix session operations with swing gui? Is good have something like this in a javabean class? public void actionPerformed(ActionEvent event) { // session code } Can i add methods to my entities that contains hql queries or is a bad practice? For example: // This method is in an entity MyOtherEntity.java class public int getDuration(){ Session session=HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); int sum=(Integer)session.createQuery("select sum(e.duration) as duration from MyEntity as e where e.myOtherEntity.id=:id group by e.name"). .setLong("id", getId()); .uniqueResult(); return sum; } In alternative how can i do this in a better and elegant way? Thanks.

    Read the article

  • Hibernate : load and

    - by Albert Kam
    According to the tutorial : http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=27hibernateloadvshibernateget, If you initialize a JavaBean instance with a load method call, you can only access the properties of that JavaBean, for the first time, within the transactional context in which it was initialized. If you try to access the various properties of the JavaBean after the transaction that loaded it has been committed, you'll get an exception, a LazyInitializationException, as Hibernate no longer has a valid transactional context to use to hit the database. But with my experiment, using hibernate 3.6, and postgres 9, it doesnt throw any exception at all. Am i missing something ? Here's my code : import org.hibernate.Session; public class AppLoadingEntities { /** * @param args */ public static void main(String[] args) { HibernateUtil.beginTransaction(); Session session = HibernateUtil.getSession(); EntityUser userFromGet = get(session); EntityUser userFromLoad = load(session); // finish the transaction session.getTransaction().commit(); // try fetching field value from entity bean that is fetched via get outside transaction, and it'll be okay System.out.println("userFromGet.getId() : " + userFromGet.getId()); System.out.println("userFromGet.getName() : " + userFromGet.getName()); // fetching field from entity bean that is fetched via load outside transaction, and it'll be errornous // NOTE : but after testing, load seems to be okay, what gives ? ask forums try { System.out.println("userFromLoad.getId() : " + userFromLoad.getId()); System.out.println("userFromLoad.getName() : " + userFromLoad.getName()); } catch(Exception e) { System.out.println("error while fetching entity that is fetched from load : " + e.getMessage()); } } private static EntityUser load(Session session) { EntityUser user = (EntityUser) session.load(EntityUser.class, 1l); System.out.println("user fetched with 'load' inside transaction : " + user); return user; } private static EntityUser get(Session session) { // safe to set it to 1, coz the table got recreated at every run of this app EntityUser user = (EntityUser) session.get(EntityUser.class, 1l); System.out.println("user fetched with 'get' : " + user); return user; } } And here's the output : 88 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final 93 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.0.Final 94 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 96 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 98 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 139 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml 139 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml 172 [main] WARN org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide! 191 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null 237 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: EntityUser 263 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity EntityUser on table MstUser 293 [main] INFO org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring 296 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled. 300 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 300 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20 300 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 309 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/hibernate 309 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=sofco, password=****} 354 [main] INFO org.hibernate.cfg.SettingsFactory - Database -> name : PostgreSQL version : 9.0.1 major : 9 minor : 0 354 [main] INFO org.hibernate.cfg.SettingsFactory - Driver -> name : PostgreSQL Native Driver version : PostgreSQL 9.0 JDBC4 (build 801) major : 9 minor : 0 372 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.PostgreSQLDialect 382 [main] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException 383 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory 384 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 384 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 384 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 384 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 384 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 384 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 384 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 384 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 385 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 385 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 385 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 385 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 385 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 385 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 385 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 385 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 385 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 385 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 385 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 386 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 386 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 388 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout 389 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 389 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 389 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 389 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 389 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled 402 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 549 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured Hibernate: select entityuser0_.id as id0_0_, entityuser0_.name as name0_0_, entityuser0_.password as password0_0_ from MstUser entityuser0_ where entityuser0_.id=? user fetched with 'get' : 1:Albert Kam xzy:abc user fetched with 'load' inside transaction : 1:Albert Kam xzy:abc userFromGet.getId() : 1 userFromGet.getName() : Albert Kam xzy userFromLoad.getId() : 1 userFromLoad.getName() : Albert Kam xzy

    Read the article

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

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

    Read the article

  • What is causing a Hibernate SQL query exception?

    - by Dark Star1
    Hi all and sorry in advance for this post but I've spent way too much time going around in circles so I'm hoping someone could shed a light on it here for me. I updated a webapp on Tomcat and I'm getting the following error which didn't exist on the previous version. Though I am quite confident that the part of code I modifed isn't to blame as I have tested the app on two different dev servers. The production server is configured thus: CentOS 5.4 virtual server with tomcat 5.5.23 running mysql 5.0.77. The two dev servers are: Windows XP SP2 running tomcat 5.5.23 with mysql 5.1.49 Mac OSX 10.6.6 Running tomcat 6 with mysql 5.1.51 The application was developed using struts (1.1 as far as I can gather) with hibernate 3 as the peristence layer. It only fails on the production server for some reason I can't fathom. I'd like to draw your attention to the java.sql.SQLException near the bottom. After some long searching I found this but because it was posted years ago (about 1 year before development started on this app I'm sure Hibernate has evolved from that version. as I can't find a way of implementing his solution. I use Eclipse Helios as an IDE. Thanks in advance for taking your time to read this, to all who manage to reply. javax.servlet.ServletException: org.hibernate.exception.SQLGrammarException: could not execute query at fr.company.action.login.LoginAction.execute(LoginAction.java:219) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at fr.company.util.EncodingFilter.doFilter(EncodingFilter.java:37) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:113) at java.lang.Thread.run(Thread.java:636) javax.servlet.ServletException: org.hibernate.exception.SQLGrammarException: could not execute query at fr.company.action.login.LoginAction.execute(LoginAction.java:219) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at fr.company.util.EncodingFilter.doFilter(EncodingFilter.java:37) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:113) at java.lang.Thread.run(Thread.java:636) java.lang.Exception: org.hibernate.exception.SQLGrammarException: could not execute query at fr.company.dao.GenericDAO.findOne(GenericDAO.java:204) at fr.company.dao.UserDAO.findOneUser(UserDAO.java:146) at fr.company.service.UserPeer.logUser(UserPeer.java:72) at fr.company.action.login.LoginAction.execute(LoginAction.java:127) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at fr.company.util.EncodingFilter.doFilter(EncodingFilter.java:37) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:113) at java.lang.Thread.run(Thread.java:636) Caused by: org.hibernate.exception.SQLGrammarException: could not execute query at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:65) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.loader.Loader.doList(Loader.java:2153) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029) at org.hibernate.loader.Loader.list(Loader.java:2024) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:369) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:300) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1128) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79) at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:749) at fr.company.dao.GenericDAO.findOne(GenericDAO.java:198) ... 26 more Caused by: java.sql.SQLException: Unknown column 'user0_1_.poloSize' in 'field list' at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666) at com.mysql.jdbc.Connection.execSQL(Connection.java:2994) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:936) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1030) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:139) at org.hibernate.loader.Loader.getResultSet(Loader.java:1669) at org.hibernate.loader.Loader.doQuery(Loader.java:662) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224) at org.hibernate.loader.Loader.doList(Loader.java:2150) ... 35 more

    Read the article

  • Grails multiple databases

    - by srinath
    Hi, how can we write queries on 2 databases . I installed datasources plugin and domain classes are : class Organization { long id long company_id String name static mapping = { version false table 'organization_' id column : 'organizationId' company_id column : 'companyId' name column : 'name' } } class Assoc { Integer id Integer association_id Integer organization_id static mapping = { version false table 'assoc' id column : 'ASSOC_ID' association_id column : 'ASSOCIATION_ID' organization_id column : 'ORGANIZATION_ID' } } this is working : def org = Organization.list() def assoc = Assoc.list() and this is not working : def query = Organization.executeQuery("SELECT o.name as name, o.id FROM Organization o WHERE o.id IN (SELECT a.organization_id FROM Assoc a )") error : org.hibernate.hql.ast.QuerySyntaxException: Assoc is not mapped [SELECT o.name as name, o.id FROM org.com.domain.Organization o WHERE o.id IN (SELECT a.organization_id FROM AssocOrg a )] How can we connect with 2 databases using single query ? thanks in advance .

    Read the article

  • Nhibernate many to many criteria query with subselect

    - by Max
    I have a simple example of a blog: a Post table, a Tag table and a Post_Tag_MM lookup table linking the two tables. I use this hql query in order to fetch all posts, that DONT have some tags: var result = session .CreateQuery(@" select p from Post p join p.Tags t where (select count(ti) from p.Tags ti where ti.Uid in (:uidList)) = 0 ") .SetParameterList("uidList", uidList) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Post>(); How can this many-to-many query and the subselect translated into a criteria query? I dont quite understand the DetachedCriteria API yet and could not get it to return the right resultset. Thank you very much in advance. Regards, Max

    Read the article

  • SQL Injection with Plain-Vanilla NHibernate

    - by James D
    Hello, Plain-vanilla NHibernate setup, eg, no fluent NHibernate, no HQL, nothing except domain objects and NHibernate mapping files. I load objects via: _lightSabers = session.CreateCriteria(typeof(LightSaber)).List<LightSaber>(); I apply raw user input directly to one property on the "LightSaber" class: myLightSaber.NameTag = "Raw malicious text from user"; I then save the LightSaber: session.SaveOrUpdate(myLightSaber); Everything I've seen says that yes, under this situation you are immune to SQL injection, because of the way NHibernate parameterizes and escapes the queries under the hood. However, I'm also a relative NHibernate beginner so I wanted to double-check. *waves hand* these aren't the droids you're looking for. Thanks!

    Read the article

  • How does Fluent NHibernate support the Import Entity

    - by Bender
    I want to create a strongly type object from a fluent NHibernate query. If I were using HQL and NHibernate I belive I would need: the class for the output Namespace Model Public Class namecount Public Overridable Property lastname() as string ... Public Overridable Property lastnamecount() as integer ... Public Sub New(lastname as string, count as integer) ... End Class End Namespace an .hbm.xml file <?xml ...> <hibernate-mapping ...> <import class="model.namecount,model"> </hibernate-mapping> and of course the query _session.createquery("select new namecount(lastname, count(lastname)) ...") (The above is a paraphrased example taken from one of the 2008 SummerofNHibernate videos) I cannot find any examples of how to do this with fluent (even in C#), is it possible? If it isn't is there a VB example of how to mix Fluent and .hbm.xml

    Read the article

  • How to execute an update via SQLQuery in Hibernate

    - by Udo Fholl
    Hi, I need to update a joined sub-class. Since Hibernate doesn't allow to update joined sub-classes in hql or named-query I want to do it via SQL. I also can't use a sql named-query because updates via named-query are not supported in Hibernate. So I decided to use a SQLQuery. But Hibernate complaints about not calling addScalar(). Are updates returning the number of rows affected and how is named that column? Are there any other ways to do an update on a joined sub-class in hibernate? Thanks in advance!

    Read the article

  • Hibernate and stored procedures

    - by cc96ai
    As my understanding on setting hibernate, I need to create table meta data file (person.hbm.xml), include all the fields mapping java object (person.java) If we use stored procedures for all transaction, do we still need the above configuration? It seems hibernate and stored procedures will overlap, We set up the stored procedure because we don't want the to developer know all the field in db. If tables change, then we need update above files. Does it mean if we purely use stored procedure, we should just go for JDBC? If hibernate, we should stay in HQL?

    Read the article

  • nhibernate fatal error

    - by Afif Lamloumi
    i have an error ( System.InvalidCastException: Unable to cast object of type 'AccountProxy' to type 'System.String'.) when i did this code i mapped the tables( Account,AccountString,EventData,...) of the the database opengts ( open source) i have this error when i called a function from EventData.cs IQuery query = session.CreateQuery("FROM Eventdata"); IList pets = query.List(); return pets; the Stack Trace: [InvalidCastException: Impossible d'effectuer un cast d'un objet de type 'AccountProxy' en type 'System.String'.] (Object , Object[] , SetterCallback ) +431 NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values) +20 NHibernate.Tuple.Component.PocoComponentTuplizer.SetPropertyValues(Object component, Object[] values) +49 NHibernate.Type.ComponentType.SetPropertyValues(Object component, Object[] values, EntityMode entityMode) +34 NHibernate.Type.ComponentType.ResolveIdentifier(Object value, ISessionImplementor session, Object owner) +150 NHibernate.Type.ComponentType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) +42 NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session) +93 NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +92 NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +675 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +129 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +116 [GenericADOException: could not execute query [ select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_ ] [SQL: select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +213 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +79 NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters) +51 NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +231 NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +369 NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +317 NHibernate.Impl.SessionImpl.List(String query, QueryParameters parameters) +282 NHibernate.Impl.QueryImpl.List() +163 DATA1.EventdataExtensions.GetEventdata() in C:\Users\HP\Desktop\our_project\DATA1\Queries\Eventdata.cs:33 MvcApplication7.Controllers.HistoriqueController.Index() in C:\Users\HP\Desktop\our_project\MvcApplication7\Controllers\HistoriqueController.cs:17 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Any suggestions? how can correct this error Data entity class (outtake from comment): public class MyClass { public virtual string DeviceID { get; set; } public virtual int Timestamp { get; set; } public virtual string Account { get; set; } public virtual int StatusCode { get; set; } public virtual double Latitude { get; set; } public virtual double Longitude { get; set; } public virtual int GpsAge { get; set; } public virtual double SpeedKPH { get; set; } public virtual double Heading { get; set; } public override bool Equals(object obj) { return true; } public override int GetHashCode() { return 0; } }

    Read the article

  • Java framework "suggestion" for persisting the results from an Oracle 9i stored procedure using Apac

    - by chocksaway
    Hello, I am developing a Java servlet which calls an Oracle stored procedure. The stored procedure is likely to "grow" over time, and I have concerns the amount of time taken to "display the results on a web page". While I am at the implementation stage, I would like some suggestions of a Persistence framework which will work on Apache Tomcat 5.5? I see two approaches to persisting the database results. A scheduled database query every N minutes, or something which utilises triggers. Hibernate seems like the obvious answer, but I have never called stored procedures from Hibernate (HQL and Criteria). Is there a more appropriate framework which can be used? Thank you. cheers Miles.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10  | Next Page >