getIdentifier method of PersistenceUnitUtil not working for Composite keys - jpa

I am getting below error when trying to retrieve identity using getIdentifier method of PersistenceUnitUtil. Is there anything I am doing wrong.
Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: An internal error occurred accessing the primary key object [202].
Internal Exception: java.lang.NullPointerException
Descriptor: RelationalDescriptor(com.sample.Person --> [DatabaseTable(PERSON)])
at org.eclipse.persistence.exceptions.DescriptorException.errorUsingPrimaryKey(DescriptorException.java:1923)
at org.eclipse.persistence.internal.jpa.CMP3Policy$FieldAccessor.setValue(CMP3Policy.java:686)
at org.eclipse.persistence.descriptors.CMPPolicy.createPrimaryKeyInstance(CMPPolicy.java:453)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getIdentifier(EntityManagerFactoryImpl.java:75)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getIdentifier(EntityManagerFactoryDelegate.java:679)
at com.sample.PersistenceUtil.getEntityIdentifier(PersistenceUtil.java:27)
at com.sample.PersistenceUtil.getEntityIdentifier(PersistenceUtil.java:18)
at com.sample.OverrideUtilTest.canconfirmEntityEqualsforCompositeId2(OverrideUtilTest.java:147)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.internal.jpa.CMP3Policy$FieldAccessor.setValue(CMP3Policy.java:682)
... 29 more
The code sample I am trying is this:
#Entity
#IdClass(PersonPK.class)
#Table(name = "PERSON")
public class Person {
#Id
#Column(name = "CODE_C")
private String code;
#Column(name = "NAME_C")
private String name;
#Id
#Column(name = "COUNTRY_C")
private String country;
public Person() {
}
public Person(String code, String country) {
this.code = code;
this.country = country;
}
public String getCode() {
return this.code;
}
public String getCountry() {
return this.country;
}
}
public class PersonPK implements Serializable {
private static final long serialVersionUID = 1L;
private final String code;
private final String country;
public PersonPK(String city, String country) {
super();
this.code = city;
this.country = country;
}
#Override
public boolean equals(Object object) {
return super.equals (object);
}
#Override
public int hashCode() {
return super.hashCode();
}
}
The code to retrieve identity I am using is
getEntityManagerFactory(persistenceUnitName).getPersistenceUnitUtil()
.getIdentifier(entity);
Any help is appreciated

The primary key class must be public and must have a public no-arg constructor.
Hibernate message in similar situation is a little bit more informative
javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: : PersonPK
Solution: Add default constructor to PersonPK

Related

NullPointerException is occurring with createNamedQuery and then persistence unit logins successfully

