jpa,jpa-2.0,jpql , How to retrieve nested data in JPQL?


How to retrieve nested data in JPQL?

Question:

Tag: jpa,jpa-2.0,jpql

working with OpenJPA2 persistence. I have a very simple entity class, that does have a String property and a List property. I do persist its instances flawlessly with the nested List (in a JSF2 web project). I check the database and there appears two tables (I use automatic schema generation), one for the entity itself, and other table for the nested List. All data persisted using EntityManager is stored fine on both tables.

Problem is I cannot retrieve nested data. I mean, I do a Query for getting all instances of the entity, but the List of all instances come empty.

(DB Engine is MySQL. ORM is OpenJPA2. Server is TomEE 1.6. IDE is Netbeans 8. I use automatic schema generation, so I DO NOT WANT to design the database tables, and I DO WANT to let the ORM create the tables, so I can work purely with objects and forget about DB.)

following is Entity Class code:

@Entity
public class Cliente implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String nombre;

    @ElementCollection
    private List<String> emails = new ArrayList<String>();

   // getters and setters omitted for brevity.

It does have an associated Facade Class, which is ClienteFacade. It includes the getAll method which uses a JPQL Query.

public List<Cliente> listaClientes(){
        Query query = em.createQuery("SELECT c FROM Cliente c");
        return query.getResultList(); }

Problem is, I get all instances of the entity in a List, but all lists of List emails come out empty. I think problem may be in the JPQL query. Still trying to learn JPQL with some difficulty... so please, How can I retrieve the nested data with JPQL?

Many thanks!


Answer:

Try @ElementCollection(fetch = FetchType.EAGER) because the default type is lazy. That means that the lists are not loaded directly.


Related:


Can I make this request more efficient using index?


java,mysql,sql,jpa
I have this bean/table "Userinfo" with columns id, username, and twitchChannel. For most userinfo the twitchChannel column will be null. I'm going through every userinfo entity in the table and search the column twitchChannel, if the column is not null I put the twitchChannel in an array. this is what...

Is it possible to have “connection preparation” with Spring / JPA persistency


