Persistance Unit Error More 2 EntityManagers 1 Persitance Unit? - java

Hi im working with Java EE 7. The code got the following structure.
model --> Entity Beans
business --> Service classes for the model (each contains a EntityManager)
presentation --> Named SessionScoped Beans with #EJB on the service
When i tested the program with just 1 service / EntityManager everything works fine but now when i added the second service class i got this error:
>
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [watchuwantPU] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class model.Tag] uses a non-entity [class java.lang.String] as target entity in the relationship attribute [field beschreibung].
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1950)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1941)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
persistence.xml
<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="watchuwantPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>watchuwant</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
FilmService.java
#Stateless
public class FilmService {
#PersistenceContext(name="watchuwantPU", unitName = "watchuwantPU")
private EntityManager em;
public void add(Film Film){
em.persist(Film);
}
public List<Film> findAll(){
return em.createQuery("select f from Film f order by f.id").getResultList();
}
}
LizenzPM.java
#SessionScoped
#Named
public class LizenzPM implements Serializable{
private String lizenzgeber;
private String lizenztyp;
private String lizenzurl;
private Date erteiltAm;
#EJB
private LizenzService service;
Film.java Entity
#Entity
public class Film implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String titel;
#OneToMany(mappedBy = "parent", cascade=CascadeType.ALL, orphanRemoval=true)
private List<Tag> tags = new LinkedList<>();
Tag.class Entity
#Entity
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(optional = false)
private String beschreibung;
private Film parent;

I think that the persistence unit name is watchuwantPU, not LizenzService. Check the #PersistenceContext annotation.

Related

Problems with java #GeneratedValue (strategy = GenerationType.IDENTITY) using MariaDB 10.4 and eclipselink

I am developing a REST web service in Java EE I am using: Glassfish 5.0 (build 25), MariaDB 10.4 and eclipselink (JPA 2.1)
here is my code:
commande_line table
CREATE TABLE IF NOT EXISTS `cooldb`.`commande_line` (
`id` INT NOT NULL AUTO_INCREMENT,
`quantity` INT NULL,
`discount` INT NULL,
`dish` INT NOT NULL,
`commande` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
INDEX `fk_commande_line_dish1_idx` (`dish` ASC),
INDEX `fk_commande_line_commande1_idx` (`commande` ASC),
CONSTRAINT `fk_commande_line_dish1`
FOREIGN KEY (`dish`)
REFERENCES `cooldb`.`dish` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_commande_line_commande1`
FOREIGN KEY (`commande`)
REFERENCES `cooldb`.`commande` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://java.sun.com/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_2.xsd">
<!-- Define Persistence Unit -->
<persistence-unit name="my_persistence_unit" transaction-type="JTA">
<jta-data-source>jdbc/mariadb</jta-data-source>
<class>com.yac.model.Address</class>
<class>com.yac.model.Commande</class>
<class>com.yac.model.CommandeLine</class>
<class>com.yac.model.Dish</class>
<class>com.yac.model.Dishtype</class>
<class>com.yac.model.Ingredient</class>
<class>com.yac.model.Payement</class>
<class>com.yac.model.Profil</class>
<class>com.yac.model.Restaurant</class>
<class>com.yac.model.Userapp</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>
commandeline entity
public class CommandeLine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "quantity")
private Integer quantity;
#Column(name = "discount")
private Integer discount;
#JoinColumn(name = "commande", referencedColumnName = "id")
#ManyToOne(optional = false)
private Commande commande;
#JoinColumn(name = "dish", referencedColumnName = "id")
#ManyToOne(optional = false)
private Dish dish;
//Constructor
// Setter and Getter
}
commandeline web service
#Stateless
#Path("commandeline")
public class CommandeLineFacadeREST extends AbstractFacade<CommandeLine> {
#PersistenceContext(unitName = "my_persistence_unit")
private EntityManager em;
public CommandeLineFacadeREST() {
super(CommandeLine.class);
}
#POST
#Override
#Consumes(MediaType.APPLICATION_JSON)
public void create(CommandeLine entity) {
super.create(entity);
}
#Override
protected EntityManager getEntityManager() {
return em;
}
}
AbstractFacade
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
}
The problem is when I test my web service with Postman and I try to insert a record with a POST request
here is what I receive as error message:
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: (conn=158) Table 'cooldb.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQ_GEN_SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?") ...
I don't understand why the problem with SEQUANCE when I use #GeneratedValue (strategy = GenerationType.IDENTITY).
When I change with #GeneratedValue (strategy = GenerationType.SEQUENCE) and I create the table with the following script:
CREATE SEQUENCE SEQUANCE START WITH 1 INCREMENT BY 1;
by applying the solution shown in : Table 'customerjpa.sequence' doesn't exist JPA
but the same probleme
thank you in advance for your help.
The problem is solved using Chris comments, i just add the following line in my persistence.xml file:
<property name="eclipselink.target-database" value="MySQL"/>
Thank you very much Chris.
So my new persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://java.sun.com/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_2.xsd">
<!-- Define Persistence Unit -->
<persistence-unit name="my_persistence_unit" transaction-type="JTA">
<jta-data-source>jdbc/mariadb</jta-data-source>
<class>com.yac.model.Address</class>
<class>com.yac.model.Commande</class>
<class>com.yac.model.CommandeLine</class>
<class>com.yac.model.Dish</class>
<class>com.yac.model.Dishtype</class>
<class>com.yac.model.Ingredient</class>
<class>com.yac.model.Payement</class>
<class>com.yac.model.Profil</class>
<class>com.yac.model.Restaurant</class>
<class>com.yac.model.Userapp</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="MySQL"/>
</properties>
</persistence-unit>
</persistence>
I just specified the database platform in MySQL in the persistence.xml file of the moment MariaDB is based on it, because MariaDB is not mentioned in the list.
If there are other suggestions do not hesitate thank you.
Another Solution:
Add ?useMysqlMetadata=true to your JDBC URL connection as bellow:
<property name="URL" value="jdbc:mariadb://[HOST]:[PORT]/[DB NAME]?useMysqlMetadata=true"/>
that will make MariaDB use MySQL meta data and then eclipselink will detect it as MySQL.

class package.X uses a non-entity package.Y as target entity in the relationship attribute field listOfQuestions

I am trying to create web aplication which connects on derby database in eclipse. I added JPA facet in project facets. When I try to generate tables from entities, I get an error. Here is the first bit of stacktrace:
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: org.eclipse.persistence.dynamic.DynamicClassLoader#2a742aa2
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [lv10example] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class ba.fet.rwa.lv10.domain.Answer] uses a non-entity [class ba.fet.rwa.lv10.domain.Question] as target entity in the relationship attribute [field listOfQuestions].
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:107)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.buildEntityManagerFactory(Main.java:94)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.execute(Main.java:80)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.main(Main.java:68)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [lv10example] failed.
Here is the code:
#Entity
public class Answer {
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
#Column(name = "id")
private int id;
private String text;
private boolean correctStatus;
#ManyToMany(cascade = CascadeType.PERSIST)
#JoinTable(name="QuestionAnswer",joinColumns=#JoinColumn(name="answerID",
referencedColumnName="id"), inverseJoinColumns=#JoinColumn(name="questionID",
referencedColumnName="id"))
private Collection<Question> listOfQuestions;
public Answer() {
id=0;
text="";
correctStatus=false;
listOfQuestions=null;
}
public Answer(int _id, String _text, boolean _correctStatus,Question question){
id=_id;
text=_text;
correctStatus=_correctStatus;
listOfQuestions.add(question);
}
... Getters and setters ...
}
Here is the other class:
#Entity
#Table(schema = "TEST")
public class Question {
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
#Column(name = "id")
private int id;
private String text;
private boolean answered;
private int points;
#ManyToMany(mappedBy="listOfQuestions")
private Collection<Quiz> listOfQuizzes;
#ManyToMany(mappedBy="listOfQuestions")
private Collection<Answer> listOfAnswers;
public Question() {
id=0;
text="";
answered=false;
points=0;
listOfAnswers=null;
}
public Question(int _id,String _text, int _points,Answer answer){
id=_id;
text=_text;
answered=false;
points=_points;
listOfAnswers.add(answer);
}
... Getters and setters ...
}
Here is 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="lv10example">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- <exclude-unlisted-classes>false</exclude-unlisted-classes> -->
<class>ba.fet.rwa.lv10.domain.Quiz</class>
<class>ba.fet.rwa.lv10.domain.Question</class>
<class>ba.fet.rwa.lv10.domain.Answer</class>
<class>ba.fet.rwa.lv10.domain.LoggedStatus</class>
<class>ba.fet.rwa.lv10.domain.Result</class>
<class>ba.fet.rwa.lv10.domain.User</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<!-- property name="eclipselink.ddl-generation" value="drop-and-create-tables" /-->
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527/sample;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
</properties>
</persistence-unit>
</persistence>
Can someone help me with this? There is certainly an error in here somewhere, but i cannot find it. Maybe it's the problem with jpa facet? I tried to debug this for 2 days from now, but with no luck. Sorry for my bad English. Thank you! :-)

JPA java.lang.ClassFormatError issue

I have an issue with starting the JPA and Derby project. I have the following error:
Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/Persistence
My Main.java is:
public class Main {
private static final String PERSISTENCE_UNIT_NAME = "customers";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory("todos");
EntityManager em = factory.createEntityManager();
Query q = em.createQuery("select t from CUSTOMER t");
List<Customer> customerList = q.getResultList();
for (Customer customer : customerList) {
System.out.println(customer);
}
System.out.println("Size: " + customerList.size());
em.getTransaction().begin();
Customer customer = new Customer();
customer.setCity("Warsaw");
customer.setCountry("USA");
customer.setName("John");
customer.setStreet("Street");
em.persist(customer);
em.getTransaction().commit();
em.close();
}
}
My persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
<class>b.model.Product</class>
<class>b.model.Book</class>
<class>b.model.Movie</class>
<class>b.model.Customer</class>
<class>b.model.Order</class>
<class>b.model.OrderElement</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527/baza;create=true" />
</properties>
</persistence-unit>
</persistence>
I have 2 dependencies in my project:
derbyclient-10.12.1.1.jar
javaee-api-6.0.jar
Any ideas on what am I doing wrong?
I have all the Model classes (like Customer) defined like this:
#Data
#Entity(name = "CUSTOMER")
public class Customer {
#Id
#Column(name = "CUSTOMER_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long customerId;
#Column(name = "NAME")
private String name;
#Column(name = "SURNAME")
private String surname;
#Column(name = "STREET")
private String street;
#Column(name = "CITY")
private String city;
#Column(name = "ZIP_CODE")
private String zipCode;
#Column(name = "COUNTRY")
private String country;
#OneToMany(mappedBy="customer",targetEntity=Order.class, fetch= FetchType.EAGER)
private Collection orders;
}
This is caused most probably by packaging the javaee-api jar inside your WAR. It contains only the method signatures, but no method bodies, thus one cannot run/test/deploy an application using it. Its sole purpose is to compile your app against it, thus making sure you follow the javaee api specs and avoid dependencies to a concrete implementation. Also one must not package any APIs provided by the server within the WAR.

JPA Relation between classes, referring to their Interfaces

I have two classes with their respective interfaces between which I want to create a JPA #OneToOne Relation. This fails with [class EmployeeImpl] uses a non-entity [class Adress] as target entity in the relationship attribute [field adress].
First Interface / Class:
public interface Employee {
public long getId();
public Adress getAdress();
public void setAdress(Adress adress);
}
#Entity(name = "EmployeeImpl")
#Table(name = "EmployeeImpl")
public class EmployeeImpl implements Employee {
#Id
#Column(name = "employeeId")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne(cascade = CascadeType.PERSIST)
private Adress adress;
// snip, getters and setters
}
Second Interface / Class:
public interface Adress {
public long getId();
public String getStreet();
public void setStreet(String street);
}
#Entity(name = "AdressImpl")
#Table(name = "AdressImpl")
public class AdressImpl implements Adress {
#Id
#Column(name = "AdressId")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "Street")
private String street;
// Snip getters and setters
}
The persistence.xml looks like this:
<?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="employee"
transaction-type="RESOURCE_LOCAL">
<class>EmployeeImpl</class>
<class>AdressImpl</class>
<properties>
<property name="eclipselink.create-ddl-jdbc-file-name"
value="create-matterhorn-employee.jdbc" />
<property name="eclipselink.drop-ddl-jdbc-file-name"
value="drop-matterhorn-employee.jdbc" />
</properties>
</persistence-unit>
</persistence>
I shortened out package names and imports and such. Exception occurs when trying to create the EntityManagerFactory (where you hand over the persistence unit). I am using eclipse link 2.0.2.
Actually JPA does allow such interface relationships, but in this case you have to provide an entity class implementing the interface, in you case this will look as follows:
#OneToOne(targetEntity = AddressImpl.class)
private Adress adress;
JPA standard does not allow for interface fields (or Collection of interface fields) being entity relationships. Some JPA implementations do support it (e.g DataNucleus JPA), but its a vendor extension to the spec. Consequently you either use one of those implementations or change your model (or add extra annotations/XML to define what type is actually stored there).

org.hibernate.AnnotationException: #OneToOne or #ManyToOne on entities.Ques#tion.examId references an unknown entity: long

I'm trying to setup JPA with a hibernate implementation for the first time with this test project. Ran into the following error:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: ExamModulePu] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at service.tests.ExamServiceTest.main(ExamServiceTest.java:18)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on entities.Question.examId references an unknown entity: long
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:109)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1536)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1457)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1365)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
These are my entities:
#Entity
public class Exam implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int numQuestions;
private int minutesAllotted;
private Date startDate;
private Date endDate;
#OneToMany(mappedBy = "examId", orphanRemoval = true)
private List<Question> questionList;
// Getters and setters here..
}
#Entity
public class Question implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#ManyToOne
private long examId;
private int points;
private int timeLimit;
private String text;
private String category;
#Embedded
private List<Answer> answerList;
}
#Embeddable
public class Answer implements Serializable {
private int optionNumber;
private String text;
private boolean correct;
}
This is what my persistence.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="ExamModulePu"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entities.Exam</class>
<class>entities.Question</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/exammoduledb" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
I haven't created any of the tables, but instead am depending on the hibernate.hb2mddl.auto to do so. But I believe my error springs up even before that happens as it can't generate the persistence unit. Any ideas what I'm doing wrong? I'm making sure I import only javax.persistence.*;
If you look closely at your stacktrace, you will see
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on entities.Question.examId references an unknown entity: long
So this field
#ManyToOne
private long examId;
is causing the problem. #ManyToOne has a paramater targetEntity which says:
(Optional) The entity class that is the target of the association.
Defaults to the type of the field or property that stores the association.
Since you haven't provided that parameter, it defaults to long, which is not a managed Entity.
You'll probably want to use
#ManyToOne(targetEntity = Exam.class)
private long examId;
otherwise it won't know what to map to. Or even better
#ManyToOne
private Exam exam;
Just add the class Team to the "hibernate-cfg.xml" file, because Hibernate doesn't identify without adding into it.
FYI, this sometimes happens if you have a hibernate annotation:
#org.hibernate.annotations.Entity
and a JPA annotation:
#javax.persistence.Entity
mixed up
Edit:
Explicitly import the javax annotation.
It took me hours to find the actual issue
I had forgotten the #Entity annotation on the Parent class and the error use to show on the child class.
In my case Hibernate was not able to identify the entity because I had not added that entity in sessionfactory using .addAnnotatedClass(XYZ.class) so it was not able to find that particular entity.

Categories

Resources