I can't seem to solve this issue. I have tried googling but can't put the pieces together to solve it. I have the following stack trace:
Warning: java.lang.NullPointerException
at org.eclipse.persistence.platform.server.ServerPlatformUtils.createServerPlatform(ServerPlatformUtils.java:99)
at org.eclipse.persistence.sessions.factories.SessionManager.init(SessionManager.java:77)
at org.eclipse.persistence.sessions.factories.SessionManager.<clinit>(SessionManager.java:71)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.addSessionToGlobalSessionManager(EntityManagerSetupImpl.java:907)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.initSession(EntityManagerSetupImpl.java:2671)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:675)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:305)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:337)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:318)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:521)
at session.CategoryFacade.findRandom(CategoryFacade.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy173.findRandom(Unknown Source)
at session.__EJB31_Generated__CategoryFacade__Intf____Bean__.findRandom(Unknown Source)
at actions.ActionFacade.setFeaturedCategories(ActionFacade.java:82)
at actions.HomeAction.execute(HomeAction.java:16)
at controller.ControllerServlet.service(ControllerServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Info: EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150605-31e8258
Info: /file:/Users/csexton/NetBeansProjects/ReadersParadise/build/web/WEB-INF/classes/_AffableBeanPU login successful
So if you look at the last two lines my persistent unit isn't logging in until I try to use the entity manager. If I do another query after the first one, everything is good, no errors, nothing......Error occurs on the createNamedQuery. The query exists and matches the exact name. I can call the same method twice and the first one causes a NPE but the second one works fine.
#Stateless(name="CategoryFacade")
public class CategoryFacade extends AbstractFacade<Category> {
#PersistenceContext(unitName = "AffableBeanPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategoryFacade() {
super(Category.class);
}
public List<Category> findRandom(int limit) {
return getEntityManager()
.createNamedQuery("Category.findRandomByLimit")
.setParameter(1, limit)
.getResultList();
}
}
I am doing a jndi lookup for the class
public class ActionFacade implements AutoCloseable {
private static ThreadLocal<ActionFacade> instance = new ThreadLocal<>();
private HttpServletRequest request;
private HttpSession session;
private CategoryFacade categoryFacade;
private BookFacade bookFacade;
private OrderManager orderManager;
private ShoppingCart cart;
public ActionFacade(HttpServletRequest request) {
this.request = request;
this.session = request.getSession();
try {
Context ctx = new InitialContext();
this.categoryFacade = (CategoryFacade) ctx.lookup(
"java:global/ReadersParadise/CategoryFacade!session.CategoryFacade");
System.out.print("JNDI lookup complete.");
this.bookFacade = (BookFacade) ctx.lookup(
"java:global/ReadersParadise/BookFacade!session.BookFacade");
this.orderManager = (OrderManager) ctx.lookup(
"java:global/ReadersParadise/OrderManager!session.OrderManager");
} catch (NamingException ex) {
System.err.println(ex);
}
}
public static ActionFacade create(HttpServletRequest request) {
ActionFacade facade = new ActionFacade(request);
instance.set(facade);
return facade;
}
public static ActionFacade getCurrentInstance() {
return instance.get();
}
#Override
public void close() {
instance.remove();
}
public void setSelectedCategory() {
String categoryName = request.getParameter("category");
Category selectedCategory = categoryFacade.findByName(categoryName);
if (selectedCategory == null) {
selectedCategory = categoryFacade.find(1);
}
session.setAttribute("selectedCategory", selectedCategory);
Collection<Book> categoryBooks = selectedCategory.getBookCollection();
session.setAttribute("categoryBooks", categoryBooks);
}
public void setAllCategories() {
request.setAttribute("categories", categoryFacade.findAll());
}
}
Then in my servlet I am using the ActionFacade like this....
try(ActionFacade facade = ActionFacade.create(request)) {
Action action = ActionFactory.getAction(request);
String view = action.execute(facade);
System.out.println(request.getServletPath());
if (request.getServletPath().equals("") || view.equals(request.getServletPath().substring(1))) {
request.getRequestDispatcher("/WEB-INF/views/" + view + ".jsp").forward(request, response);
} else {
response.sendRedirect(view);
}
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
This is the category entity
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name= :name")
})
#NamedNativeQuery(name = "Category.findRandomByLimit",
query = "SELECT * FROM Category ORDER BY RAND() LIMIT ?1")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<Book> bookCollection;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
public Category(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#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 Category)) {
return false;
}
Category other = (Category) 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 "entity.Category[ id=" + id + " ]";
}
}
Category Action Class which uses the ActionFacade
public class CategoryAction implements Action {
#Override
public String execute(ActionFacade facade) throws Exception {
facade.setSelectedCategory();
facade.setAllCategories();
return "category";
}
}
I think it is a problem of Glassfish 4.1.1 described here:
https://java.net/jira/browse/GLASSFISH-21468
According this, it may help, if you add
<property name="eclipselink.target-server" value="Glassfish"/>
to your persistence.xml

java.sql.SQLSyntaxErrorException: is not a column in table

