JPA StackOverflowError when loading data in relationship tables - jpa-2.0

I'm trying to implement loading in three tables (the beginning of the problem with mapping)
Products:
#Entity
#Table(name = "products")
public class Product implements Serializable {
#Id
#Column(name = "id")
private Integer id;
#OneToMany(mappedBy = "property", fetch = FetchType.LAZY)
private Collection<ProductProperty> productPropertyCollection;
...
}
Properties:
#Entity
#Table(name = "properties")
public class Property implements Serializable {
#Id
#Column(name = "id")
private Integer id;
#OneToMany(mappedBy = "property", fetch = FetchType.LAZY)
private Collection<ProductProperty> productPropertyCollection;
...
}
Product_Property
#Entity
#Table(name = "product_property")
public class ProductProperty implements Serializable {
#EmbeddedId
protected ProductPropertyPK productPropertyPK;
#MapsId(value = "propertyId")
#JoinColumn(name = "property_id", referencedColumnName = "id")
#ManyToOne()
private Property property;
#MapsId(value = "productId")
#JoinColumn(name = "product_id", referencedColumnName = "id")
#ManyToOne()
private Product product;
...
}
#Embeddable
public class ProductPropertyPK implements Serializable {
#Basic(optional = false)
#NotNull
#Column(name = "product_id", insertable = false, updatable = false)
private int productId;
#Basic(optional = false)
#NotNull
#Column(name = "property_id", insertable = false, updatable = false)
private int propertyId;
...
}
It works fine for 1, 10, 100 products, but somewhere there is an error, because for 1000 and more products throws error:
Caused by: java.lang.StackOverflowError
at java.util.HashMap.getEntry(HashMap.java:443)
at java.util.HashMap.containsKey(HashMap.java:434)
at java.util.HashSet.contains(HashSet.java:201)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4141)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:938)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:916)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:1964)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4178)
at org.eclipse.persistence.mappings.CollectionMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(CollectionMapping.java:426)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:1964)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4178)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:938)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:916)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:1964)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4178)
at org.eclipse.persistence.mappings.CollectionMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(CollectionMapping.java:426)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:1964)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4178)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:938)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:916)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:1964)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4178)
...
when i'm creating ProductProperty, i'm setting product and property in ProductProperty, and adding to collection for bidirection in Product and Property.
where i could make a mistake?

Looks like your object model complexity or depth is just difficult to traverse within your JVM's stack limits. As it is, every entity seems reachable from every other entity, which causes problems when traversed recursively. Try increasing the -Xss setting. You might also reduce the interconnectivity, such as removing one of the OneToMany mappings and query for it directly instead of storing it in the Product or Property mapping. You might also file an enhancement with EclipseLink to traverse the object graph using a stack instead of recursively.

Related

Hibernate criteria cannot fetch rows could not resolve property

Hi i have these 2 basic entity mapping for postgresql db, and i have wrote criteria for
fetching all activated user which have same key it is showing this error
org.hibernate.QueryException: could not resolve property: key.id of: com.sar.dfsapp.modal.ActivatedUser
#Entity
#Table(name = "activated_user")
public class ActivatedUser implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, length = 11)
private long id;
#ManyToOne
#JoinColumn(name = "key_id", nullable = false)
private Key key;
}
#Entity
#Table(name = "key")
public class Key implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, length = 11)
private long id;
#Column(name = "key_code", nullable = false)
private String keyCode;
}
Below is my criteria i have tried.
Criteria c = getSession().createCriteria(ActivatedUser.class);
c.add(Restrictions.eq("key.id", id));
List<ActivatedUser> result = c.list();
try this :
Criteria c = getSession().createCriteria(ActivatedUser.class);
Criteria keyCriteria = criteria.createCriteria("key", CriteriaSpecification.INNER_JOIN);
keyCriteria.add(Restrictions.eq("id", id));
List<ActivatedUser> result = c.list();
it there the same error ?

JPA query filtered by a collection's property in a OneToMany relationship

hope somebaody can help me. I have two entities related OneToMany.
First:
#Entity
#Table(name = "repartos")
#XmlRootElement
public class Repartos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "fecha")
#Temporal(TemporalType.DATE)
private Date fecha;
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "repartoId")
public List<RepartosDetalle> repartosDetalleList;
.....
And then the another one:
#Entity
#Table(name = "repartos_detalle")
#XmlRootElement
public class RepartosDetalle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#JoinColumn(name = "reparto_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Repartos repartoId;
#Column(name = "descargado")
#Convert(converter = BooleanOneZeroConverter.class)
private boolean descargado;
public RepartosDetalle() {
}
public RepartosDetalle(Repartos repartoId) {
this.repartoId = repartoId;
}
public Repartos getRepartoId() {
return repartoId;
}
public void setRepartoId(Repartos repartoId) {
this.repartoId = repartoId;
}
public boolean isDescargado() {
return descargado;
}
public void setDescargado(boolean descargado) {
this.descargado = descargado;
}
}
What I try to get is all the Repartos given a date and where they have al least one RepartosDetalle with the property descargado=TRUE.
I've been trying with the following query but I do't get any result.
#Override
public List<Repartos> buscarPorFechaDescargados(Date searchDate) {
Query q = em.createQuery("SELECT e FROM Repartos e "
+ "WHERE e.fecha = :searchDate"
+ " AND e.repartosDetalleList.descargado=TRUE");
q.setParameter("searchDate", searchDate);
return q.getResultList();
}
Is there a proper way to make this query using one of the collection's property value?
Thanks a lot and nice weekend.
Try to use JOIN operator on these 2 entities - Repartos and RepartosDetalle :
SELECT e FROM Repartos e JOIN RepartosDetalle d
WHERE e.fecha = :searchDate
AND d.descargado = TRUE

