Can't persist my objects - java

here's is the problem
I have a java class Agence that has a #ManytoOne relationship with my class Reseau .
there is my Agence code :
package ma.kafil.bank;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Agence implements Serializable{
private int idAgence;
private String labelle;
private Reseau reseau;
public Agence(String labelle) {
this.labelle = labelle;
}
public Agence() {
}
#ManyToOne
public Reseau getReseau() {
return reseau;
}
public void setReseau(Reseau reseau) {
this.reseau = reseau;
}
#Id
#GeneratedValue
public int getIdAgence() {
return idAgence;
}
public void setIdAgence(int idAgence) {
this.idAgence = idAgence;
}
public String getLabelle() {
return labelle;
}
public void setLabelle(String labelle) {
this.labelle = labelle;
}
}
and my Reseau Class :
package ma.kafil.bank;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Reseau implements Serializable{
private int idReseau;
private String Libelle;
private ArrayList<Agence> Agences = new ArrayList();
//Constructor without arguments
public Reseau() {
}
public Reseau(String Libelle) {
this.Libelle = Libelle;
}
public void ajouterAgence(Agence a){
Agences.add(a);
}
#Id
#GeneratedValue
public int getIdReseau() {
return idReseau;
}
public void setIdReseau(int idReseau) {
this.idReseau = idReseau;
}
public String getLibelle() {
return Libelle;
}
public void setLibelle(String Libelle) {
this.Libelle = Libelle;
}
#OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, mappedBy="reseau")
public Collection<Agence> getAgences() {
return Agences;
}
public void setAgences(ArrayList<Agence> Agences) {
this.Agences = Agences;
}
public void addAgence(Agence a){
this.Agences.add(a);
}
}
And Finally the main class :
package ma.kafil.bank;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String [] args){
//Creating Entity Manager
//persistence-unit name="test"
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
//beginning the transaction
em.getTransaction().begin();
//Creating a new Reseau r with r.labbelle = "Centre" and r.id=1
Reseau r = new Reseau("Centre");
r.setIdReseau(1);
//Creating a new Agence a
Agence a = new Agence("Nom Agence");
a.setIdAgence(2);
//adding a to my Reseau (What's the problem with that ?? )
r.addAgence(a);
em.persist(r);
a.setIdAgence(1990);
a.setReseau(r);
em.persist(a);
em.getTransaction().commit();
//closing em and emf
em.close();
emf.close();
}
}
Here is the stack trace :
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: ma.kafil.bank.Reseau
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:637)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:226)
at ma.kafil.bank.Main.main(Main.java:30)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: ma.kafil.bank.Reseau
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:79)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:220)
... 1 more
Java Result: 1
And here is persistence.xml :
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class> ma.kafil.bank.Agence</class>
<class> ma.kafil.bank.Reseau</class>
<properties>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/awbawards"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit> </persistence>
Thanks in Advance

In your reseau class, the agences list is never initialized, it should be:
#Entity
public class Reseau implements Serializable{
private int idReseau;
private String Libelle;
private List<Agence> Agences = new ArrayList<Agence>();
Also your field, getter and setter declarations should all use the type List, not Collection not ArrayList and your field shouldn't start with a capital letter (java naming conventions):
private List<Agence> agences = new ArrayList<Agence>();
public List<Agence> getAgences() {
return agences;
}
public void setAgences(List<Agence> agences) {
this.agences = agences;
}

The problem is when you do r.addAgence(a); it is possible that list of Agences is null for few Reseau. A quick fix can be done in your add method -
public void addAgence(Agence a){
if(Agences==null){//do this check to avoid null pointer
Agences = new ArrayList<Agence>();
}
this.Agences.add(a);
}

Since you edited your question I'll post it as an answer.
Based on this reply https://stackoverflow.com/a/2442036/1094430 you should not set your ID by code if you DB is set to auto generate them.
So remove
r.setIdReseau(1);
...
a.setIdAgence(2);
...
a.setIdAgence(1990);
from your code and then do the persist.

Try with this main:
package ma.kafil.bank;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String [] args){
//Creating Entity Manager
//persistence-unit name="test"
EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
EntityManager em = emf.createEntityManager();
//beginning the transaction
em.getTransaction().begin();
//Creating a new Reseau r with r.labbelle = "Centre" and r.id=1
Reseau r = new Reseau("Centre");
r.setIdReseau(1);
//Creating a new Agence a
Agence a = new Agence("Nom Agence");
a.setIdAgence(2);
a.setIdAgence(1990);
a.setReseau(r);
//adding a to my Reseau (What's the problem with that ?? )
r.addAgence(a);
em.persist(r);
em.getTransaction().commit();
//closing em and emf
em.close();
emf.close();
}
}
It should work, because both objects are linked.