I'm working on a JavaEE application using EJB and JPA
Two of my Entities are:
#Entity
public class Utente implements Serializable {
private static final long serialVersionUID = 1L;
#Override
public String toString() {
return "Utente [cod_utente=" + cod_utente + ", nome_utente="
+ nome_utente + ", morada_utente=" + morada_utente
+ ", dnasc_utente=" + dnasc_utente + ", tel_utente="
+ tel_utente + "]";
}
/**
*
*/
public Utente(String nome_utente, String morada_utente,
GregorianCalendar dnasc_utente, int tel_utente) {
super();
this.nome_utente = nome_utente;
this.morada_utente = morada_utente;
this.dnasc_utente = dnasc_utente;
this.tel_utente = tel_utente;
}
#Id
#GeneratedValue
private int cod_utente;
private String nome_utente;
private String morada_utente;
#Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_utente;
private int tel_utente;
private List<GregorianCalendar> agenda;
#OneToMany
#JoinColumn(nullable=true)
private List<Prescricao> lista_presc;
public Utente(){
super();
}
public List<Prescricao> getLista_presc() {
return lista_presc;
}
public void setLista_presc(List<Prescricao> lista_presc) {
this.lista_presc = lista_presc;
}
public List<GregorianCalendar> getAgenda() {
return agenda;
}
public void setAgenda(List<GregorianCalendar> agenda) {
this.agenda = agenda;
}
public int getCod_utente() {
return cod_utente;
}
public void setCod_utente(int cod_utente) {
this.cod_utente = cod_utente;
}
public String getNome_utente() {
return nome_utente;
}
public void setNome_utente(String nome_utente) {
this.nome_utente = nome_utente;
}
public String getMorada_utente() {
return morada_utente;
}
public void setMorada_utente(String morada_utente) {
this.morada_utente = morada_utente;
}
public GregorianCalendar getDnasc_utente() {
return dnasc_utente;
}
public void setDnasc_utente(GregorianCalendar dnasc_utente) {
this.dnasc_utente = dnasc_utente;
}
public int getTel_utente() {
return tel_utente;
}
public void setTel_utente(int tel_utente) {
this.tel_utente = tel_utente;
}
}
and:
#Entity
public class FichaClinica implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
#Id
#GeneratedValue
private int cod_ficha;
#OneToOne
#JoinColumn
private Utente utente;
#OneToMany
#JoinColumn(nullable=true)
private List <AtoEnfermagem> lista_atos_enf;
#OneToMany
#JoinColumn(nullable=true)
private List <AtoMedico> lista_atos_medicos;
#OneToMany
#JoinColumn(nullable=true)
private List<Consulta> lista_consultas;
public FichaClinica(){ //construtor vazio
super();
}
public Utente getUtente() {
return utente;
}
public void setUtente(Utente utente) {
this.utente = utente;
}
#Override
public String toString() {
return "FichaClinica [cod_ficha=" + cod_ficha + ", lista_atos_enf="
+ lista_atos_enf + ", lista_atos_medicos=" + lista_atos_medicos
+ ", lista_consultas=" + lista_consultas + "]";
}
public FichaClinica(Utente utente){
super();
this.utente=utente;
}
public FichaClinica(Utente utente,
ArrayList<AtoEnfermagem> lista_atos_enf,
ArrayList<AtoMedico> lista_atos_medicos,
ArrayList<Consulta> lista_consultas) {
super();
this.lista_atos_enf = lista_atos_enf;
this.lista_atos_medicos = lista_atos_medicos;
this.lista_consultas = lista_consultas;
}
//Adicionar elementos às listas
public int getCod_ficha() {
return cod_ficha;
}
public void setCod_ficha(int cod_ficha) {
this.cod_ficha = cod_ficha;
}
public List<AtoEnfermagem> getLista_atos_enf() {
return lista_atos_enf;
}
public void setLista_atos_enf(List<AtoEnfermagem> lista_atos_enf) {
this.lista_atos_enf = lista_atos_enf;
}
public List<AtoMedico> getLista_atos_medicos() {
return lista_atos_medicos;
}
public void setLista_atos_medicos(ArrayList<AtoMedico> lista_atos_medicos) {
this.lista_atos_medicos = lista_atos_medicos;
}
public List<Consulta> getLista_consultas() {
return lista_consultas;
}
public void setLista_consultas(ArrayList<Consulta> lista_consultas) {
this.lista_consultas = lista_consultas;
}
public void adicionar_ato_medico(AtoMedico a_medico){
lista_atos_medicos.add(a_medico);
}
public void adiconar_consulta(Consulta c){
lista_consultas.add(c);
}
public void adicionar_ato_enf(AtoEnfermagem a_enf){
lista_atos_enf.add(a_enf);
}
}
When I try to execute the following method:
#Override
public String cria_utente(String nome_utente, String morada_utente,GregorianCalendar dnasc_utente, int tel_utente) {
Utente u=new Utente(nome_utente,morada_utente,dnasc_utente,tel_utente);
em.persist(u);
FichaClinica fc=new FichaClinica(u);
em.persist(fc);
return "Utente "+Integer.toString(u.getCod_utente())+" (Ficha Clinica "+Integer.toString(fc.getCod_ficha())+") cirado!";
}
An error occurs. Here is the complete stacktrace:
Exception in thread "main" javax.ejb.EJBException: Transaction aborted
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:725)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy238.cria_utente(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:490)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:719)
... 24 more
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
Error Code: 20000
Call: INSERT INTO FICHACLINICA (COD_FICHA, UTENTE_COD_UTENTE) VALUES (?, ?)
bind => [2 parameters bound]
Query: InsertObjectQuery(FichaClinica [cod_ficha=10, lista_atos_enf={[]}, lista_atos_medicos={[]}, lista_consultas={[]}])
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl$1.handleException(EntityManagerSetupImpl.java:696)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.handleException(AbstractSynchronizationListener.java:275)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:170)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
... 26 more
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
Error Code: 20000
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2002)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:298)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:377)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:165)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:180)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:489)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:301)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:798)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1786)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1737)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:226)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsForClassWithChangeSet(CommitManager.java:193)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:138)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4207)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1441)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1531)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3168)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:352)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:158)
... 28 more
Caused by: java.sql.SQLSyntaxErrorException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
at com.sun.gjc.spi.base.ConnectionHolder.prepareStatement(ConnectionHolder.java:586)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:255)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:52)
at com.sun.gjc.spi.ManagedConnectionImpl.prepareCachedStatement(ManagedConnectionImpl.java:992)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareStatement(ConnectionWrapper40.java:173)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.prepareStatement(DatabaseAccessor.java:1556)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.prepareStatement(DatabaseAccessor.java:1505)
at org.eclipse.persistence.internal.databaseaccess.DatabaseCall.prepareStatement(DatabaseCall.java:778)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:619)
... 58 more
Caused by: org.apache.derby.client.am.SqlException: 'UTENTE_COD_UTENTE' is not a column in table or VTI 'APP.FICHACLINICA'.
at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
at org.apache.derby.client.am.Statement.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.prepare(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatementX(Unknown Source)
... 68 more
Can please someone help me find what's wrong here?
The error occurs because you probably didn't create the column UTENTE_COD_UTENTE in the table APP.FICHACLINICA. Creating the column (type integer) should fix the problem.
The code:
#OneToOne
#JoinColumn
private Utente utente;
doesn't specify a name for the join column and therefore creates a default join column based on this rule (from #JoinColumn):
Default (only applies if a single join column is used): The
concatenation of the following: the name of the referencing
relationship property or field of the referencing entity or embeddable
class; ""; the name of the referenced primary key column. If there is
no such referencing relationship property or field in the entity, or
if the join is for an element collection, the join column name is
formed as the concatenation of the following: the name of the entity;
""; the name of the referenced primary key column.
You can set a name for the join column like this:
#OneToOne
#JoinColumn(name = "SOMETHING_UTENTE")
private Utente utente;
But then you'll have to create a column named like this.
See also:
JPA JoinColumn vs mappedBy

getting NullPointerException when try to persist entity

I have the following code. When I run the junit test it's creating a table and fields but they are null. I'm also getting a NullPointerException..
Why isn't my user being added?
java.lang.NullPointerException
at com.testproject.repo.JPAUserRepo.addUser(JPAUserRepo.java:15)
at com.testproject.manager.UserManager.saveUser(UserManager.java:18)
at com.testproject.manager.test.UserManagerTest.testSaveUser(UserManagerTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
User.java
#Entity
#Table(name="USER")
#NamedQuery(name="getAllUser", query="SELECT a FROM User a ORDER BY a.userid")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="USER_ID")
private long userid;
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String password;
#Column(name="USER_EMAIL")
private String userEmail;
#Column(name="USER_PHONE")
private int userPhone;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String password, String email, int userPhone) {
super();
this.username = username;
this.password = password;
this.userEmail = email;
this.userPhone = userPhone;
}
//Getters and Setters
JPAUserRepo.java
public class JPAUserRepo implements UserRepo {
EntityManager em;
#Override
public void addUser(User user) {
em.persist(user);
}
UserManager.java
public class UserManager {
UserRepo userRepo;
public void saveUser(User user){
userRepo.addUser(user);
}
UserManagerTest.java
public class UserManagerTest {
EntityManager em;
UserManager userManager;
User user;
#Before
public void setUp() throws Exception {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitMySQL");
em = factory.createEntityManager();
userManager = new UserManager();
JPAUserRepo jpaUserRepo = new JPAUserRepo();
userManager.setUserRepo(jpaUserRepo);
em.getTransaction().begin();
user = new User("name", "password", "mail#mail.com", 1561234567);
}
#After
public void tearDown() throws Exception {
em.getTransaction().commit();
}
#Test
public void testSaveUser() {
userManager.saveUser(user);
}
}

When using inheritance throw exception java.lang.NoSuchFieldError: __odbTracker on NetBeans 7.3 Jboss 7.1.1 ObjectDB 2.5.1

When using inheritance throw exception java.lang.NoSuchFieldError: __odbTracker on NetBeans 7.3 + ObjectDB 2.5.1 + Jboss 7.1.1, but works fine on NetBeans 7.3 + ObjectDB 2.5.1 + GlassFish 3.1
#Entity
public class Person extends AbstractObject {
private static final long serialVersionUID = 1L;
#ManyToOne #Index
private City city;
#OneToMany(mappedBy = "owner")
private List<City> cities;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public List<City> getCitys() {
return cities;
}
public void setCitys(List<City> citys) {
this.cities = citys;
}
}
#Entity
public class City extends AbstractObject {
private static final long serialVersionUID = 33L;
#OneToMany(mappedBy = "city")
private List<Person> persons;
#ManyToOne #Index
private Person owner;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = owner;
}
}
#Entity
public abstract class AbstractObject implements IAbstractObject {
//private static final long serialVersionUID = 1L;
#Id
private String id = UUID.randomUUID().toString();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#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 AbstractObject)) {
return false;
}
AbstractObject other = (AbstractObject) 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 "test.AbstractObject[ id=" + id + " ]";
}
}
This code throw exception:
Person person = new Person();
person.setName(name);
City city = new City();
city.setName("Москва");
person.setCity(city);
entityManager.persist(city);
entityManager.persist(person);
The exception:
java.lang.NoSuchFieldError: __odbTracker
test.City.__odbSet_name(City.java:1)
test.City.setName(City.java:39)
ejb.PersonBean.create(PersonBean.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.jboss.as.ee.component.ManagedReferenceMethodInterceptorFactory$ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptorFactory.java:72)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:127)
org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:135)
org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:36)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:36)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:82)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:228)
org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:304)
org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:190)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:32)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:165)
org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:173)
org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:72)
ejb.PersonBeanLocal$$$view66.create(Unknown Source)
servlet.TestServlet.processRequest(TestServlet.java:68)
servlet.TestServlet.doGet(TestServlet.java:107)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62)
if remove the inheritance works fine. On GlassFish 3.1 with inheritance also works fine.
Why "person.setName(name);" works fine? But "city.setName("Москва");" throw exception
Thanks for your help.
if someone is interested in the answer - objectdb support
I added this code in build.xml. the project works fine.
<target name="-post-compile">
<java classname="com.objectdb.Enhancer" fork="true" classpath="C:/projects/test/lib/objectdb.jar">
<arg line="-s ./build/classes/test/*.class"/>
</java>
</target>