Marshalling Error: failed to lazily initialize a collection of role (...), no session or session was closed

I`m using Eclipse RCP with EJB exposed like WebServices. My services beans looks like follows
#Override
#SuppressWarnings("unchecked")
public List<Author> listAll() {
final Query query = this.entityManager.createQuery("from Author");
final List<Author> authors = query.getResultList();
return authors;
}
The two entityes are:
#Entity
#Table(name = "books")
public class Book implements Serializable {
#Id
private int id;
private String title;
private String summary;
private String isbn;
#Column(name = "published")
private Date publishingDate;
#Column(name = "created")
private Date createdAt;
#Column(name = "updated")
private Date modifiedAt;
#ManyToMany
#JoinTable(
name = "book_authors",
joinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "author_id", referencedColumnName = "id"))
private List<Author> authors;
and
#Entity
#Table(name = "authors")
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "last_name")
private String lastName;
#Column(name = "created")
private Date createdAt;
#Column(name = "updated")
private Date modifiedAt;
#ManyToMany
#JoinTable(
name = "book_authors",
joinColumns = #JoinColumn(name = "author_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id"))
private List<Book> books;
In my TestWSCLient i`m trying to do something like this
AuthorServiceBeanServiceLocator locator = new AuthorServiceBeanServiceLocator();
AuthorServiceBean service = locator.getAuthorServiceBeanPort();
Author[] authors = service.listAll();
for(Author a : authors){
System.out.println(a.getFirstName());
}
and I`m getting this error
{....//xml.apache.org/axis/}stackTrace:Marshalling Error: failed to lazily initialize a collection of role: ro.cgs.entities.Author.books, no session or session was closed
I`m mention that if I do not make the Many-To-Many relationship all works fine. Can anybody tell me what should I do to fix this problem ?
I use Hibernate for persistence.
Thanks.

JPA, compound key with foreign keys + persist oneToMany

I'm trying to do something with JPA that'll use a lot on a project but I'm stuck.
I have 2 entities + a kind of "glue" entity, I'll call them
ClassA
ClassB
Glue
I want to add a new ClassA with new Glues set in it's list, ClassB's already exist.
That would do something like :
ClassA 1 | Glue 1 1 | ClassB 1
ClassA 1 | Glue 1 2 | ClassB 2
ClassA 1 | Glue 1 3 | ClassB 3
ClassA 1 | Glue 1 4 | ClassB 4
So as said ClassA and all Glues are to be inserted, ClassA has a List with the new Glues to be inserted.
Here they are :
#Entity
public class ClassA implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
(...)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "classA")
private List<Glue> glueList;
(...)
}
#Entity
public class ClassB implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
(...)
}
#Entity
public class Glue implements Serializable {
#EmbeddedId
protected GluePK gluePK;
#JoinColumn(name = "id_class_a", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
#ManyToOne(optional = false)
private ClassA classA;
#JoinColumn(name = "id_class_b", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
#ManyToOne(optional = false)
private ClassB classB;
(...)
}
#Embeddable
public class GluePK implements Serializable {
#Basic(optional = false)
#NotNull
#Column(name = "id_class_a", nullable = false)
private int idClassA;
#Basic(optional = false)
#NotNull
#Column(name = "id_class_b", nullable = false)
private int idClassB;
(...)
}
When I try to persist my ClassA I'm getting something like :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails (bdd.glue, CONSTRAINT constraint_name FOREIGN KEY (id_class_a) REFERENCES ClassA (id) ON DELETE NO ACTION ON UPDATE NO ACTION)
I understand that he complains that Glues dont have ClassA's reference set but I'd like him to fill it just then he persists ClassA.
Is this achievable?
If not what's the best way to do it?
I'd like to stay on JPA without any specific vendor tricks (I'm using eclipselink) but if some vendor can do it easily I'll go for it.
Thanks!
I would remove the EmbeddedId, use an IdClass instead and just add the #Id to the #ManyToOne mappings.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0
Or maybe even give Glue an id of its own.
You could also remove the insertable = false, updatable = false from the #ManyToOne and move them to the EmbeddedId.

Not Null Property Exception with JPA onetoone mapping

I am trying my way around JPA but I cant get this to work the way I understand them.
Its the onetoone bidirectional mapping between an Order and an OrderInvoice class which is a required
association
My entities are marked as this
#Entity
#Table(name = "Orders")
public class Order {
#Id
#GeneratedValue
#Column(name = "ORDER_ID")
private int orderId;
#OneToOne(optional=false,cascade=CascadeType.ALL, mappedBy="order", targetEntity=OrderInvoice.class)
private OrderInvoice invoice;
}
#Entity
#Table(name = "ORDER_INVOICE")
public class OrderInvoice {
#Id
#GeneratedValue
#Column(name = "INVOICE_ID", nullable = false)
private int invoiceId;
#OneToOne(optional = false)
#JoinColumn(name="ORDER_ID")
private Order order;
}
My test class is like this.
#Test
public void createOrder() {
Order order = createOrderImpl();
assertNotNull(order);
}
private Order createOrderImpl() {
OrderInvoice orderInvoice = new OrderInvoice(new Date(), 100.0, null,
null, new Date());
Order order = new Order(100.0, "JOHN Doe's Order", new Date(), new Date(),orderInvoice);
orderDao.create(order);
return order;
}
But I am encountering below problem when I run my Test
javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: order.OrderInvoice.order
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: order.OrderInvoice.order
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:95)
try to
orderInvoice.setOrder(order);
orderDao.create(order);