Related

How to properly set up hibernate persistence with a java model

I am attempting to write a rest API to interface with a MariaDB. I feel like I am most of the way there however I am recieving the following error:
java.lang.IllegalArgumentException: Unknown entity: Models.User
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:808)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at test.Application.addUser(Application.java:40)
at test.Application.main(Application.java:18)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:542)
at java.base/java.lang.Thread.run(Thread.java:834)
I imagine that this is because I have incorrectly configured the user class in the persistence.xml file in resources/META-INF. Below are the relavent inter relating files:
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="potholeAPI" transaction-
type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Models.User</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/PotholeDB?
useUnicode=true&useJDBCCompliantTimezoneShift
=true&useLegacyDate
timeCode=false&serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
</properties>
</persistence-unit>
User.java
package Models;
import org.hibernate.annotations.Entity;
import org.hibernate.annotations.Table;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
#Table(appliesTo = "Users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id", unique = true)
private int id;
#Column(name = "name", unique = true)
private String name;
#Column(name = "created_date")
private int created_date;
getters and setters....
and the main and driver for my testing
Application.java
package test;
import Models.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#SpringBootApplication
public class Application {
private static EntityManagerFactory ENTITY_MANAGER_FACTORY =
Persistence.createEntityManagerFactory("potholeAPI");
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
addUser(1, "jim");
addUser(2, "bob");
getUser(1);
getUsers();
ENTITY_MANAGER_FACTORY.close();
}
public static void addUser(int id, String name) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
Date date = new Date();
try {
et = em.getTransaction();
et.begin();
User user = new User();
user.setId(id);
user.setName(name);
user.setCreated_date(date.getDate());
em.persist(user);
} catch (Exception ex) {
if (et != null) {
et.rollback();
}
ex.printStackTrace();
} finally {
em.close();
}
}
public static void getUser(int id) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT u FROM User u WHERE u.id = :userID";
TypedQuery<User> tq = em.createQuery(query, User.class);
tq.setParameter("userID", id);
User user = null;
try {
user = tq.getSingleResult();
System.out.println(user.getName() + " ");
} catch (NoResultException e) {
System.out.println("ex");
e.printStackTrace();
} finally {
em.close();
}
}
public static void getUsers() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT u FROM User u WHERE u.id IS NOT NULL";
TypedQuery<User> tq = em.createQuery(query, User.class);
List<User> users;
try {
users = tq.getResultList();
users.forEach(user-> System.out.println(user.getName()+ " "));
} catch (NoResultException e) {
System.out.println("ex");
e.printStackTrace();
} finally {
em.close();
}
}
}
My suspicion is that I screwed up the xml file however I am new to spinning up an API like this so I am not fully confident.
Tablename is 'User',so User.java->#Table(appliesTo = "Users") should be #Table(appliesTo = "User")

org.hibernate.QueryException: Unable to resolve path, unexpected token [trying to use left join]