java,spring,jpa,spring-data
I have a Spring CrudRepository that is just an interface, and I have a persistence context class where I have defined my data source: @Configuration @EnableTransactionManagement public class PersistenceContext { @Bean(name="dataSource", destroyMethod = "close") public DataSource dataSource() throws SQLException { return ... public interface DataRepository extends CrudRepository<Data, Long> { Data...

How to Fetch Data using Spring Data


spring,jpa,spring-boot,spring-data
Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many relationship, suppose i want to fetch list of books by a particular author_id, since in my book entity, i...

Hibernate/JPA: Check generated sql before updating DB Schema (like .NET EF migrations)


java,hibernate,jpa
So i am trying to learn Hibernate/JPA and i was wondering if there is something similar to .NET's Entity Framework migrations that i can use. I like Code First (Class -> Schema) approach, but the auto generated sql queries may do strange (and dangerous) things to a database. I want...

JPA and Apache Aries: persistence unit unresolved dependency


java,jpa,osgi,blueprint-osgi,aries
I'm trying to configure a datasource for mysql and a corresp. persistence bundle on top of Apache Aries. This is the datasource's blueprint file <bean id="mysqlDataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"> <property name="url" value="jdbc:mysql://matteos-mbp:3306/" /> <property name="user" value="root" /> <property name="password" value="root" /> <property name="databaseName" value="testDBBlueprint" /> <property name="createDatabaseIfNotExist" value="true" /> </bean> <bean...

jsf - foreign key in datatable


jpa,datatable
I'm showing a list of Orders in a datatable , and one of its columns must show the customer_id of that order: customer_id is a fk in ManyToOne relationship. Customer entity @Entity public class Customer { ///other columns @OneToMany(mappedBy = "cliente", fetch=FetchType.EAGER) private List<Order> orders; Order entity @Entity @Table(name =...

Making an efficient query with 7 joins, JPA or SQL? What type of collection?


java,mysql,jpa,join
folks! Had to performance tune an expensive JPA query with 7 joins, taking 42 seconds to complete locally and ~3 minutes in the remote server (AWS). SELECT res FROM Resultado res JOIN res.panoramica pan JOIN pan.gondolaId gon JOIN gon.visitaId vis JOIN vis.estabelecimentoId estab JOIN estab.cliente cli JOIN res.configuracaoAnalise ca JOIN...

org.hibernate.ejb.event.EJB3MergeEventListener missing after upgrading from Hibernate 3 to 4.3.9


java,hibernate,jpa,ejb
I am trying to upgrade from Hibernate 3.6.10 to 4.3.9 (and JPA 2.0 to 2.1). Some code in my application uses the org.hibernate.ejb.event.EJB3MergeEventListener class, which used to be in the hibernate-entitymanager jar, but is missing from the 4.3.9 version. From what I can tell, it was removed as of 4.3,...

javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on event:'prePersist'


hibernate,jpa,eclipselink,bean-validation,jsr303
Given two entities Department and Employee forming a unidirectional one-to-many relationship from Department to Employee based on respective tables in the database in question as follows. public class Department implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "department_id", nullable = false) private Long departmentId; @Size(max =...

JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9


java,hibernate,postgresql,jpa
I am having a rather odd problem. I have native query which runs perfectly when executed on sql server: SELECT date_time, GREATEST(sum(count_up - count_down) OVER (PARTITION BY date_trunc('day', result.date_time) ORDER BY date_time),0) AS cum_amt FROM peoplecounting.result order BY date_time; However, using this query as native query in JPA results in...

Drools Stateful Knowledge Session using persistence


java,jpa,jdbc,drools,jbpm
I am creating a Drools stateful session as described in the JBPM persistence documentation: http://docs.jboss.org/jbpm/v5.1/javadocs/org/drools/persistence/jpa/JPAKnowledgeService.html However, I came across the following exception javax.persistence.TransactionRequiredException: joinTransaction has been called on a resource-local EntityManager which is unable to register for a JTA transaction. My code is : EntityManagerFactory emf = Persistence.createEntityManagerFactory("metadata.model"); Environment env...

Blocking Updating or Inserting an Entity when using Cascade in Hibernate


java,hibernate,jpa,orm,hibernate-mapping
I have an entity , EntHesaplasma , this entity has a relationship with EntCariHareketler entity. I have a foreign key in the EntHesaplasma entity for EntCariHareketler. I want to set a relationship between them , but I dont want to update,insert or remove operations on EntCariHareketler entity. Only I want...

Unidirectional one-to-many mapping in Hibernate generates redundant updates


java,hibernate,jpa
I have defined two classes, Parent and Child. The parent can have a list of children. @Entity public class Parent { @Id @GeneratedValue(...) @SequenceGenerator(...) private long id; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false) private List<Child> children; public Parent() { children =...

Use JSF, JPA, JTA, JAAS, CDI, Bean Validation with Tomcat? [closed]


jsf,tomcat,jpa,cdi,jta
Is it possible to use the following APIs with tomcat (as a lightweight server): JSF, JPA, JTA, JAAS, CDI, Bean Validation. ...

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) doesn't work


java,jpa,glassfish,ejb-3.0
I need to delete a list of employees ignoring any integrity constraints (i.e. successfully delete the entity that doesn't related to any others yet or skip the entity that related to others) using JPA 2.0 and EJB3.0 on glassfish3.0: I iterated on the list and call entity manager in a...

Why JPA entities are treated like this outside a session?


jpa,entity
Hy, I am having a "Solve failed to lazily initialize a collection of role.... exception" in jpa. I understand that outside a session, when you want to retrieve a lazy collection if there is not session bound you will get this error, fine. But what I dont understand is if...

@Resource datasource breaking DB connection


java,jpa,jdbc,jboss,wildfly
I recently wrote a class, in my web application, for parsing a huge XML file and feed a db table with its content. My application is running on Wildfly9, and uses JPA with Hibernate provider to handle a MySQL DB. The AS configuration is pretty standard, I just added my...

Configure HikariCP + Hibernate + GuicePersist(JPA) at Runtime


java,hibernate,jpa,hikaricp,guice-persist
I have a java8 desktop app using GuicePersist, Hibernate, and HikariCP to communicate with a Postgres DB. I've had success getting my app to send/receive data to the DB using this META-INF/persistence.xml: <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <!-- A JPA Persistence Unit --> <persistence-unit name="myJPAunit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>...

What are Relational Objects?


database,jpa,persistence
I am referring to this http://www.tutorialspoint.com/jpa/jpa_architecture.htm for learning JPA ,Here a table is given In query row what is relational object they are referring to? Are they the objects of entity classes which I am making or something else....

How to know an object has changed compared to database


java,hibernate,jpa,playframework,playframework-1.x
I need to know if some fields of a model object has been changed before save because I need to compare the new values with the old ones. I can't touch the model classes are they are generated. My problem is that whenever I change an object in a controller...

JPA persit creates new existing entity in many to one relation


java,hibernate,jpa,insert
I'm new in JPA and I have de following Entities in my project : Animal entity : package com.shop.model; import java.io.Serializable; import javax.persistence.*; @Entity @NamedQueries({ @NamedQuery(name="Animal.findAll", query="SELECT a FROM Animal a"), @NamedQuery(name="Animal.findAllByTypeId", query="SELECT a FROM Animal a WHERE a.type.id = :id"), }) public class Animal implements Serializable { private static...

Envers Pre/PostCollection Listener


java,hibernate,jpa,hibernate-envers
I use Hibernate Envers with conditional logging. The documentation describes quite well how this can be done (http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch15.html#d5e4449). At 2nd item, it says you have to subclass the appropriate listeners.. The purpose of the three listeners EnversPostDeleteEventListener, EnversPostInsertEventListener and EnversPostUpdateEventListener is clear to me. However, I am not quite clear...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column


hibernate,sql-server-2008,jpa,spring-data-jpa
I want to know proper JPA annotation setup to handle MS Server 2008 R2 IDENTITY column. MS Server 2008 R2 (RTM) doesn't support SEQUENCE, but the IDENTITY gives auto increment when I tested by raw sql. However, by JPA I can't make it work by any strategy (IDENTITY, AUTO, TABLE)...

Spring 4 + JPA (Hibernate 4) + JTA transaction manager doesn't flush automatically


java,spring,hibernate,jpa,transactions
I am migrating an application from Spring 3.0.5 + JPA 2.0 to Spring 4 + JPA (Hibernate 4) I have followed the migration guide : https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework. The application is using a JTA transaction manager : a Jencks / GeronimoPlatformTransactionManager (because of transactions distributed on datasources and ESB). The Spring /...

Segregating the read-only and read-write in Spring/J2EE Apps


mysql,jpa,design-patterns,architecture,spring-data
We using Spring, Spring-Data and JPA in our project. For production servers, we would like to setup database cluster such that all read queries are directed to one server and all write queries are directed to another server. This obviously will require some changes in the way the DAOs are...

Use alternative producers of EntityManager / EMF in integration tests


java,maven,jpa,integration-testing,cdi
I looking for way how to use CDI and alternative producers in integration tests. When i speak about producers, i mean EMF producer. Reason for different EMF producer is that i want to use testing in-memory database (different persistence unit). Is there easy way how to start CDI for integrations...

Why is my EntityManager not properly injected?


jpa,ejb,wildfly,entitymanager
I tried to build a project with manages Employees using JPA and Beans and JSF. I started trying to manipulated an existing user which I manually created in the database. (before I tried to read the data from the database, this worked well) I tried this in various ways, by...

JPA AccessType.Property failing to retrieve value from nested classes


java,jpa,persistence
I'm attempting to parse JSON into an @Entity in order to persist the data in a table. I confirmed the parsing works but I have run into an issue when attempting to persist the data. In order to retrieve the needed value in the nested classes (two deep) I am...

Checking for multiple child constraint violations in Hibernate/JPA


spring,hibernate,jpa
TL;DR: Is it possible to perform nested transactions in Hibernate that use SavePoints to rollback to specific states? So I am attempting to persist a parent entity with a OneToMany mapping to child entities. This is working fine. During this persistence, I would like to catch and log ALL constraint...

Transaction error in Spring


java,spring,jpa
I have a project https://github.com/ivartanian/onlinecontrol in Spring MVC + JPA, initially worked with the Spring configuration through XML. Now I am trying to set up the project through JAVA Config (without XML). The project starts, but when I create a new user(entity User), an error transaction. But if I create...

Optimistic locking not throwing exception when manually setting version field


hibernate,jpa,spring-data-jpa
I have a Spring Boot 1.3.M1 web application using Spring Data JPA. For optimistic locking, I am doing the following: Annotate the version column in the entity: @Version private long version;. I confirmed, by looking at the database table, that this field is incrementing properly. When a user requests an...

Java JPA EM.createNativeQuery(sql, someClass).getResultList()


java,jpa
How do I return a list of foobar as below? @MappedSuperclass public abstract class foobar{} @Entity @Table(name="foobar") public class foo extends foobar{} @Entity @Table(name="foobar") public class bar extends foobar{} List<foobar> results = em.createNativeQuery("SELECT * FROM foobar").getResultList(); Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to foobar....

Cache inconsistency - Entity not always persisted in cached Collection


java,hibernate,jpa,caching,ehcache
I'm having an issue where a Validation instance is added to a Collection on a Step instance. Declaration is as follows: Step class: @Entity @Table @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Step extends AbstractEntity implements ValidatableStep { @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "step_id", nullable...

JPQL In clause error - Statement too complex


jpa,derby,jpql
Following is the code which is blowing up if the list which is being passed in to "IN" clause has several values. In my case the count is 1400 values. Also the customer table has several thousands (arround 100,000) of records in it. The query is executing against DERBY database....

Not persisted entity with Hibernate


java,spring,hibernate,jpa
I have created this code: Sale sale = new Sale(); saleService.create(sale); Vendor vendor = new Vendor("name"); Sale updatedSale = saleService.findById(sale.getId()); updatedSale.setVendor(vendor); try { saleService.update(updatedSale); } catch (EntityNotFoundException ex) { System.err.println(""); } Also, sale is in cascade with vendor: @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REFRESH}, targetEntity = Vendor.class) @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.PERSIST })...

Is it possible to connect a JPA implementation to a Neo4j specific version?


jpa,neo4j,datanucleus,kundera,hibernate-ogm
I have a Java project that use an embedded Neo4j database (NoSQL), version 2.0.0. I need to migrate this data for a traditional relational db (SQL). For this job, I thought that using an implementation of JPA could help. I found these three projects: Hibernate OGM DataNucleus Kundera But I...

very high float value changing to infinity while retrieving from database


java,mysql,sql-server,hibernate,jpa
I have an entry in my database select item_numeric_value from Item_Allowed_Values where id=761 datatype of item_numeric_value is float in my db. the result I get is 1.11111111111111E+49. when I retrieve this value in java in a string , I get infinity. is there anything I am missing or doing wrong ?...

Is possible do not fetch eager relation in JPA?


hibernate,jpa
I have relation annotated as following: @OneToMany( fetch = FetchType.EAGER ) Is possible to do not fetch this relation without changing default fetch type to lazy? I ask obout it because I improve existing application and I don't want to change existing entities and their annotations. In my case I...

performance of executing openjpa query


java,performance,jpa,openjpa
I have a rest web app with cxf 3.0.1 framework and openjpa 2.3.0. The web.xml: <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Mobile app rest services</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/cxf-servlet.xml</param-value>...

multiple update with jpa


java,jpa
I need to upgrade a field of several records in bd. How to do this with JPA?. I tried the following but not working: @Override public String estadoPedido(List<DetallePedido> lista) { int cod; String mensage = null; for (DetallePedido ped : lista) { cod = ped.getIdDetalle(); EntityManager em = emf.createEntityManager(); DetallePedido...

Get id column name from POJO, using reflection


java,jpa,reflection,annotations
@Entity @Table(name="MY_TABLE") public class MyTable{ @Id @Column(name="MY_TABLE_ID") @GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE") @SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE") private Long myTableId; How can I, using reflection, get the primary key column name from my POJO, defined with the javax.persistence.Id annotation? I'd have to find the @Id and then get the name property of the @Column...

Hibernate Query cache invalidation


java,hibernate,jpa,caching,concurrency
I am using Hibernate(with JPA) in an application that has a high write-read ratio. For caching I have enabled query-cache and hibernate second level cache(ehcache). The problem I am facing is due to automatic query cache invalidation when an update is done. Is there any way to configure query cache...

Sqlite JPA Primary Key error


java,sqlite,jpa
Hello i have a Problem with Sqlite and JPA. I have the following table in Sqlite: Section: secID INTEGER Primary Key secname TEXT If I use Primary Key in Sqlite this Value will automatically updated when i insert a value like INSERT INTO Section(secname) VALUES("Default"); In my Java Classes i...

Retrieve the id of an Entity object as soon as the entity was instantiated?


jsf,jpa
Is there a way in JPA to retrieve the id of an Entity object as soon as the entity was instantiated? e.g Person person = new Person(); Currently i am using in my entity class the following strategy: @GeneratedValue(strategy = GenerationType.IDENTITY) If not is there a "Dummy Id" strategy for...

Spring Data JPA user posts


java,spring,jpa,data
I have user login and profile view, I would like the users to have posts. Can someone guide me in the right direction? I have a user entity: @Entity @Table(name = "usr", indexes = { @Index(columnList = "email", unique = true) }) // using usr because in may conflict with...

OpenJPA OneToMany and composite key in parent and child table


java,jpa,jpa-2.0,openjpa
I have tables with composited primary key. Server(key=ServerId) ServerId|Name 1 |server1 2 |server2 ParentObj(key=ServerId+Code) ServerId|Code |Title 1 |code1|value1 1 |code2|value2 2 |code1|Value2b ChildObj(key=ServerId+Code+Name) ServerId|Code |Name |Value 1 |code1|prop1|val1 1 |code1|prop2|val2 1 |code2|prop1|val1b 2 |code1|prop3|val3 This is Java beans I have. @Entity @Table(name="ParentObj") @Access(AccessType.FIELD) @IdClass(value=ParentObj.PK.class) @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement public class ParentObj {...

JCR vs JPA for a DMS: performance, benefits, drawbacks


java,jpa,jcr,jackrabbit,dms
After doing some research about JCR or RDBMS, and reading other posts, I am still uncertain whether to use JCR over JPA for a document management system, which has to deal with different document types, very large files and a lot of concurrent access from many users. My main reason...

All I want is to access a H2 mem database in Websphere V8 using JPA 2.0


java,jpa,jdbc,websphere,persistence.xml
I've been struggling with this for days now and I searched dozens of articles in StackOverflow and other dev sites. I used the Deployment Manager interface to configure a Websphere Application Server 8.0.0.3 with a H2 JDBC provider and a Data Source for my application using a tutorial I've found...

Hibernate's ManyToMany simple use


java,spring,hibernate,jpa,many-to-many
I've two entities : CollabEntity and TechnoEntity. A collab can uses several technos. A techno can be used by several collabs. I would like to know all technos used by a specific collab. My DB looks like : CREATE TABLE collabs( co_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, co_firstname VARCHAR(25)...