JPA EclipseLink uses a non-entity as target entity in the relationship attribute - jpa

I get the following error when i try to deploy my application on glassfish 4.1:
[class com.sample.model.Profile] uses a non-entity [class com.sample.model.ProfileEventMapping] as target entity in the relationship attribute [field events].
The tables for both entities are getting created in the database.
Profile:
#Entity
public class Profile
...
#OneToMany(mappedBy = "profile", orphanRemoval = true)
private Set<ProfileEventMapping> events = new HashSet<>();
ProfileEventMapping:
#Entity
public class ProfileEventMapping
...
#NotNull
#ManyToOne
private Profile profile;
and in my persistence.xml i choose to include all entities:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
anybody an idea?

I renamed the hole project with just find and replace. The problem was that in the ear project was a dependency to an old .war file which had an persistence.xml in it. Just deleted the old dependency and BOOM. Now i just need to fix the other error messages ("com.Profile[id = null] is not a known entity type")

Related

Specifying One-to-one relationship foreign key in JPA

I am implementing REST API using Spring and JPA. Consider for example the following scenario where there are Project and Department entities where a Project belongs to a single Department. I would normally have a Department object referenced in Project Pojo, with a #OneToOne annotation.
When creating a Project through REST API (where a Department is already created), I am currently getting departmentID as an attribute from the user, loading Department object using the ID, associating it to the Project and then saving the Project instance using JPA. Is there a way to avoid this and directly save the Project by specifying department ID directly?
Create two entity classes like
class Department{
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL,
mappedBy = "department")
Project project;
}
class Project{
}

EntityGraph - You must define a fetch group manager at descriptor in order to set a fetch group on the query

I would like use Entity Graphs in EclipseLink and GlassFish.
#Entity
#NamedQueries({
#NamedQuery(name = "invoice.all", query = "SELECT i FROM Invoice i")})
#NamedEntityGraph(name = "graph.invoice",
attributeNodes = {#NamedAttributeNode("invoiceNum")})
#Table(name = "INVOICE")
public class Invoice implements Serializable {
private int id;
private String bizonylatSzam;
...
}
EntityManager em = getEntityManagerFactory().createEntityManager();
EntityGraph eg = em.createEntityGraph("graph.invoice");
List<Invoice> invoiceList = em.createNamedQuery("invoice.all").setHint("javax.persistence.fetchgraph", eg).getResultList();
If I use javax.persistence.loadgraph graph everything OK, but if i use javax.persistence.fetchgraph I have an exception:
org.eclipse.persistence.exceptions.QueryException
Exception Description: You must define a fetch group manager at descriptor (Invoice) in order to set a fetch group on the query (invoice.all)
In EclipseLink webpage write:
... using Weaving technologi..
Weaving and Java EE Application Servers
The default EclipseLink weaving behavior applies in any Java EE
JPA-compliant application server using the EclipseLink JPA persistence
provider. To change this behavior, modify your persistence.xml file
(for your JPA entities or POJO classes) to use EclipseLink JPA
properties, EclipseLink JPA annotations, or both.
I dont understand what is the problem. :(

JPA #OneToOne with an Entity that is not exported from it's OSGi Bundle

I am trying to set up a simple foreign key relation ship using JPA in a rather complex OSGi environment.
The two entities I want to use are structured in bundles like so:
masterbundle
|->org.masterpackage.persistence
|-> MasterEntityDto.java
slavebundle
|->org.slavepackage.persistence
|-> SlaveEntity.java
SlaveEntity want to refer to the MasterEntityDtolike so
#Entity(name = "SlaveEntity")
public class SlaveEntity {
#Id
#Column(name = "slaveID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne
#JoinColumn(name = "masterEntity_id")
private MasterEntity masterEntity;
// snip..
}
Now, this fails because masterbundle is not exporting the MasterEntityDto (or its package), I think. We are using the Service Aspect of OSGi, masterBundle is provide-interface-ing a service that is using the Dto instead of the Dto.
The exception I see when the bundle starts says, among other things org.osgi.framework.BundleException: Unresolved constraint in bundle slavebundle [121]: Unable to resolve 121.8: missing requirement [121.8] osgi.wiring.package;
Question: How do I create a #OneToOne relation from SlaveEntity to MasterEntityDto? Is this not possible in when using the OSGi service platform and I only expose services and not whole bundles / packages?
Edit1
As per request: MasterEntityDto has nothing fancy.
#Entity(name = "MasterEntityDto")
public class MasterEntityDto {
#Id
#Column(name = "id", length = 128)
private String masterId;
// snip
}
I would want JPA to make a SlaveEntity - table with columns SlaveId (which is this tables PK) and masterEntity_id which would act as foreign key, pointing to table MasterEntityDto's id column.
The packages containing domain classes (such as MasterEntityDto) do need to be exported, so that the JPA bundle can have visibility to instantiate them.
Because of this it is very important to keep such packages separated from other packages containing implementation/logic code, which should be private.

Mapping xml to jpa entities using JAXB

Isn't it possible to map xml to jpa entities using JAXB? Will Eclipselink Moxy be helpful?
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
Yes you can map JPA entities to XML, and the following are some ways that EclipseLink JAXB (MOXy) makes this easier.
1. Bidirectional Mappings
Customer
import javax.persistence.*;
#Entity
public class Customer {
#Id
private long id;
#OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
private Address address;
}
Address
import javax.persistence.*;
import org.eclipse.persistence.oxm.annotations.*;
#Entity
public class Address implements Serializable {
#Id
private long id;
#OneToOne
#JoinColumn(name="ID")
#MapsId
#XmlInverseReference(mappedBy="address")
private Customer customer;
}
For More Information
http://blog.bdoughan.com/2010/07/jpa-entities-to-xml-bidirectional.html
http://bdoughan.blogspot.com/2010/08/creating-restful-web-service-part-25.html
2. Mapping Compound Key Relationships
We normally think of mapping a tree of objects to XML, however JAXB supports using the combination of #XmlID/#XmlIDREF to map relationship between nodes representing a graph. The standard mechanism is one key, to one foreign key. JPA supports the concept of composite keys and so does MOXy using #XmlKey and #XmlJoinNodes (similar to #XmlJoinColumns in JPA).
Employee
#Entity
#IdClass(EmployeeId.class)
public class Employee {
#Id
#Column(name="E_ID")
#XmlID
private BigDecimal eId;
#Id
#XmlKey
private String country;
#OneToMany(mappedBy="contact")
#XmlInverseReference(mappedBy="contact")
private List<PhoneNumber> contactNumber;
}
PhoneNumber
#Entity
public class PhoneNumber {
#ManyToOne
#JoinColumns({
#JoinColumn(name="E_ID", referencedColumnName = "E_ID"),
#JoinColumn(name="E_COUNTRY", referencedColumnName = "COUNTRY")
})
#XmlJoinNodes( {
#XmlJoinNode(xmlPath="contact/id/text()", referencedXmlPath="id/text()"),
#XmlJoinNode(xmlPath="contact/country/text()", referencedXmlPath="country/text()")
})
private Employee contact;
}
For More Information
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA/CompoundPrimaryKeys
3. MOXy allows for Composite and Embedded Keys
JPA can also use embedded key classes to represent composite keys. MOXy also supports this style of composite keys.
For More Information
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA/EmbeddedIdClass
4. EclipseLink JAXB (MOXy) and EclipseLink JPA Have Shared Concepts
EclipseLink provides both JAXB and JPA implementations that share a common core. This means that they share many of the same concepts, such as:
Virtual Access Methods
EclipseLink supports the concept of virtual properties. This is useful when creating a multi-tenant application where you want per-tenant customizations. This concept is upported in both EclipseLink's JPA and JAXB implementations.
http://blog.bdoughan.com/2011/06/moxy-extensible-models-multi-tenant.html
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Extensibility