Relation ManyToOne, javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session

I've spent a lot of time searching for the bug and I can't resolve this.
I use spring JPA with Hibernate and Postgre.
I have two entities Location and Ap:
CREATE TABLE ap
(
id serial NOT NULL,
ssid text NOT NULL,
bssid text NOT NULL,
capabilities text,
CONSTRAINT ap_pkey PRIMARY KEY (id )
)
CREATE TABLE location2
(
latitude double precision NOT NULL,
longitude double precision NOT NULL,
power integer NOT NULL,
ap_id integer,
id serial NOT NULL,
CONSTRAINT location2_pkey PRIMARY KEY (id ),
CONSTRAINT location2_ap_id_fkey FOREIGN KEY (ap_id)
REFERENCES ap (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
Ap:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "ap")
public class Ap implements Serializable {
private Long id;
private String ssid;
private String bssid;
private String capabilities;
private Set<Location> locations = new HashSet<Location>();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#OneToMany(mappedBy = "ap", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
public Set<Location> getLocations() {
return locations;
}
public void setLocations(Set<Location> locations) {
this.locations = locations;
}
#Column
public String getSsid() {
return ssid;
}
public void setSsid(String ssid) {
this.ssid = ssid;
}
#Column
public String getBssid() {
return bssid;
}
public void setBssid(String bssid) {
this.bssid = bssid;
}
#Column
public String getCapabilities() {
return capabilities;
}
public void setCapabilities(String capabilities) {
this.capabilities = capabilities;
}
public void addLocation(Location location) {
location.setAp(this);
getLocations().add(location);
}
public void removeLocation(Location location) {
getLocations().remove(location);
}
public Ap() {
super();
}
public Ap(String ssid, String bssid, String capabilities) {
this.ssid = ssid;
this.bssid = bssid;
this.capabilities = capabilities;
}
}
Location2
#Entity
#Table(name = "location2")
public class Location implements Serializable {
private Long id;
private double latitude;
private double longitude;
private int power;
private Ap ap;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name = "ap_id")
public Ap getAp() {
return ap;
}
public void setAp(Ap ap) {
this.ap = ap;
}
#Column
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
#Column
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
#Column
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public Location(double latitude, double longitude, int power) {
super();
this.latitude = latitude;
this.longitude = longitude;
this.power = power;
}
public Location() {
super();
}
When I add one Location to Ap it works, but when Ap has two or more Location I can't save Ap entity.
ApService service=context.getBean("ApService", ApService.class);
Ap ap=new Ap("test_ssid2", "test_bssid2", "test_capabilities2");
ap.addLocation(new Location(9.121, 12.9, 12));
ap.addLocation(new Location(9.122, 12.9, 12));
service.save(ap);
ApService:
public Ap save(Ap ap) {
return apRepository.save(ap);
}
It cases error:
Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: a different object with the same identifier value was already associated with the session: [com.kulig.ap.domain.Location#9]; nested exception is javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [com.kulig.ap.domain.Location#9]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:318)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:106)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:91)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy24.save(Unknown Source)
at com.kulig.ap.service.jpa.ApServiceImpl.save(ApServiceImpl.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy29.save(Unknown Source)
at com.kulig.ap.Test.main(Test.java:24)
Caused by: javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [com.kulig.ap.domain.Location#9]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1359)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1315)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1321)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:843)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy19.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:341)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:334)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 22 more
I also tried EntityManager with merge and persist methods and this gives the same error.
Please help.
In Location try to change
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
to
#Id
#GeneratedValue(generator="LOCATION_SEQ_GEN",strategy=GenerationType.SEQUENCE)
#SequenceGenerator(sequenceName="location_sequence_name",name="LOCATION_SEQ_GEN",allocationSize=1)
I heard that allocationSize=1 is bad practice but otherwise there are problems with sequence. You can read more Hibernate use of PostgreSQL sequence does not affect sequence table