I've created 2 entity classes:
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "fr")
public class FR {
#Id
#Column(name = "id")
private String id;
#Column(name = "pid")
private String pId;
#Column(name = "pname")
private String pName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
and
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ar")
public class AR {
#Id
#Column(name = "id")
private String id;
#Column(name = "value1")
private String value1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
}
and I'm trying to join these tables to fetch the record.
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123");
but getting an exception:
org.hibernate.QueryException: Unable to resolve path [FR.id], unexpected token [FR] [from entities.FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123]
and when I'm removing FR from the query
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where id=123 or pId=123");
getting another exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from entities.FR left join AR on FR.pId = AR.id where id=123 or pId=123]
I'm in a learning stage of Hibernate and don't know what to do now.
If you've any other info regarding Left Join or the other Joins then please share that too.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/examples?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root#123</property>
<property name="hibernate.show_sql">true</property>
<mapping class="entities.FR"/>
<mapping class="entities.AR"/>
</session-factory>
</hibernate-configuration>
Main Class
package hibernate.joins;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateJoins {
public static void main(String[] args) {
SessionFactory sessionFactory = getSessionFactory();
Session session = sessionFactory.openSession();
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id and ( FR.id=123 or FR.pId=123 )");
List list = qry.list();
list.forEach(System.out::println);
session.close();
sessionFactory.close();
}
public static SessionFactory getSessionFactory () {
SessionFactory sessionFactory = new Configuration().configure("configurations/hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
}
Since you are using ON clause in your query, therefore, you can not to use where clause separately. Just keep on adding the condition using AND or OR clause(whichever is applicable)

Why can't I query an entity with a TYPE-WHERE clause matching the entity type in JPA 2.1?

Queries in the form of an entity class A in the form of
SELECT a from A a WHERE TYPE(a) = A
fail with
could not resolve property: class of: de.richtercloud.type.operator.nonsense.A [SELECT a from de.richtercloud.type.operator.nonsense.A a WHERE TYPE(a) = A]
which I don't understand because restricting A to A should exclude all superclass instances which aren't As as well as subclass instances.
Example:
package de.richtercloud.type.operator.nonsense;
import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
/**
* Illustrates the problem/misunderstanding that storing an {#link A} and
* querying it with a {#code WHERE TYPE([identifier]) = A} fails with
* {#code org.hibernate.QueryException: could not resolve property:
* class of: de.richtercloud.type.operator.nonsense.A}.
* #author richter
*/
public class NewMain {
private final static File DATABASE_DIR = new File("/tmp/type-operator-nonsense");
private final static String DERBY_CONNECTION_URL = String.format("jdbc:derby:%s", DATABASE_DIR.getAbsolutePath());
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws SQLException {
//setup database
EntityManagerFactory entityManagerFactory = null;
try {
Map<Object, Object> entityManagerFactoryMap = new HashMap<>();
entityManagerFactoryMap.put("javax.persistence.jdbc.url",
String.format("%s;create=%s", DERBY_CONNECTION_URL, !DATABASE_DIR.exists()));
entityManagerFactory = Persistence.createEntityManagerFactory("type-operator-nonsense",
entityManagerFactoryMap);
//show issue
EntityManager entityManager = entityManagerFactory.createEntityManager();
A a = new A(1L, "b");
entityManager.getTransaction().begin();
entityManager.persist(a);
entityManager.flush();
Query query = entityManager.createQuery("SELECT a from A a WHERE TYPE(a) = A");
List<?> queryResult = query.getResultList();
entityManager.getTransaction().commit();
System.out.println(queryResult.size());
}finally {
if(entityManagerFactory != null) {
entityManagerFactory.close();
}
}
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="type-operator-nonsense" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>de.richtercloud.type.operator.nonsense.A</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:/tmp/type-operator-nonsense"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
with org.hibernate:hibernate-entitymanager:5.1.0.Final and org.apache.derby:derby:10.11.1.1
A is a POJO in this example which doesn't involve inheritance, that shouldn't matter for the restriction I expect (although it wouldn't make sense to apply it if there's no inheritance):
package de.richtercloud.type.operator.nonsense;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class A implements Serializable {
private static final long serialVersionUID = 1L;
private String b;
#Id
private Long id;
public A() {
}
public A(Long id, String b) {
this.id = id;
this.b = b;
}
public void setB(String b) {
this.b = b;
}
public String getB() {
return b;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
This behaviour occurs due to a hibernate bug https://hibernate.atlassian.net/browse/HHH-10653. The example above works fine with OpenJPA.
TYPE() can only be used in inheritance mapping.
Is A a class in a inheritance mapping and A either the route class with #Inheritance or A extends a class that has #Inheritance declared?
Example.
#Inheritance
#Entity
public class Project
#Entity
public class DesignProject extends Project
#Entity
public class QualityProject extends Project
#Entity
public class SoftwareProject extends Project
Now you can use TYPE()
SELECT p
FROM Project p
WHERE TYPE(p) = DesignProject OR TYPE(p) = QualityProject

org.hibernate.MappingException: Unknown entity - What is the root cause?

I am new to hibernate. i am following a tutorial and trying to execute a simple code but I am getting below error.
org.hibernate.MappingException: Unknown entity:
I am using annotations and configuration file also did exactly according the tutorials. I have googled but didn't get the correct answer
This is my code
package org.anne;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class Demo {
public static void main(String[] args) {
Paper p = new Paper();
p.setPname("indu");
SessionFactory sf = HibernateUtil.getSessionFactory();
Session ses = sf.openSession();
Transaction tr = ses.beginTransaction();
ses.save(p);
tr.commit();
ses.close();
sf.close();
}
}
package org.anne;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
static SessionFactory sf;
public static SessionFactory getSessionFactory()
{
Configuration cf = new Configuration();
cf.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder srv = new StandardServiceRegistryBuilder();
StandardServiceRegistry sr = srv.applySettings(cf.getProperties()).build();
sf = cf.buildSessionFactory(sr);
return sf;
}
}
package org.anne;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "PAPER")
public class Paper {
int pid;
String pname;
#Id
#Column(name = "PID")
#GeneratedValue(strategy = GenerationType.AUTO)
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
#Column(name = "PNAME")
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name = "connection.driver_class">com.mysql.jdbc.Driver</property>
<property name = "connection.url">jdbc:mysql://localhost:3306/test</property>
<property name = "connection.username">root</property>
<property name = "connection.password">abc123</property>
<property name = "hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name = "hibernate.show_sql">true</property>
<mapping class = "org.anne.Paper" />
</session-factory>
</hibernate-configuration>
If you boot Hibernate yourself, make sure to use the AnnotationConfiguration class instead of the Configuration class. Here is an example using the (legacy) HibernateUtil approach:
package hello;
import org.hibernate.*;
import org.hibernate.cfg.*;
import test.*;
import test.animals.Dog;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
} catch (Throwable ex) {
// Log exception!
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession()
throws HibernateException {
return sessionFactory.openSession();
}
}
More here https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html#setup-configuration

jpa subgraph and MappedSuperclass throws Unknown entity

I have a silly problem with subgraphs. It's my firsttime with EntityGraphs.
I have following classes im my common lib:
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.ManyToMany;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public abstract class NamedDomainObjectWithFiles extends NamedDomainObject {
/**
*
*/
private static final long serialVersionUID = 1L;
#ManyToMany(cascade = CascadeType.ALL)
private Set<File> files;
public Set<File> getFiles() {
return files;
}
public void setFiles(Set<File> files) {
this.files = files;
}
}
and
import java.util.Date;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#NamedQueries({ #NamedQuery(name = File.findAll, query = "SELECT f FROM File f ORDER BY f.createdOn"),
#NamedQuery(name = File.findByName, query = "SELECT f FROM File f WHERE f.name = :name") })
#NamedEntityGraphs({
#NamedEntityGraph(name = File.EG_LoadRoles, attributeNodes = { #NamedAttributeNode("roles") }),
#NamedEntityGraph(name = File.EG_LoadALL, includeAllAttributes=true)
})
#Entity
public class File extends NamedDomainObject{
/**
*
*/
private static final long serialVersionUID = 3696244073145217983L;
public static final String findByName = "File.findByName";
public static final String findAll = "File.findAll";
public static final String EG_LoadRoles = "File.EG_LoadRoles";
public static final String EG_LoadALL = "File.EG_LoadALL";
#ManyToMany
private Set<Role> roles;
#ManyToMany
private Set<FileCategory> fileCategories;
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Set<FileCategory> getFileCategories() {
return fileCategories;
}
public void setFileCategories(Set<FileCategory> fileCategories) {
this.fileCategories = fileCategories;
}
}
and the class Kunde in my war
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.NamedSubgraph;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import de.xxx.common.domain.Address;
import de.xxx.common.domain.NamedDomainObjectWithFiles;
#NamedQueries({ #NamedQuery(name = Kunde.findAll, query = "SELECT b FROM Kunde b where b.activ=1 ORDER BY b.name"),
#NamedQuery(name = Kunde.findByName, query = "SELECT b FROM Kunde b WHERE b.name = :name") })
#NamedEntityGraphs({
#NamedEntityGraph(name = Kunde.EG_loadAll,
attributeNodes = {
#NamedAttributeNode(value = "files", subgraph = Kunde.SG_filesLoadAll)
},
subgraphs = {
#NamedSubgraph(name = Kunde.SG_filesLoadAll,
attributeNodes = {
#NamedAttributeNode("roles"),
#NamedAttributeNode("fileCategories")
}
)
}
)
})
#Entity
public class Kunde extends NamedDomainObjectWithFiles {
/**
*
*/
private static final long serialVersionUID = -7339308550470317787L;
public static final String findByName = "Kunde.findByName";
public static final String findAll = "Kunde.findAll";
public static final String EG_loadAll = "Kunde.EG_loadAll";
public static final String SG_filesLoadAll = "Kunde.SG_filesLoadAll";
#OneToMany(cascade = CascadeType.ALL, mappedBy = "kunde", orphanRemoval = true)
private List<Objekt> objekte;
public Kunde() {
}
public List<Objekt> getObjekte() {
return objekte;
}
public void setObjekte(List<Objekt> objekte) {
this.objekte = objekte;
}
}
Everything works fine until i try to activate the subgraph 'Kunde.SG_filesLoadAll' in my class Kunde. During startup i get following exception:
org.hibernate.MappingException: Unknown entity: de.xxx.common.domain.NamedDomainObjectWithFiles
If i only set
#NamedEntityGraph(name = Kunde.EG_loadAll,
attributeNodes = {
#NamedAttributeNode(value = "files")
}
no exception is thrown during startup.
I hope you can help me.
I tested this code with the same result on wildfly 8.1 and 9.0.1.
Michael
#Edit:
Here is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
<jta-data-source>java:jboss/datasources/ObjektmanagementDS</jta-data-source>
<jar-file>lib/common-0.0.1.jar</jar-file>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/objektmanagement?UseUnicode=true&characterEncoding=utf8" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>

Categories

Resources