EclipseLink/JPA #OneToMany Backpointer Cardinality Error

I am trying to generate a unidirectional one-to-many mapping between two JPA entities. In my ChatRoom class, I have a Vector<User> type object that represents Users in a ChatRoom. I am trying to create a one-to-many mapping, based on userId (in the User class). Here is my sample code:
#Entity
public class ChatRoom {
#Id
#GeneratedValue
private int chatRoomID;
#OneToMany(mappedBy="userID")
private Vector<User> users;
// A no-argument constructor is required for EclipseLink to instantiate the persistence object properly.
public ChatRoom() {}
// Getter/Setter section
}
Here is the User class:
#Entity
public class User {
#Id
#GeneratedValue
private int userID;
private String username;
// Getter/Setter section
}
When I try to generate the tables from these entities in Eclipse, I get the following error:
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ChatJPA] failed.
Internal Exception: Exception [EclipseLink-7244] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class iosoa.entity.ChatRoom] and [class iosoa.entity.User]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:126)
Do you have any ideas on how to resolve this problem? Thanks for your help.
A few things,
Your mappedBy is wrong, a mappedBy for a OneToMany must be a ManyToOne. I would recommend you add the ManyToOne back, or use a #JoinTable, if you do not wish to, then you could use an #JoinColumn and no mappedBy.
Vector is not valid in JPA, you must use List, Set or Map. You can still use a Vector as your implementation class. If you really want to use Vector, then EclipseLink will support this, but you must make your mapping EAGER.
I guess It's problem of mappedBy annotation. It should be: "private ChatRoom chatRoom;" in your user class. And in mappedBy try to write this variable.
P.S. If you don't have link to CharRoom in your relation, than you for sure have join table. Then you should use #JoinTable annotation and #OneToMany without mappedBy.