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")
Related
guys please help me for solve this error, it's been 4 days, this problem hasn't been solved.
this is my Entity Class code :
package mybengkel;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author rhmtsaepuloh
*/
#Entity
#Table(name = "employee")
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.id = :id"),
#NamedQuery(name = "Employee.findByUsername", query = "SELECT e FROM Employee e WHERE e.username = :username"),
#NamedQuery(name = "Employee.findByPassword", query = "SELECT e FROM Employee e WHERE e.password = :password")})
public class Employee 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)
#Column(name = "username")
private String username;
#Basic(optional = false)
#Column(name = "password")
private String password;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Employee(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "mybengkel.Employee[ id=" + id + " ]";
}
}
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="MyBengkelPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jar-file>/Users/rhmtsaepuloh/Downloads/mysql-connector-java-8.0.18/mysql-connector-java-8.0.18.jar</jar-file>
<class>mybengkel.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/oop?serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
and Main class java :
package mybengkel;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author rhmtsaepuloh
*/
public class MyBengkel {
public static void main(String[] args) {
EntityManager em;
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("MyBengkelPU");
em = emf.createEntityManager();
em.getTransaction().begin();
Employee e = new Employee();
e.setUsername("haha");
e.setPassword("hehe");
em.persist(e);
em.getTransaction().commit();
}
}
the problem is when I run the program found error code :
[EL Info]: 2019-11-28 16:07:45.916--ServerSession(347978868)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2019-11-28 16:07:46.813--ServerSession(347978868)--file:/Volumes/Data/Perkuliahan/OOP/NetBeans/MyBengkel/build/classes/_MyBengkelPU login successful
[EL Warning]: metamodel: 2019-11-28 16:07:46.859--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
Exception in thread "main" java.lang.IllegalArgumentException: Object: mybengkel.Employee[ id=null ] is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at mybengkel.MyBengkel.main(MyBengkel.java:29)
/Users/rhmtsaepuloh/Library/Caches/NetBeans/11.1/executor-snippets/run.xml:111: The following error occurred while executing this line:
/Users/rhmtsaepuloh/Library/Caches/NetBeans/11.1/executor-snippets/run.xml:68: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I try this on netbeans 11.1 and mysql connector java 8.0.18 Please help me to fix it guys... Thanks before
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>
I've got this error.. Could someone help me ?
run: Exception in thread "main" java.lang.NullPointerException at
cidade.CidadeJpaController.getEntityManager(CidadeJpaController.java:24)
at cidade.CidadeJpaController.create(CidadeJpaController.java:30) at
Main.Main.main(Main.java:10) Java Result: 1
Cidade
package cidade;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Cidade implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String nome;
private String uf;
public Cidade() {
}
public Cidade(String n, String u){
this.nome = n;
this.uf = u;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
}
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="easyjavajpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>cidade.Cidade</class>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/thibernate"/>
<property name="javax.persistence.jdbc.password" value="1234"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
CidadeJpaController
package cidade;
import cidade.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
public class CidadeJpaController implements Serializable {
public CidadeJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public CidadeJpaController() {
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Cidade cidade) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(cidade);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Cidade cidade) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
cidade = em.merge(cidade);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
long id = cidade.getId();
if (findCidade(id) == null) {
throw new NonexistentEntityException("The cidade with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cidade cidade;
try {
cidade = em.getReference(Cidade.class, id);
cidade.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The cidade with id " + id + " no longer exists.", enfe);
}
em.remove(cidade);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Cidade> findCidadeEntities() {
return findCidadeEntities(true, -1, -1);
}
public List<Cidade> findCidadeEntities(int maxResults, int firstResult) {
return findCidadeEntities(false, maxResults, firstResult);
}
private List<Cidade> findCidadeEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Cidade.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Cidade findCidade(long id) {
EntityManager em = getEntityManager();
try {
return em.find(Cidade.class, id);
} finally {
em.close();
}
}
public int getCidadeCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Cidade> rt = cq.from(Cidade.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Main
package Main;
import java.util.*;
import cidade.*;
public class Main {
public static void main(String[] args) {
CidadeJpaController em = new CidadeJpaController();
Cidade cidade = new Cidade("Santarém", "PA");
em.create(cidade);
List cidades = em.findCidadeEntities();
System.out.println( cidades.size() + " cidade(s) encontradas" );
for (Object c : cidades) {
Cidade cid = (Cidade) c;
System.out.println(cid.getNome());
}
}
}
It seems that you are not setting the entityManagerFactory while instantiating your controller. Hence it is throwing a null pointer exception. As per your code
em = getEntityManager();
the getEntityManagerMethod():
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
Here emf is already null. As you used default constructor to initialize your code and I do not see any injection what so ever.
Regards
Himanshu
You have this constructor in CidadeJpaController which takes EntityManagerFactory object.
public CidadeJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
While instantiating you're not providing EntityManagerFactory object resulting in null pointer error when trying to access. SO create an EntityManagerFactory object ans send it CidadeJpaController.Below is a sample solution change it in your Main class
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("easyjavajpa");
CidadeJpaController em = new CidadeJpaController(entityManagerFactory);
Cidade cidade = new Cidade("Santarém", "PA");
em.create(cidade);
List cidades = em.findCidadeEntities();
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.
I'm trying to figure out how to use #PersistenceUnit as I've read it's a much better solution than #PersistenceContext. The trouble is.... I can't figure out how to get it to work properly...
#Controller
public class Content {
#PersistenceUnit(unitName = "CMTPU")
public EntityManagerFactory emf;
public EntityManager em = emf.createEntityManager();
#RequestMapping(value={"/content/edit*"}, method=RequestMethod.GET)
public ModelAndView edit(Model model) {
ModelAndView mv = new ModelAndView();
mv.setViewName("content/edit");
//get symbols
List<Symbol> symbols = em.createNamedQuery("Symbol.findAll").getResultList();
mv.addObject(symbols);
return mv;
}
}
My app loaded before I added the //get symbols section and the EntityManager stuff. Now I'm seeing the error SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.NullPointerException
I've read that I need to define a unitName, but then I'm looking at this documentation and it doesn't show that being done.
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="CMTPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>CMT_DEV</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I'm having trouble determining what I'm doing wrong.
update
My model defines the database and all of that as seen below. Do I even need a persistence.xml?
package com.fettergroup.cmt.models;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "symbol", catalog = "DATABASE1", schema = "dbo")
#NamedQueries({
#NamedQuery(name = "Symbol.findAll", query = "SELECT s FROM Symbol s"),
#NamedQuery(name = "Symbol.findById", query = "SELECT s FROM Symbol s WHERE s.id = :id"),
#NamedQuery(name = "Symbol.findBySymbol", query = "SELECT s FROM Symbol s WHERE s.symbol = :symbol"),
#NamedQuery(name = "Symbol.findByHtmlNumber", query = "SELECT s FROM Symbol s WHERE s.htmlNumber = :htmlNumber"),
#NamedQuery(name = "Symbol.findByHtmlName", query = "SELECT s FROM Symbol s WHERE s.htmlName = :htmlName"),
#NamedQuery(name = "Symbol.findByAsciiDec", query = "SELECT s FROM Symbol s WHERE s.asciiDec = :asciiDec"),
#NamedQuery(name = "Symbol.findByAsciiHex", query = "SELECT s FROM Symbol s WHERE s.asciiHex = :asciiHex")})
public class Symbol implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Short id;
#Size(max = 10)
#Column(name = "symbol")
private String symbol;
#Size(max = 10)
#Column(name = "html_number")
private String htmlNumber;
#Size(max = 10)
#Column(name = "html_name")
private String htmlName;
#Size(max = 10)
#Column(name = "ascii_dec")
private String asciiDec;
#Size(max = 10)
#Column(name = "ascii_hex")
private String asciiHex;
public Symbol() {
}
public Symbol(Short id) {
this.id = id;
}
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getHtmlNumber() {
return htmlNumber;
}
public void setHtmlNumber(String htmlNumber) {
this.htmlNumber = htmlNumber;
}
public String getHtmlName() {
return htmlName;
}
public void setHtmlName(String htmlName) {
this.htmlName = htmlName;
}
public String getAsciiDec() {
return asciiDec;
}
public void setAsciiDec(String asciiDec) {
this.asciiDec = asciiDec;
}
public String getAsciiHex() {
return asciiHex;
}
public void setAsciiHex(String asciiHex) {
this.asciiHex = asciiHex;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Symbol)) {
return false;
}
Symbol other = (Symbol) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.project1.models.Symbol[ id=" + id + " ]";
}
}
use only
#Controller
public class Content {
#PersistenceContext(unitName = "CMTPU")
public EntityManager em;
The entity manager should be controlled by spring.
This ins an example, it uses hiberante as persistence provider, but I think you can adapt it.
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="myPersistenceUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
</bean>
sample persistance unit, that works with that configuration
<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>