Search Results

Search found 955 results on 39 pages for 'jpa'.

Page 8/39 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Querying my JPA provider (Hibernate) for a collection of <Id,Name> of an entity

    - by Ittai
    Hi, I have an entity which looks something like this: Id (PK) Name Other business properties and associations... I have the need for my DAL (JPA with hibernate as provider) to return a list of the entities which correlate to some constraints (or just return them all) but instead of returning the entities themselves I'd like to receive only the Id and the Name properties. I know this can be achieved with HQL/SQL (something like: select id,name from entity where...) but I don't want to go down that road. I was thinking of somehow defining the pair a compositioned part of the entity and thought that might help me but I'm not sure that's "legal" as the Id is the PK. The logic for this scenario is to have a textbox which asynchronously queries the web-service (and through it the DAL) for the relevant entities and once an entity is selected then it is loaded as a whole and shipped to the front-end. Would appreciate any feedback, Ittai

    Read the article

  • JPA hibernate OneToOne mapping

    - by Stupidfrog
    enviroment: hibernate 4.1.6.final spring 3.1.2.release spring jpa 1.1.0.release postgresql 9.1-901-1.jdbc4 there is 2 table public A { private Long id; private Long name; } public B { private Long id; private Long table_a_id; } the A.id and B.id is sequential, unique , but no related.(means they are separately id for their own table). how to do mapping? i have tried some method, however the result is not i wanted, because it bind wrong. for example: public A { .... @OneToOne @JoinColumn(name = "id") private B table_b } public B { ... @JsonIgnore @OneToOne(mappedBy = "table_b") private A table_a; } when i query A the result is { "id":5, "table_b":{ "id":5, "table_a_id":4 } } obviously the data join by using their id but not joining using table_a_id. what i expect is { "id":4, "table_b":{ "id":5, "table_a_id":4 } } so can somebody teach me that, how to map this 2 table by using table b table_a_id(foregin key)

    Read the article

  • Can I write to different jetty databases using JPA that is using the same "entity class"

    - by Per
    I am using Java persistance and there EntityManager class and have it assigned to storage a class object that shall be written to the database. My problem is that I want to write to different databases using the same storage class. My solution to that was to write a StorageManagerfactory that has a Map holding all EntityManagers. The solution looked good until I looked at the databases and realized that all information (undepending of the Map, which gets the correct value) was written to the same database (one of the initialised in the Map). So my question is: Can I write to different databases using JPA that is using the same storage class (the class holding the structure of my database)? Thanks

    Read the article

  • Issue with a JPA query

    - by boyd4715
    I am trying to execute the following JPA query: public static final String UPDATE_INVENTORY_CUSTOMER_FOR_AMS_MAPPING = "UPDATE Inventory inventory SET" + " inventory.customer.id = :" + DataAccessConstants.PARAM_CUSTOMER_ID + " ,inventory.lastUpdateUserId = :" + DataAccessConstants.PARAM_USER_ID + " where inventory.amsConsignorName = :" + DataAccessConstants.PARAM_AMS_CONSIGNOR_NAME + " and inventory.amsConsignorOrgCd = :" + DataAccessConstants.PARAM_AMS_CONSIGNOR_ORG_CD + " and inventory.amsConsignorTypeName = :" + DataAccessConstants.PARAM_AMS_CONSIGNOR_TYPE + " and inventory.status.code in (:" + DataAccessConstants.PARAM_STATUS + ")"; but it is seeing the following: update ATL_INVENTORY, set CONSIGNOR_ID=?, LAST_UPDATE_USER_ID=? where AMS_CONSIGNOR_NAME=? and AMS_CONSIGNOR_ORG_CD=? and AMS_CONSIGNOR_TYPE_NAME=? and (CODE in (? , ? , ? , ?)) Any ideal as to why there is a comma after the table name?

    Read the article

  • JPA generic field

    - by m.ugues
    Hallo all Is it possible to persist a generic field? I have this property on an Entity class ... private T payload; ... T extends EventMessagePayload and public interface StringPayload extends EventMessagePayload{ String getPayload(); } In my application i persist the field only when is of String type and during the save operation all works great. When I read the object instead JPA try to create a String object but instead is a StringPaylod. Is there a way to intercept the creation and handle the object marshalling? Kind regards Massimo

    Read the article

  • JPA Bidirectional OneToMany and ManyToOne?

    - by PhoenixJon
    I'm using Oracle JDeveloper 11g Release 2. I created two tables A and B using SQL developer. Table A has a FK to table B. Using the Entities from Tables function, I created two JPA files from it. A has @ManyToOne annotation on FK. And also B has @OneToMany annotation to A. I don't want this. Can I remove this @OneToMany annotation automatically? public class A implements Serializable { ... @ManyToOne @JoinColumn(name = "FIELD_B") private B b; ... } public class B implements Serializable { ... @OneToMany(mappedBy = "B") private List<A> assetList; ... } I don't need @OneToMany mapping.

    Read the article

  • Can JPA do batch update | put | write | insert as pm.makePersistentAll() does in GAE/J

    - by Kenyth
    I searched through multiple discussions here. Can someone just give me a quick and direct answer? And if with JPA you can't do a batch update, what if I don't use transaction, and just use the following flow: em = emf.getEntityManager // do some query // make some data modification em.persist(..) // do some query // make some data modification em.persist(..) // do some query // make some data modification em.persist(..) ... em.close() How does this compare to batch update with regard to performance, and compare to a single transaction commit, measured by RPC calls to datastore server, CPU cycles per request, or so. Does every call to em.persist(..) before em.close() trigger a RPC call to the datastore server? Thanks very much for any response!

    Read the article

  • In JPA, a Map of embeddable values, that have an embedded entity used as the key

    - by Schmuli
    I'm still new to JPA (and Hibernate, which I'm using as my provider), so maybe this just can't be done, but anyway... Consider the following code: @Entity class Root { @Id private long id; private String name; @ElementCollection private Map<ResourceType, Resource> resources; ... } @Entity class ResourceType { @Id private long id; private String name; } @Embeddable class Resource { private ResourceType resourceType; private long value; } In the database, there is a collection table, 'Root_resources', that stores the values of the map, but the resource type appears twice (actually, the resource type ID does), once as the KEY of the map, and once as part of the value. Is there a way, similar to, say, the @MapKey annotation, to indicate that the key is one of the columns of the value (i.e. embedded)?

    Read the article

  • JBoss 7.1.1 + Spring 3.1 + JPA 2 (Hibernate 3.6.8) > Cannot parse beans.xml

    - by Mashrur
    Trying to deploy a JSF 2 app with Spring 3.1 + JPA 2 (Hibernte 3.6.8) into JBoss 7.1.1 AS. The app was working fine on tomcat 7. Now, I have already added and changed some configurations. Added jboss-deployment-structure.xml <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1"> <deployment> <exclusions> <module name="org.apache.log4j" /> <module name="javax.faces.api" slot="main"/> <module name="com.sun.jsf-impl" slot="main"/> <module name="org.hibernate"/> <module name="org.javassist" /> <module name="javaee.api" /> <module name="org.hibernate.validator" /> <module name="org.jboss.as.web" /> <module name="org.jboss.logging" /> <module name="javax.persistence.api" /> <module name="org.jboss.interceptor" /> </exclusions> </deployment> </jboss-deployment-structure> 2. Inside web.xml added these lines: <persistence-unit-ref> <persistence-unit-ref-name>persistence/persistenceUnit</persistence-unit-ref-name> <persistence-unit-name>persistenceUnit</persistence-unit-name> </persistence-unit-ref> 3. Inside applicationContext.xml, changed bean definition for entityManagerFactory by adding this property <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"/> Now, do I still need to do something more than these which is obvious to you? Because, while I am trying to deploy it from eclipse indigo SR2, getting this 14:10:32,046 INFO [org.jboss.modules] JBoss Modules version 1.1.1.GA 14:10:33,054 INFO [org.jboss.msc] JBoss MSC version 1.0.2.GA 14:10:33,200 INFO [org.jboss.as] JBAS015899: JBoss AS 7.1.1.Final "Brontes" starting 14:10:36,375 INFO [org.xnio] XNIO Version 3.0.3.GA 14:10:36,384 INFO [org.jboss.as.server] JBAS015888: Creating http management service using socket-binding (management-http) 14:10:36,432 INFO [org.xnio.nio] XNIO NIO Implementation Version 3.0.3.GA 14:10:36,462 INFO [org.jboss.remoting] JBoss Remoting version 3.2.3.GA 14:10:36,587 INFO [org.jboss.as.logging] JBAS011502: Removing bootstrap log handlers 14:10:36,714 INFO [org.jboss.as.security] (ServerService Thread Pool -- 44) JBAS013101: Activating Security Subsystem 14:10:36,735 INFO [org.jboss.as.naming] (MSC service thread 1-2) JBAS011802: Starting Naming Service 14:10:37,043 INFO [org.jboss.as.mail.extension] (MSC service thread 1-6) JBAS015400: Bound mail session [java:jboss/mail/Default] 14:10:37,208 INFO [org.jboss.as.connector] (MSC service thread 1-7) JBAS010408: Starting JCA Subsystem (JBoss IronJacamar 1.0.9.Final) 14:10:37,295 INFO [org.jboss.as.security] (MSC service thread 1-7) JBAS013100: Current PicketBox version=4.0.7.Final 14:10:37,740 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3) 14:10:38,792 INFO [org.jboss.ws.common.management.AbstractServerConfig] (MSC service thread 1-3) JBoss Web Services - Stack CXF Server 4.0.2.GA 14:10:38,833 INFO [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-2) Starting Coyote HTTP/1.1 on http-localhost-127.0.0.1-8080 14:10:39,534 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-1) JBAS015012: Started FileSystemDeploymentService for directory F:\work\softwares\Application Servers\JBoss\jboss-as-7.1.1.Final\jboss-as-7.1.1.Final\standalone\deployments 14:10:39,618 INFO [org.jboss.as.remoting] (MSC service thread 1-3) JBAS017100: Listening on localhost/127.0.0.1:4447 14:10:39,623 INFO [org.jboss.as.remoting] (MSC service thread 1-2) JBAS017100: Listening on /127.0.0.1:9999 14:10:39,698 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015014: Re-attempting failed deployment treasury.war 14:10:39,706 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015003: Found com.misl.treasury.ui.war in deployment directory. To trigger deployment create a file called com.misl.treasury.ui.war.dodeploy 14:10:40,105 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-2) JBAS010400: Bound data source [java:jboss/datasources/ExampleDS] 14:10:40,399 INFO [org.jboss.as.server.deployment] (MSC service thread 1-1) JBAS015876: Starting deployment of "com.misl.treasury.ui.war" 14:10:40,405 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015876: Starting deployment of "treasury.war" 14:10:55,283 WARN [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Tomcat6InjectionProvider:org.apache.catalina.util.DefaultAnnotationProcessor' for service type 'com.sun.faces.spi.injectionprovider' 14:10:55,289 WARN [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Jetty6InjectionProvider:org.mortbay.jetty.plus.annotation.InjectionCollection' for service type 'com.sun.faces.spi.injectionprovider' 14:10:55,428 INFO [org.jboss.as.jpa] (MSC service thread 1-7) JBAS011401: Read persistence.xml for persistenceUnit 14:10:55,843 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Tomcat6InjectionProvider:org.apache.catalina.util.DefaultAnnotationProcessor' for service type 'com.sun.faces.spi.injectionprovider' 14:10:55,849 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Jetty6InjectionProvider:org.mortbay.jetty.plus.annotation.InjectionCollection' for service type 'com.sun.faces.spi.injectionprovider' 14:10:56,010 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC00001: Failed to start service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "com.misl.treasury.ui.war" at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_23] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_23] at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_23] Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletOutputStream at java.lang.Class.getDeclaredConstructors0(Native Method) [rt.jar:1.6.0_23] at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) [rt.jar:1.6.0_23] at java.lang.Class.getConstructor0(Class.java:2699) [rt.jar:1.6.0_23] at java.lang.Class.getConstructor(Class.java:1657) [rt.jar:1.6.0_23] at org.jboss.as.web.deployment.jsf.JsfManagedBeanProcessor.deploy(JsfManagedBeanProcessor.java:108) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] ... 5 more Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletOutputStream from [Module "deployment.com.misl.treasury.ui.war:main" from Service Module Loader] at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) ... 11 more 14:10:56,628 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."treasury.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."treasury.war".PARSE: Failed to process phase PARSE of deployment "treasury.war" at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_23] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_23] at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_23] Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: SAXException parsing vfs:/F:/work/softwares/Application Servers/JBoss/jboss-as-7.1.1.Final/jboss-as-7.1.1.Final/bin/content/treasury.war/WEB-INF/beans.xml at org.jboss.as.weld.deployment.BeansXmlParser.parse(BeansXmlParser.java:100) at org.jboss.as.weld.deployment.processors.BeansXmlProcessor.parseBeansXml(BeansXmlProcessor.java:133) at org.jboss.as.weld.deployment.processors.BeansXmlProcessor.deploy(BeansXmlProcessor.java:97) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] ... 5 more Caused by: org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:196) at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:175) at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:394) at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:322) at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:281) at org.apache.xerces.impl.XMLScanner.reportFatalError(XMLScanner.java:1459) at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(XMLDocumentScannerImpl.java:903) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:324) at org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:845) at org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:768) at org.apache.xerces.parsers.XMLParser.parse(XMLParser.java:108) at org.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1196) at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:555) at org.apache.xerces.jaxp.SAXParserImpl.parse(SAXParserImpl.java:289) at org.jboss.as.weld.deployment.BeansXmlParser.parse(BeansXmlParser.java:94) ... 8 more 14:10:56,670 INFO [org.jboss.as] (MSC service thread 1-1) JBAS015951: Admin console listening on http://127.0.0.1:9990 14:10:56,672 ERROR [org.jboss.as] (MSC service thread 1-1) JBAS015875: JBoss AS 7.1.1.Final "Brontes" started (with errors) in 25527ms - Started 143 of 222 services (2 services failed or missing dependencies, 76 services are passive or on-demand) 14:10:56,671 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015871: Deploy of deployment "treasury.war" was rolled back with no failure message 14:10:56,679 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "com.misl.treasury.ui.war" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"com.misl.treasury.ui.war\""}} 14:10:56,851 INFO [org.jboss.as.server.deployment] (MSC service thread 1-8) JBAS015877: Stopped deployment com.misl.treasury.ui.war in 172ms 14:10:57,068 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment treasury.war in 395ms 14:10:57,070 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report JBAS014777: Services which failed to start: service jboss.deployment.unit."treasury.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."treasury.war".PARSE: Failed to process phase PARSE of deployment "treasury.war" service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "com.misl.treasury.ui.war" 14:10:57,079 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"com.misl.treasury.ui.war\""}}}} 14:10:57,087 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS014654: Composite operation was rolled back And by the way, JBOSS_HOME\modules\javax\api\main folder only contains a module.xml, no jars. Tried to add jboss-servlet-api_3.0_spec-1.0.0.Final.jar file in that directory and updated module.xml too. But, it shows a very long trail of stacktraces :) I have even removed beans.xml. No change. I have never tried JBoss before. Any help would be highly appreciated.

    Read the article

  • How to populate Java (web) application with initial data using Spring/JPA/Hibernate

    - by Tuukka Mustonen
    I want to setup my database with initial data programmatically. I want to populate my database for development runs, not for testing runs (it's easy). The product is built on top of Spring and JPA/Hibernate. Developer checks out the project Developer runs command/script to setup database with initial data Developer starts application (server) and begins developing/testing then: Developer runs command/script to flush the database and set it up with new initial data because database structures or the initial data bundle were changed What I want is to setup my environment by required parts in order to call my DAOs and insert new objects into database. I do not want to create initial data sets in raw SQL, XML, take dumps of database or whatever. I want to programmatically create objects and persist them in database as I would in normal application logic. One way to accomplish this would be to start up my application normally and run a special servlet that does the initialization. But is that really the way to go? I would love to execute the initial data setup as Maven task and I don't know how to do that if I take the servlet approach. There is somewhat similar question. I took a quick glance at the suggested DBUnit and Unitils. But they seem to be heavily focused in setting up testing environments, which is not what I want here. DBUnit does initial data population, but only using xml/csv fixtures, which is not what I'm after here. Then, Maven has SQL plugin, but I don't want to handle raw SQL. Maven also has Hibernate plugin, but it seems to help only in Hibernate configuration and table schema creation (not in populating db with data). How to do this?

    Read the article

  • Duplicate a collection of entities and persist in Hibernate/JPA

    - by Michael Bavin
    Hi, I want to duplicate a collection of entities in my database. I retreive the collection with: CategoryHistory chNew = new CategoryHistory(); CategoryHistory chLast = (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE ch.date = MAX(date)").getSingleResult; List<Category> categories = chLast.getCategories(); chNew.addCategories(categories)// Should be a copy of the categories: OneToMany Now i want to duplicate a list of 'categories' and persist it with EntityManager. I'm using JPA/Hibernate. UPDATE After knowing how to detach my entities, i need to know what to detach: current code: CategoryHistory chLast = (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE ch.date=(SELECT MAX(date) from CategoryHistory)").getSingleResult(); Set<Category> categories =chLast.getCategories(); //detach org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession(); session.evict(chLast);//detaches also its child-entities? //set the realations chNew.setCategories(categories); for (Category category : categories) { category.setCategoryHistory(chNew); } //set now create date chNew.setDate(Calendar.getInstance().getTime()); //persist em.persist(chNew); This throws a failed to lazily initialize a collection of role: entities.CategoryHistory.categories, no session or session was closed exception. I think he wants to lazy load the categories again, as i have them detached. What should i do now?

    Read the article

  • JPA : many-to-many - only one foreign key in the association table

    - by Julien
    Hi, I mapped two classes in a ManyToMany association with these annotations : @Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public abstract class TechnicalItem extends GenericBusinessObject implements Resumable{ @SequenceGenerator(name="TECHNICAL_ITEM_ID_GEN", sequenceName="TECHNICAL_ITEM_ID_SEQ") @Id @Column(name = "\"ID\"", nullable = false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TECHNICAL_ITEM_ID_GEN") private int id; @ManyToMany(mappedBy = "referencePerformanceItems", fetch=FetchType.LAZY) private List testingRates; } @Entity @DiscriminatorValue("T") public class TestingRate extends Rate { @ManyToMany(fetch=FetchType.LAZY) @JoinTable(name="ecc.\"TESTING_RATE_TECHNICAL_ITEM\"", joinColumns = {@JoinColumn(name = "\"TESTING_RATE_ID\"")}, inverseJoinColumns = {@JoinColumn(name = "\"TECHNICAL_ITEM_ID\"")}) //@ManyToMany(mappedBy = "testingRates", fetch=FetchType.LAZY) private List referencePerformanceItems; } The sql generated for the association table creation is : create table ecc."TESTING_RATE_TECHNICAL_ITEM" ( "TESTING_RATE_ID" int4 not null, "TECHNICAL_ITEM_ID" int4 not null ); alter table ecc."TESTING_RATE_TECHNICAL_ITEM" add constraint FKC5D64DF6A2FE2698 foreign key ("TESTING_RATE_ID") references ecc."RATE"; There is no mention of the second foreign key "TECHNICAL_ITEM_ID" (the second part of the composite foreign key which should be in the association table). Is it a normal behaviour ? What should I do in the mapping if I want my 2 columns are 2 foreign keys referencing the primary keys of my 2 concerned tables. I use a PostGreSQL database and Hibernate as JPA provider. Thanks, Julien

    Read the article

  • Disable caching in JPA (eclipselink)

    - by James
    Hi, I want to use JPA (eclipselink) to get data from my database. The database is changed by a number of other sources and I therefore want to go back to the database for every find I execute. I have read a number of posts on disabling the cache but this does not seem to be working. Any ideas? I am trying to execute the following code: EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default"); EntityManager em = entityManagerFactory.createEntityManager(); MyLocation one = em.createNamedQuery("MyLocation.findMyLoc").getResultList().get(0); MyLocation two = em.createNamedQuery("MyLocation.findMyLoc").getResultList().get(0); System.out.println(one==two); one==two is true while I want it to be false. I have tried adding each/all the following to my persistence.xml <property name="eclipselink.cache.shared.default" value="false"/> <property name="eclipselink.cache.size.default" value="0"/> <property name="eclipselink.cache.type.default" value="None"/> I have also tried adding the @Cache annotation to the Entity itself: @Cache( type=CacheType.NONE, // Cache nothing expiry=0, alwaysRefresh=true ) Am I misunderstanding something? Thank you, James

    Read the article

  • JPA association table is not deletable

    - by Marcel
    Hi I have a problem with JPA (EclipseLink). I am not able to delete a association table. This is the situation: Product 1:n to ProductResource Resource 1:n to ProductResource I first set the product and resource attributes of ProductResource. If I then try to delete the ProductResource object nothing happens (no sql is generated - no exception). If I comment out both OneToMany annotations in ProductResource I can delete the object. I can also delete the object when product and resource attributes are not set. If I comment out only the annotation above the ressource attribut the ProductResource object gets deleted upon the deletion of the product object (cascade=CascadeType.ALL). I hope someone could give me a hint. Thank you. Product Resource: public class ProductResource implements Serializable { @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.MERGE) private Product product; @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.MERGE) private Resource resource; Product: public class Product implements Serializable { @OneToMany(mappedBy="product", fetch=FetchType.EAGER, cascade=CascadeType.ALL) private List<ProductResource> productResources = new ArrayList<ProductResource>(); Resource: public class Resource implements Serializable { @OneToMany(mappedBy="resource", fetch=FetchType.EAGER, cascade=CascadeType.ALL) private List<ProductResource> productResources = new ArrayList<ProductResource>(); Greetings Marcel

    Read the article

  • JPA - Setting entity class property from calculated column?

    - by growse
    I'm just getting to grips with JPA in a simple Java web app running on Glassfish 3 (Persistence provider is EclipseLink). So far, I'm really liking it (bugs in netbeans/glassfish interaction aside) but there's a thing that I want to be able to do that I'm not sure how to do. I've got an entity class (Article) that's mapped to a database table (article). I'm trying to do a query on the database that returns a calculated column, but I can't figure out how to set up a property of the Article class so that the property gets filled by the column value when I call the query. If I do a regular "select id,title,body from article" query, I get a list of Article objects fine, with the id, title and body properties filled. This works fine. However, if I do the below: Query q = em.createNativeQuery("select id,title,shorttitle,datestamp,body,true as published, ts_headline(body,q,'ShortWord=0') as headline, type from articles,to_tsquery('english',?) as q where idxfti @@ q order by ts_rank(idxfti,q) desc",Article.class); (this is a fulltext search using tsearch2 on Postgres - it's a db-specific function, so I'm using a NativeQuery) You can see I'm fetching a calculated column, called headline. How do I add a headline property to my Article class so that it gets populated by this query? So far, I've tried setting it to be @Transient, but that just ends up with it being null all the time.

    Read the article

  • Disable chaching in JPA (eclipselink)

    - by James
    Hi, I want to use JPA (eclipselink) to get data from my database. The database is changed by a number of other sources and I therefore want to go back to the database for every find I execute. I have read a number of posts on disabling the cache but this does not seem to be working. Any ideas? I am trying to execute the following code: EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default"); EntityManager em = entityManagerFactory.createEntityManager(); MyLocation one = em.createNamedQuery("MyLocation.findMyLoc").getResultList().get(0); MyLocation two = em.createNamedQuery("MyLocation.findMyLoc").getResultList().get(0); System.out.println(one==two); one==two is true while I want it to be false. I have tried adding each/all the following to my persistence.xml <property name="eclipselink.cache.shared.default" value="false"/> <property name="eclipselink.cache.size.default" value="0"/> <property name="eclipselink.cache.type.default" value="None"/> I have also tried adding the @Cache annotation to the Entity itself: @Cache( type=CacheType.NONE, // Cache nothing expiry=0, alwaysRefresh=true ) Am I misunderstanding something? Thank you, James

    Read the article

  • JPA - Entity design problem

    - by Yatendra Goel
    I am developing a Java Desktop Application and using JPA for persistence. I have a problem mentioned below: I have two entities: Country City Country has the following attribute: CountryName (PK) City has the following attribute: CityName Now as there can be two cities with same name in two different countries, the primaryKey for City table in the datbase is a composite primary key composed of CityName and CountryName. Now my question is How to implement the primary key of the City as an Entity in Java @Entity public class Country implements Serializable { private String countryName; @Id public String getCountryName() { return this.countryName; } } @Entity public class City implements Serializable { private CityPK cityPK; private Country country; @EmbeddedId public CityPK getCityPK() { return this.cityPK; } } @Embeddable public class CityPK implements Serializable { public String cityName; public String countryName; } Now as we know that the relationship from Country to City is OneToMany and to show this relationship in the above code, I have added a country variable in City class. But then we have duplicate data(countryName) stored in two places in the City class: one in the country object and other in the cityPK object. But on the other hand, both are necessary: countryName in cityPK object is necessary because we implement composite primary keys in this way. countryName in country object is necessary because it is the standard way of showing relashionship between objects. How to get around this problem?

    Read the article

  • Is JPA persistence.xml classpath located?

    - by Vinnie
    Here's what I'm trying to do. I'm using JPA persistence in a web application, but I have a set of unit tests that I want to run outside of a container. I have my primary persistence.xml in the META_INF folder of my main app and it works great in the container (Glassfish). I placed a second persistence.xml in the META-INF folder of my test-classes directory. This contains a separate persistence unit that I want to use for test only. In eclipse, I placed this folder higher in the classpath than the default folder and it seems to work. Now when I run the maven build directly from the command line and it attempts to run the unit tests, the persistence.xml override is ignored. I can see the override in the META-INF folder of the maven generated test-classes directory and I expected the maven tests to use this file, but it isn't. My Spring test configuration overrides, achieved in a similar fashion are working. I'm confused at to whether the persistence.xml is located through the classpath. If it were, my override should work like the spring override since the maven surefire plugin explains "[The test class directory] will be included at the beginning the test classpath". Did I wrongly anticipate how the persistence.xml file is located? I could (and have) create a second persistence unit in the production persistence.xml file, but it feels dirty to place test configuration into this production file. Any other ideas on how to achieve my goal is welcome.

    Read the article

  • [hibernate - jpa] @OneToOne annotoation problem (i think...)

    - by blow
    Hi all, im new in hibernate and JPA and i have some problems with annotations. My target is to create this table in db (PERSON_TABLE with personal-details) ID ADDRESS NAME SURNAME MUNICIPALITY_ID First of all, i have a MUNICIPALITY table in db containing all municipality of my country. I mapped this table in this ENTITY: @Entity public class Municipality implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String country; private String province; private String name; @Column(name="cod_catasto") private String codCatastale; private String cap; public Municipality() { } ... Then i make an EMBEDDABLE class Address containing fields that realize a simple address... @Embeddable public class Address implements Serializable { @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="id_municipality") private Municipality municipality; @Column(length=45) private String address; public Address() { } ... Finally i embedded this class into Person ENTITY @Entity public class Person implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; private String surname; @Embedded private Address address; public Person() { } ... All works good when i have to save a new Person record, in fact hibernate creates a PERSON_TABLE as i want, but if i try to retrieve a Person record i have an exception. HQL is simply "from Person" The excpetion is (Entities is the package containing all classes above-mentioned): org.hibernate.AnnotationException: @OneToOne or @ManyToOne on Entities.Person.address.municipality references an unknown entity: Entities.Municipality Is the @OneToOne annotation the problem? Thanks.

    Read the article

  • Finding users whose birtday is today with JPA

    - by Jeduan Cornejo
    Hi, I have a table with users and are trying to get a list with the people who have birthday today so the app can send an email. The User is defined as @Entity public class User { @Size(max = 30) @NotNull private String name; [...] @Temporal(TemporalType.DATE) @DateTimeFormat(style = "S-") protected Date birthday; } and I've got a method which returns the people which were born today like so @SuppressWarnings("unchecked") public static List<User> findUsersWithBirthday() { List<User> users = entityManager().createQuery("select u from User u where u.birthday = :date") .setParameter("date", new Date(), TemporalType.DATE) .getResultList(); return users; } This is fine and all for finding people which were born today, however tha's not really that useful, so I've been struggling for a way to find all the users that were born today, independent of the year. Using MySQL there's functions I can use like select month(curdate()) as month, dayofmonth(curdate()) as day However I've been struggling to find a JPA equivalent to that. I'm using Spring 3.0.1 and Hibernate 3.3.2

    Read the article

  • Refreshing a JPA result list which is bound with a jTable

    - by exhuma
    First off, I hage to write this on my mobile. But I'll try to format it properly. In Netbeans I created a jTable and bound it's values to a JPA result set. This works great. The qery contains a param which i set in the pre-create box of the "query result" component. So just before netbeans creates the query result i write this: myQuery.setParameter("year", "1997"); This works fine. Now, I have an event handler which is supposed to change the param and display the new values in the table. So I do this: myQuery.setParameter("year", "2005"); myResultList.clear(); myResultList.addAll(myQuery.getResultList()); jTable1.updateUI(); This works, but it feels wrong to me. Note: the result set is bound to the table. So I was hoping there was something like this: myQuery.setParameter("year", "2005"); myResultList.refresh(); Is there something like this?

    Read the article

  • Is it possible to order by a composite key with JPA and CriteriaBuilder

    - by Kjir
    I would like to create a query using the JPA CriteriaBuilder and I would like to add an ORDER BY clause. This is my entity: @Entity @Table(name = "brands") public class Brand implements Serializable { public enum OwnModeType { OWNER, LICENCED } @EmbeddedId private IdBrand id; private String code; //bunch of other properties } Embedded class is: @Embeddable public class IdBrand implements Serializable { @ManyToOne private Edition edition; private String name; } And the way I am building my query is like this: CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Brand> q = cb.createQuery(Brand.class).distinct(true); Root<Brand> root = q.from(Brand.class); if (f != null) { f.addCriteria(cb, q, root); f.addOrder(cb, q, root, sortCol, ascending); } return em.createQuery(q).getResultList(); And here are the functions called: public void addCriteria(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r) { } public void addOrder(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r, String sortCol, boolean ascending) { if (ascending) { q.orderBy(cb.asc(r.get(sortCol))); } else { q.orderBy(cb.desc(r.get(sortCol))); } } If I try to set sortCol to something like "id.edition.number" I get the following error: javax.ejb.EJBException: java.lang.IllegalArgumentException: Unable to resolve attribute [id.name] against path Any idea how I could accomplish that? I tried searching online, but I couldn't find a hint about this... Also would be great if I could do a similar ORDER BY when I have a @ManyToOne relationship (for instance, "id.edition.number")

    Read the article

  • Total row count for pagination using JPA Criteria API

    - by ThinkFloyd
    I am implementing "Advanced Search" kind of functionality for an Entity in my system such that user can search that entity using multiple conditions(eq,ne,gt,lt,like etc) on attributes of this entity. I am using JPA's Criteria API to dynamically generate the Criteria query and then using setFirstResult() & setMaxResults() to support pagination. All was fine till this point but now I want to show total number of results on results grid but I did not see a straight forward way to get total count of Criteria query. This is how my code looks like: CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Brand> cQuery = builder.createQuery(Brand.class); Root<Brand> from = cQuery.from(Brand.class); CriteriaQuery<Brand> select = cQuery.select(from); . . //Created many predicates and added to **Predicate[] pArray** . . select.where(pArray); // Added orderBy clause TypedQuery typedQuery = em.createQuery(select); typedQuery.setFirstResult(startIndex); typedQuery.setMaxResults(pageSize); List resultList = typedQuery.getResultList(); My result set could be big so I don't want to load my entities for count query, so tell me efficient way to get total count like rowCount() method on Criteria (I think its there in Hibernate's Criteria).

    Read the article

  • Strange JPA one-to-many behavior when trying to set the "many" on the "one" entity

    - by errr
    I've mapped two entities using JPA (specifically Hibernate). Those entities have a one-to-many relationship (I've simplified for presentation): @Entity public class A { @ManyToOne public B getB() { return b; } } @Entity public Class B { @OneToMany(mappedBy="b") public Set<A> getAs() { return as; } } Now, I'm trying to create a relationship between two instances of these entities by using the setter of the one-side/not-owner-side of the relationship (i.e the table being referenced to): em.getTransaction().begin(); A a = new A(); B b = new B(); Set<A> as = new HashSet<A>(); as.add(a); b.setAs(as); em.persist(a); em.persist(b); em.getTransaction().commit(); But then, the relationship isn't persisted to the DB (the row created for entity A isn't referencing the row created for entity B). Why is it so? I'd excpect it to work. Also, if I remove the "mappedBy" property from the @OneToMany annotation it will work. Again - why is it so? and what are the possible effects for removing the "mappedBy" property?

    Read the article

  • JPA/Hibernate Parent/Child relationship

    - by NubieJ
    Hi I am quite new to JPA/Hibernate (Java in general) so my question is as follows (note, I have searched far and wide and have not come across an answer to this): I have two entities: Parent and Child (naming changed). Parent contains a list of Children and Children refers back to parent. e.g. @Entity public class Parent { @Id @Basic @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "PARENT_ID", insertable = false, updatable = false) private int id; /* ..... */ @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY) @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", nullable = true) private Set<child> children; /* ..... */ } @Entity public class Child { @Id @Basic @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "CHILD_ID", insertable = false, updatable = false) private int id; /* ..... */ @ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID") private Parent parent; /* ..... */ } I want to be able to do the following: Retrieve a Parent entity which would contain a list of all its children (List), however, when listing Parent (getting List, it of course should omit the children from the results, therefore setting FetchType.LAZY. Retrieve a Child entity which would contain an instance of the Parent entity. Using the code above (or similar) results in two exceptions: Retrieving Parent: A cycle is detected in the object graph. This will cause infinitely deep XML... Retrieving Child: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxxxxxxxxxx, no session or session was closed When retrieving the Parent entity, I am using a named query (i.e. calling it specifically) @NamedQuery(name = "Parent.findByParentId", query = "SELECT p FROM Parent AS p LEFT JOIN FETCH p.children where p.id = :id") Code to get Parent (i.e. service layer): public Parent findByParentId(int parentId) { Query query = em.createNamedQuery("Parent.findByParentId"); query.setParameter("id", parentId); return (Parent) query.getSingleResult(); } Why am I getting a LazyInitializationException event though the List property on the Parent entity is set as Lazy (when retrieving the Child entity)?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >