Consider code bellow
Beneficiaire class :
#Entity
#Table(uniqueConstraints=
#UniqueConstraint(name="u_benef_noBenef", columnNames="noBenef"))
public class Beneficiaire implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idBenef;
#Column(nullable=false)
private Integer noApBenef;
#Column(nullable=false)
private Integer noBenef;
#Column(columnDefinition="character varying(100) not null")
private String nomBenef;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateNaissanceBenef;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_cat_beneficiaire",
foreignKey=#ForeignKey(name="fk_benef_idCatBenef"),
nullable=false)
private CategorieBeneficiaire categorieBeneficiaire;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_sexe",
foreignKey=#ForeignKey(name="fk_benef_idSexe"),
nullable=false)
private Sexe sexe;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_assure",
foreignKey=#ForeignKey(name="fk_benef_idAssure"),
nullable=false)
private Assure assure;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_attributaire",
foreignKey=#ForeignKey(name="fk_benef_idAttrib"),
nullable=false)
private Attributaire attributaire;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_prestation",
foreignKey=#ForeignKey(name="fk_benef_idPrestation"),
nullable=false)
private Prestation prestation;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateEffetPrestation;
#Column(precision=8, nullable=false)
private BigDecimal mntMensuelPrestation;
private Integer trimestreDerniereEmission;
private Integer anneeDerniereEmission;
#Column(columnDefinition="integer default 1 not null", insertable=false)
private Integer estActifBenef;
#Column(columnDefinition="timestamp default current_timestamp not null", insertable=false)
private LocalDateTime dateheureCreationBenef;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_utilisateur",
foreignKey=#ForeignKey(name="utilisateur_id_fk"),
nullable=true)
private Utilisateur utilisateur;
/*#OneToMany(mappedBy="beneficiairePj", cascade=CascadeType.ALL, orphanRemoval=true)
private List<PieceJustificative> pieceJustificatives = new ArrayList<PieceJustificative>();*/
public Beneficiaire() {
//For JPA
}
public Beneficiaire(Integer noBenef, String nomBenef, Integer noApBenef,
CategorieBeneficiaire categorieBeneficiaire, Sexe sexe, Assure assure, Attributaire attributaire,
Prestation prestation) {
super();
this.noBenef = noBenef;
this.nomBenef = nomBenef;
this.noApBenef = noApBenef;
this.categorieBeneficiaire = categorieBeneficiaire;
this.sexe = sexe;
this.assure = assure;
this.attributaire = attributaire;
this.prestation = prestation;
}
public Integer getIdBenef() {
return idBenef;
}
public void setIdBenef(Integer idBenef) {
this.idBenef = idBenef;
}
public Integer getNoBenef() {
return noBenef;
}
public void setNoBenef(Integer noBenef) {
this.noBenef = noBenef;
}
public String getNomBenef() {
return nomBenef;
}
public void setNomBenef(String nomBenef) {
this.nomBenef = nomBenef;
}
public Integer getNoApBenef() {
return noApBenef;
}
public void setNoApBenef(Integer noApBenef) {
this.noApBenef = noApBenef;
}
public LocalDate getDateNaissanceBenef() {
return dateNaissanceBenef;
}
public void setDateNaissanceBenef(LocalDate dateNaissanceBenef) {
this.dateNaissanceBenef = dateNaissanceBenef;
}
public CategorieBeneficiaire getCategorieBeneficiaire() {
return categorieBeneficiaire;
}
public void setCategorieBeneficiaire(CategorieBeneficiaire categorieBeneficiaire) {
this.categorieBeneficiaire = categorieBeneficiaire;
}
public Sexe getSexe() {
return sexe;
}
public void setSexe(Sexe sexe) {
this.sexe = sexe;
}
public Assure getAssure() {
return assure;
}
public void setAssure(Assure assure) {
this.assure = assure;
}
public Attributaire getAttributaire() {
return attributaire;
}
public void setAttributaire(Attributaire attributaire) {
this.attributaire = attributaire;
}
public Prestation getPrestation() {
return prestation;
}
public void setPrestation(Prestation prestation) {
this.prestation = prestation;
}
public LocalDate getDateEffetPrestation() {
return dateEffetPrestation;
}
public void setDateEffetPrestation(LocalDate datteEffetPrestation) {
this.dateEffetPrestation = datteEffetPrestation;
}
public BigDecimal getMntMensuelPrestation() {
return mntMensuelPrestation;
}
public void setMntMensuelPrestation(BigDecimal mntMensuelPrestation) {
this.mntMensuelPrestation = mntMensuelPrestation;
}
public Integer getTrimestreDerniereEmission() {
return trimestreDerniereEmission;
}
public void setTrimestreDerniereEmission(Integer trimestreDerniereEmission)
{
this.trimestreDerniereEmission = trimestreDerniereEmission;
}
public Integer getAnneeDerniereEmission() {
return anneeDerniereEmission;
}
public void setAnneeDerniereEmission(Integer anneeDerniereEmission) {
this.anneeDerniereEmission = anneeDerniereEmission;
}
public Integer getEstActifBenef() {
return estActifBenef;
}
public void setEstActifBenef(Integer estActifBenef) {
this.estActifBenef = estActifBenef;
}
public LocalDateTime getDateheureCreationBenef() {
return dateheureCreationBenef;
}
public void setDateheureCreationBenef(LocalDateTime dateheureCreationBenef)
{
this.dateheureCreationBenef = dateheureCreationBenef;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
//For Test Equal, override equals() and hashCode()
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Beneficiaire beneficiaire = (Beneficiaire) o;
return noBenef.equals(beneficiaire.getNoBenef());
}
#Override
public int hashCode() {
return Objects.hash(noBenef);
}
}
PieceJustificative class :
#Entity
#Table(uniqueConstraints=
#UniqueConstraint(name="u_pj_noPj", columnNames="noPj"))
public class PieceJustificative implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idPj;
#Column(nullable=false)
private Integer noPj;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateDebutValiditePj;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateFinValiditePj;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(nullable=false)
private LocalDate dateSignaturePj;
#Column(columnDefinition="timestamp default current_timestamp not null", insertable=false)
private LocalDateTime dateHeureSaisiePj;
private LocalDateTime dateHeureValidationPj;
#Column(columnDefinition="integer default 0 not null", insertable=false)
private Integer estValidePj;
/*#ManyToOne(optional=false, fetch=FetchType.LAZY)
*/
#ManyToOne
#JoinColumn(name="id_type_pj",
foreignKey=#ForeignKey(name="fk_pj_id_type_pj"),
nullable=false)
private TypePj typePj;
/*#ManyToOne(optional=false, fetch=FetchType.LAZY)
#JoinColumn(name="id_beneficiaire",
foreignKey=#ForeignKey(name="fk_pj_id_beneficiaire"))
*/
/*#ManyToOne(optional=false)*/
#ManyToOne
#JoinColumn(name="idBenef",
foreignKey=#ForeignKey(name="fk_pj_id_beneficiaire"),
nullable=false)
private Beneficiaire beneficiairePj;
#ManyToOne
#JoinColumn(name="id_utilisateur_saisie",
foreignKey=#ForeignKey(name="fk_pj_id_utilisateur_saisie"))
private Utilisateur utilisateurSaisiePj;
#ManyToOne
#JoinColumn(name="id_utilisateur_valide",
foreignKey=#ForeignKey(name="fk_pj_id_utilisateur_valide"))
private Utilisateur utilisateurValidationPj;
protected PieceJustificative() {
//For JPA
}
public Integer getIdPj() {
return idPj;
}
public void setIdPj(Integer idPj) {
this.idPj = idPj;
}
public Integer getNoPj() {
return noPj;
}
public void setNoPj(Integer noPj) {
this.noPj = noPj;
}
public LocalDate getDateDebutValiditePj() {
return dateDebutValiditePj;
}
public void setDateDebutValiditePj(LocalDate dateDebutValiditePj) {
this.dateDebutValiditePj = dateDebutValiditePj;
}
public LocalDate getDateFinValiditePj() {
return dateFinValiditePj;
}
public void setDateFinValiditePj(LocalDate dateFinValiditePj) {
this.dateFinValiditePj = dateFinValiditePj;
}
public LocalDate getDateSignaturePj() {
return dateSignaturePj;
}
public void setDateSignaturePj(LocalDate dateSignaturePj) {
this.dateSignaturePj = dateSignaturePj;
}
public LocalDateTime getDateHeureSaisiePj() {
return dateHeureSaisiePj;
}
public void setDateHeureSaisiePj(LocalDateTime dateHeureSaisiePj) {
this.dateHeureSaisiePj = dateHeureSaisiePj;
}
public LocalDateTime getDateHeureValidationPj() {
return dateHeureValidationPj;
}
public void setDateHeureValidationPj(LocalDateTime dateHeureValidationPj) {
this.dateHeureValidationPj = dateHeureValidationPj;
}
public Integer getEstValidePj() {
return estValidePj;
}
public void setEstValidePj(Integer estValidePj) {
this.estValidePj = estValidePj;
}
/**
* #return the typePj
*/
public TypePj getTypePj() {
return typePj;
}
/**
* #param typePj the typePj to set
*/
public void setTypePj(TypePj typePj) {
this.typePj = typePj;
}
public Beneficiaire getBeneficiairePj() {
return beneficiairePj;
}
public void setBeneficiairePj(Beneficiaire beneficiairePj) {
this.beneficiairePj = beneficiairePj;
}
public Utilisateur getUtilisateurSaisiePj() {
return utilisateurSaisiePj;
}
public void setUtilisateurSaisiePj(Utilisateur utilisateurSaisiePj) {
this.utilisateurSaisiePj = utilisateurSaisiePj;
}
public Utilisateur getUtilisateurValidationPj() {
return utilisateurValidationPj;
}
public void setUtilisateurValidationPj(Utilisateur utilisateurValidationPj) {
this.utilisateurValidationPj = utilisateurValidationPj;
}
//For Test Equal, override equals() and hashCode()
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PieceJustificative pieceJustificative = (PieceJustificative) o;
return noPj.equals(pieceJustificative.getNoPj());
}
#Override
public int hashCode() {
return Objects.hash(noPj);
}
}
My thymeleaf rendered view for list of PieceJustificative :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layouts/layout">
<head>
<meta charset="UTF-8" />
<title>Liste des pièces justificatives</title>
<!-- <link th:href="#{/css/form.css}" rel="stylesheet"/> -->
</head>
<body>
<div id="content" layout:fragment="content">
<div class="w3-container">
<h2>Liste des pièces justificatives</h2>
<!-- <table class="w3-table-all w3-hoverable"> -->
<table id="customers">
<thead>
<!-- <tr class="w3-light-grey"> -->
<tr >
<th>N° pièce jointe</th>
<th>Type pièce jointe</th>
<th>N° bénéficiaire</th>
<th>Nom bénéficiaire</th>
<th>Date début validité</th>
<th>Date fin validité</th>
<th>Date signature</th>
<th>Modifier</th>
<th>Supprimer</th>
</tr>
</thead>
<tr th:each="pieceJustificative : ${pieceJustificatives}">
<td th:text="${pieceJustificative.noPj}">N°</td>
<td th:text="${pieceJustificative.typePj.libelleTypePj}">libelleTypePj</td>
<td th:text="${pieceJustificative.beneficiairePj.noBenef}">noBenef</td>
<td th:text="${pieceJustificative.beneficiairePj.nomBenef}">nomBenef</td>
<td th:text="${#temporals.format(pieceJustificative.dateDebutValiditePj, 'dd/MM/yyyy')}">dateDebutValiditePj</td>
<td th:text="${#temporals.format(pieceJustificative.dateFinValiditePj, 'dd/MM/yyyy')}">dateFinValiditePj</td>
<td th:text="${#temporals.format(pieceJustificative.dateSignaturePj, 'dd/MM/yyyy')}">dateSignaturePj</td>
<td>Modifier</td>
<td>Supprimer</td>
</tr>
</table>
</div>
<p>
Ajouter pièce justificative
</p>
</div><!-- end div content -->
When I tried to render this list of PieceJustificative, I got this exception, however the Beneficiaire with id 57271 exist in my database :
javax.persistence.EntityNotFoundException: Unable to find ne.cnss.pension.beneficiaire.Beneficiaire with id 57271
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:144) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:154) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:128) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1133) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:992) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:930) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2600) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.Loader.list(Loader.java:2424) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:50) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:329) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:74) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at com.sun.proxy.$Proxy162.findAll(Unknown Source) ~[na:na]
at ne.cnss.pension.piecejustificative.PieceJustificativeService.listeDesPiecesJustificatives(PieceJustificativeService.java:101) ~[classes/:na]
at ne.cnss.pension.piecejustificative.PieceJustificativeController.listeDesCategoriesPieceJustificatives(PieceJustificativeController.java:117) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Try fetch=FetchType.EAGER
Default is lazy. It should work.
Related
This question already has an answer here:
Convert between LocalDate and sql.Date [duplicate]
(1 answer)
Closed 4 years ago.
hello i need to display a date column in a tableview; in the database I declare the field fecha_nacimiento as date , i used a datepicker to insert that data into the database, so far its Ok with that operation so the next step was formatting the tableview cell to display the date data correctly, with the help of this site i did that, but when i need to retrieve the date data from the database i am getting an error, something like this:
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
this is some of my controller code
public void initialize(URL arg0, ResourceBundle arg1) {
clienteid.setCellValueFactory(new PropertyValueFactory <Persona, Integer>("id_cliente"));
nombrescol.setCellValueFactory(new PropertyValueFactory <Persona, String>("nombres"));
apellidoscol.setCellValueFactory(new PropertyValueFactory <Persona, String>("apellidos"));
//fechacli.setCellValueFactory(new PropertyValueFactory <Persona, LocalDate>("fechacliente"));//
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
fechacli.setCellFactory(column -> {
return new TableCell<Persona, LocalDate>() {
#Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(formatter.format(item));
}
}
};
});
seleccionaregistros();
seleccionanombre();
seleccionapellido();
}
public void seleccionaregistros() {
ObservableList <Persona> data =FXCollections.observableArrayList();
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement mostrar=conn.createStatement();
ResultSet rs;
rs= mostrar.executeQuery("select * from cliente");
while ( rs.next() )
{
data.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
tablacliente.setItems(data);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
this is my persona class code
package application;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Persona {
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
private ObjectProperty <LocalDate>fechacliente;
public Persona (String nombres, String apellidos, Integer id_cliente, LocalDate fechacliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
this.fechacliente= new SimpleObjectProperty<>(fechacliente);
}
public LocalDate getFechaCliente() {
return fechacliente.get();
}
public void setFechaCliente(LocalDate fechacliente) {
this.fechacliente = new SimpleObjectProperty<>(fechacliente);
}
public ObjectProperty<LocalDate> fechaClienteProperty() {
return fechacliente;
}
public String getNombres() {
return nombres.get();
}
public void setNombres(String nombres) {
this.nombres=new SimpleStringProperty (nombres);
}
public String getApellidos() {
return apellidos.get();
}
public void setApellidos(String apellidos) {
this.apellidos=new SimpleStringProperty ( apellidos);
}
public Integer getId_cliente() {
return id_cliente.get();
}
public void setid_cliente(Integer id_cliente) {
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
}
id have been reading, and i found that can't truncate or pass the data beetween Localdate and Date, so any help could be truly helpful. regards.
all the errors here:
javafx.fxml.LoadException:
/C:/Users/ROA%20PC/eclipse-workspace/Conexion/bin/application/Vista.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at application.Main.start(Main.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
at application.ConexionController.seleccionaregistros(ConexionController.java:190)
at application.ConexionController.initialize(ConexionController.java:92)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 17 more
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Root cannot be null
at javafx.scene.Scene.<init>(Scene.java:336)
at javafx.scene.Scene.<init>(Scene.java:235)
at application.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application application.Main
The java.sql.Date is a java.util.Date subclass that holds no time information, so you can’t convert it to an Instant class.
Fortunately, there is a toLocalDate method that does just that, convert it directly to LocalDate.
It should be like this:
rs.getDate(4).toLocalDate();
For further reference take a look at the JavaDoc https://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#toInstant--
I have my service endpoint invoking get() method on my DAO, but fails with java.lang.NullPointerException. while debuging it seems Spring cannot find the implementation of my DAO
ContactEndoint
package com.spring.contacts;
#Endpoint
#Configuration
#ComponentScan(basePackages="com.spring.contacts")
#EnableWebMvc
public class ContactEndpoint {
private static final String NAMESPACE_URI = "http://spring.io/guides/gs-producing-web-service";
#Autowired
private ContactDAO contactDAO;
//Default constructor
public ContactEndpoint(){
}
#Autowired
public ContactEndpoint(ContactDAO contactDAO) {
this.contactDAO = contactDAO;
}
#Cacheable(cacheName="imageCache", keyGenerator=#KeyGenerator(name="StringKeyCache"))
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getContactRequest")
#RequestMapping(value = "/editContact", method = RequestMethod.GET)
#ResponsePayload
public GetContactResponse getContact(#RequestPayload GetContactRequest request){
GetContactResponse response = new GetContactResponse();
response.setContact(contactDAO.get(request.getId()));
return response;
}
ContactDAO
package com.spring.contacts.dao;
public interface ContactDAO {
public Contact get(int contactId);
ContactDAOImpl
package com.spring.contacts.dao;
#Repository("contactDAO")
public class ContactDAOImpl implements ContactDAO {
private JdbcTemplate jdbcTemplate;
//default constructor
public ContactDAOImpl(){
}
public ContactDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
#Override
public Contact get(int contactId) {
String sql = "SELECT * FROM contact WHERE contact_id=" + contactId;
return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
#Override
public Contact extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contact contact = new Contact();
contact.setId(rs.getInt("contact_id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));
contact.setAdress(rs.getString("address"));
contact.setTelephone(rs.getString("telephone"));
return contact;
}
return null;
}
});
}
WebServiceConfig
package com.spring.contacts;
#EnableWs
#Configuration
#ComponentScan("com.spring")
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
#Bean(name = "contacts")
public DefaultWsdl11Definition defaultContactsWsdl11Definition(XsdSchema contactsSchema){
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("ContactsPort");
wsdl11Definition.setLocationUri("/ws/JDBC");
wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(contactsSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries/countries.xsd"));
}
#Bean
public XsdSchema contactsSchema(){
return new SimpleXsdSchema(new ClassPathResource("contacts/contact.xsd"));
}
StackTrace
java.lang.NullPointerException: null
at com.spring.contacts.dao.ContactDAOImpl.get(ContactDAOImpl.java:85) ~[ContactDAOImpl.class:na]
at com.spring.contacts.dao.ContactDAOImpl$$FastClassBySpringCGLIB$$f0feb335.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653) ~[spring-aop-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.spring.contacts.dao.ContactDAOImpl$$EnhancerBySpringCGLIB$$5f3048d3.get(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at com.spring.contacts.ContactEndpoint.getContact(ContactEndpoint.java:45) ~[ContactEndpoint.class:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_25]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_25]
at org.springframework.ws.server.endpoint.MethodEndpoint.invoke(MethodEndpoint.java:134) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter.invokeInternal(DefaultMethodEndpointAdapter.java:291) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.endpoint.adapter.AbstractMethodEndpointAdapter.invoke(AbstractMethodEndpointAdapter.java:55) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.MessageDispatcher.dispatch(MessageDispatcher.java:236) [spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.server.MessageDispatcher.receive(MessageDispatcher.java:176) [spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.transport.support.WebServiceMessageReceiverObjectSupport.handleConnection(WebServiceMessageReceiverObjectSupport.java:89) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter.handle(WebServiceMessageReceiverHandlerAdapter.java:61) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.ws.transport.http.MessageDispatcherServlet.doService(MessageDispatcherServlet.java:293) ~[spring-ws-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) ~[servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) ~[spring-webmvc-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.21]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-websocket.jar:8.0.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) ~[catalina.jar:8.0.21]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) ~[catalina.jar:8.0.21]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) ~[catalina.jar:8.0.21]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) ~[catalina.jar:8.0.21]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) ~[catalina.jar:8.0.21]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) ~[catalina.jar:8.0.21]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) ~[tomcat-coyote.jar:8.0.21]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) ~[tomcat-coyote.jar:8.0.21]
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223) ~[tomcat-coyote.jar:8.0.21]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517) ~[tomcat-coyote.jar:8.0.21]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474) ~[tomcat-coyote.jar:8.0.21]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_25]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-util.jar:8.0.21]
at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25]
I fixed it by injecting datasource to DAOImpl using #Autowired
#Autowired
public ContactDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
the contest is: TomEE 7.0 with openEjb 4.7.1. I'm try to create an instance of an Entity Bean, EJB Entity 2.1 BMP (Bean Managed Persistence).
The Deploy of the bean work fine, also the creating of the remote home interface on a client example application, but when i try to create an istance of the entity bean, an error occur.
The code of the Entity is:
Home interface BmpEntityHome.java
package it.enzo.ejb.entity.bmp;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
import javax.ejb.FinderException;
public interface BmpEntityHome extends EJBHome {
//Metodo Creazione
public BmpEntityBean createObject(String id) throws RemoteException, CreateException;
//Metodo finder
public BmpEntityBean findByPrimaryKey(String key) throws RemoteException, FinderException;
//Metodo di logica personalizzato
//public int getMetodoPersonalizzato() throws RemoteException;
}
Remote interface BmpEntityObject.java
package it.enzo.ejb.entity.bmp;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface BmpEntityObject extends EJBObject{
public String getId() throws RemoteException;
public void setId(String id) throws RemoteException;
public String getValore1() throws RemoteException;
public void setValore1(String x) throws RemoteException;
public String getValore2() throws RemoteException;
public void setValore2(String x) throws RemoteException;
public int getAddizzione() throws RemoteException;
//Metodo di logica
//public void addizziona(int a, int b) throws RemoteException;
}
Bean interface BmpEntityBean.java
package it.enzo.ejb.entity.bmp;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
public class BmpEntityBean implements EntityBean{
private static final long serialVersionUID = 1L;
private EntityContext ectx;
private String iD;
private String valore1;
private String valore2;
private int addizzione;
//Costruttore
public BmpEntityBean(){
System.out.println("BmbRntityBean chiamato il costruttore");
}
//Metodo di business
public void addizziona(int a, int b){
this.addizzione = a + b;
}
//Metodi getter e setter
public String getId() {
return iD;
}
public void setId(String iD) {
this.iD = iD;
}
public String getValore1() {
return valore1;
}
public void setValore1(String valore1) {
this.valore1 = valore1;
}
public String getValore2() {
return valore2;
}
public void setValore2(String valore2) {
this.valore2 = valore2;
}
public int getAddizzione() {
return addizzione;
}
//Metodo privato per creare la connessione al DB
private Connection getConnection(){
Connection cnn = null;
try {
Class.forName("org.sqlite.JDBC");
cnn = DriverManager.getConnection("jdbc:sqlite:EJBdatabase.db");
this.CreaTabelle(cnn);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cnn;
}
private void CreaTabelle(Connection cnn){
Statement stat = null;
try {
stat = cnn.createStatement();
stat.executeUpdate("CREATE TABLE if not exists BmpEntityBeanTable (id string primary key, valore1 string, valore2 string, addizzione integer)");
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Metodo finder
public String ejbFindByPrimaryKey(String key) throws FinderException{
PreparedStatement pstm = null;
Connection cnn = null;
try{
cnn = this.getConnection();
pstm = cnn.prepareStatement("SELECT id FROM BmpEntityBeanTable WHERE id = ?");
pstm.setString(1, key);
ResultSet rs = pstm.executeQuery();
if(rs.next())return key;
}catch(Exception e){e.printStackTrace();}
finally{
try {
pstm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cnn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
throw new FinderException("Entity con id "+key+" non Trovato");
}
//Metodo personalizzato sull'oggetto Home
//public int ejbHomeGetMetodoPersonalizzato(){
//return 2976;
//}
//Metodi di callback richiamati dal container
//Metodo di creazione
public BmpEntityBean ejbCreateObject(String id) throws CreateException{
Connection cnn = null;
PreparedStatement pstm = null;
this.iD = id;
try{
cnn = this.getConnection();
pstm = cnn.prepareStatement("INSERT INTO BmpEntityBeanTable (id) values ('"+id+"')");
pstm.execute();
return this;
}catch(Exception e){e.printStackTrace();}
finally{
try {
pstm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cnn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
throw new CreateException();
}
#Override
public void setEntityContext(EntityContext ctx) throws EJBException,
RemoteException {
// TODO Auto-generated method stub
this.ectx = ctx;
}
#Override
public void unsetEntityContext() throws EJBException, RemoteException {
// TODO Auto-generated method stub
this.ectx = null;
}
#Override
public void ejbRemove() throws RemoveException, EJBException,
RemoteException {
// TODO Auto-generated method stub
String key = (String) this.ectx.getPrimaryKey();
String id = key;
Connection cnn = null;
PreparedStatement pstm = null;
try{
cnn = this.getConnection();
pstm = cnn.prepareStatement("DELETE FROM BmpEntityBeanTable WHERE id = ?");
pstm.setString(1, id);
pstm.execute();
}catch(Exception e){e.printStackTrace();}
finally{
try {
pstm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cnn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void ejbActivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbPassivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbLoad() throws EJBException, RemoteException {
// TODO Auto-generated method stub
String key = (String) this.ectx.getPrimaryKey();
String id = key;
Connection cnn = null;
PreparedStatement pstm = null;
try{
cnn = this.getConnection();
pstm = cnn.prepareStatement("SELECT * FROM BmpEntityBeanTable WHERE id = ?");
pstm.setString(1, id);
ResultSet rs = pstm.executeQuery();
if(rs.next()){
this.iD = id;
this.valore1 = rs.getString("valore1");
this.valore2 = rs.getString("valore2");
this.addizzione = rs.getInt("addizzione");
}
rs.close();
}catch(Exception e){e.printStackTrace();}
finally{
try {
pstm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cnn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void ejbStore() throws EJBException, RemoteException {
// TODO Auto-generated method stub
String key = (String) this.ectx.getPrimaryKey();
String id = key;
Connection cnn = null;
PreparedStatement pstm = null;
try{
cnn = this.getConnection();
pstm = cnn.prepareStatement("UPDATE BmpEntityBeanTable set valore1 = ?, valore2 = ?, addizione = ? WHERE id = ?");
pstm.setString(1, this.valore1);
pstm.setString(2, this.valore2);
pstm.setInt(3, this.addizzione);
pstm.setString(4, id);
pstm.execute();
}catch(Exception e){e.printStackTrace();}
finally{
try {
pstm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
cnn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Deploy desciptor ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"
version="2.1">
<enterprise-beans>
<entity>
<ejb-name>BmpEntity</ejb-name>
<home>it.enzo.ejb.entity.bmp.BmpEntityHome</home>
<remote>it.enzo.ejb.entity.bmp.BmpEntityObject</remote>
<ejb-class>it.enzo.ejb.entity.bmp.BmpEntityBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>false</reentrant>
<primkey-field>iD</primkey-field>
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>BmpEntity</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
Client Example application
package it.enzo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.ejb.CreateException;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ProvaServ
*/
#WebServlet("/ProvaServ")
public class ProvaServ extends HttpServlet {
private static final long serialVersionUID = 1L;
private it.enzo.ejb.entity.bmp.BmpEntityHome bmpEntityHome = null;
public ProvaServ() {
super();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String comm = request.getParameter("comm");
if(comm!=null){
switch(comm.toString()){
case "bmpEntity_Start":
this.bmpEntityHome = null;
this.callBmpEntity();
break;
case "bmpEntity_Create":
if(this.bmpEntityHome!=null){
try {
String id = request.getParameter("id");
//it.enzo.ejb.entity.bmp.BmpEntityBean bmpEntityBean_TMP =
this.bmpEntityHome.createObject(id);
out.print("BmpEntity aggiunto: ");//+bmpEntityBean_TMP.getId());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
out.print("<div><form action=''>"
+"<input type='hidden' name='comm' value='bmpEntity_Create'>"
+"Aggiungi un BmpEntity <input type='text' name='id' value='ID-DELL-ENTITY-1'>"
+"<input type='submit' value='Aggiungi'>"
+"</form></div>");
out.print("<br><br><a href='?comm=bmpEntity_Start'>Start BMPEntity</a><br>");
}
private void callBmpEntity(){
if(this.bmpEntityHome==null){
Properties p = new Properties();
p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
p.put("java.naming.provider.url", "http://localhost:8080/tomee/ejb");
InitialContext initialContext;
Object object = null;
try {
initialContext = new InitialContext(p);
object = initialContext.lookup("BmpEntityRemoteHome");
this.bmpEntityHome = (it.enzo.ejb.entity.bmp.BmpEntityHome)
PortableRemoteObject.narrow(object, it.enzo.ejb.entity.bmp.BmpEntityHome.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
the stack error
nov 23, 2014 9:36:48 AM org.apache.openejb.core.transaction.EjbTransactionUtil handleSystemException
GRAVE: EjbTransactionUtil.handleSystemException: object is not an instance of declaring class
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.openejb.core.entity.EntityContainer.createEJBObject(EntityContainer.java:340)
at org.apache.openejb.core.entity.EntityContainer.invoke(EntityContainer.java:182)
at org.apache.openejb.server.ejbd.EjbRequestHandler.doEjbHome_CREATE(EjbRequestHandler.java:420)
at org.apache.openejb.server.ejbd.EjbRequestHandler.processRequest(EjbRequestHandler.java:187)
at org.apache.openejb.server.ejbd.EjbDaemon.processEjbRequest(EjbDaemon.java:344)
at org.apache.openejb.server.ejbd.EjbDaemon.service(EjbDaemon.java:240)
at org.apache.openejb.server.ejbd.EjbServer.service(EjbServer.java:86)
at org.apache.openejb.server.httpd.ServerServlet.service(ServerServlet.java:58)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
java.rmi.RemoteException: The bean encountered a non-application exception; nested exception is:
java.lang.IllegalArgumentException: object is not an instance of declaring class
at org.apache.openejb.core.transaction.EjbTransactionUtil.handleSystemException(EjbTransactionUtil.java:155)
at org.apache.openejb.core.entity.EntityContainer.handleException(EntityContainer.java:484)
at org.apache.openejb.core.entity.EntityContainer.createEJBObject(EntityContainer.java:369)
at org.apache.openejb.core.entity.EntityContainer.invoke(EntityContainer.java:182)
at org.apache.openejb.server.ejbd.EjbRequestHandler.doEjbHome_CREATE(EjbRequestHandler.java:420)
at org.apache.openejb.server.ejbd.EjbRequestHandler.processRequest(EjbRequestHandler.java:187)
at org.apache.openejb.server.ejbd.EjbDaemon.processEjbRequest(EjbDaemon.java:344)
at org.apache.openejb.server.ejbd.EjbDaemon.service(EjbDaemon.java:240)
at org.apache.openejb.server.ejbd.EjbServer.service(EjbServer.java:86)
at org.apache.openejb.server.httpd.ServerServlet.service(ServerServlet.java:58)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.openejb.core.entity.EntityContainer.createEJBObject(EntityContainer.java:340)
... 25 more
The error origin in the class EntityContainer.class of the package openejb-core-4.7.1.jar
....
protected ProxyInfo createEJBObject(final Method callMethod, final Object[] args, final ThreadContext callContext, final InterfaceType type) throws OpenEJBException {
final BeanContext beanContext = callContext.getBeanContext();
callContext.setCurrentOperation(Operation.CREATE);
/*
* According to section 9.1.5.1 of the EJB 1.1 specification, the "ejbPostCreate(...)
* method executes in the same transaction context as the previous ejbCreate(...) method."
*
* For this reason the TransactionScopeHandler methods usally preformed by the invoke( )
* operation must be handled here along with the call explicitly.
* This ensures that the afterInvoke() is not processed between the ejbCreate and ejbPostCreate methods to
* ensure that the ejbPostCreate executes in the same transaction context of the ejbCreate.
* This would otherwise not be possible if container-managed transactions were used because
* the TransactionScopeManager would attempt to commit the transaction immediately after the ejbCreate
* and before the ejbPostCreate had a chance to execute. Once the ejbPostCreate method execute the
* super classes afterInvoke( ) method will be executed committing the transaction if its a CMT.
*/
final TransactionPolicy txPolicy = createTransactionPolicy(beanContext.getTransactionType(callMethod, type), callContext);
EntityBean bean = null;
Object primaryKey = null;
try {
// Get new ready instance
bean = instanceManager.obtainInstance(callContext);
// Obtain the proper ejbCreate() method
final Method ejbCreateMethod = beanContext.getMatchingBeanMethod(callMethod);
//HERE THE ERROR
// invoke the ejbCreate which returns the primary key
primaryKey = ejbCreateMethod.invoke(bean, args);//HERE THE ERROR
didCreateBean(callContext, bean);
// determine post create callback method
final Method ejbPostCreateMethod = beanContext.getMatchingPostCreateMethod(ejbCreateMethod);
// create a new context containing the pk for the post create call
final ThreadContext postCreateContext = new ThreadContext(beanContext, primaryKey);
postCreateContext.setCurrentOperation(Operation.POST_CREATE);
final ThreadContext oldContext = ThreadContext.enter(postCreateContext);
try {
// Invoke the ejbPostCreate method on the bean instance
ejbPostCreateMethod.invoke(bean, args);
// According to section 9.1.5.1 of the EJB 1.1 specification, the "ejbPostCreate(...)
// method executes in the same transaction context as the previous ejbCreate(...) method."
//
// The bean is first insterted using db.create( ) and then after ejbPostCreate( ) its
// updated using db.update(). This protocol allows for visablity of the bean after ejbCreate
// within the current trasnaction.
} finally {
ThreadContext.exit(oldContext);
}
// update pool
instanceManager.poolInstance(callContext, bean, primaryKey);
} catch (final Throwable e) {
handleException(txPolicy, e, callContext, bean);
} finally {
afterInvoke(txPolicy, callContext);
}
return new ProxyInfo(beanContext, primaryKey);
}
....
When i try this in the client example:
....
this.bmpEntityHome.createObject(id);
....
in the class EntityContainer.class of the package openejb-core-4.7.1.jar is called this method:
...
protected ProxyInfo createEJBObject(final Method callMethod, final Object[]...
...
and at the line 340 the instruction:
...
// invoke the ejbCreate which returns the primary key
primaryKey = ejbCreateMethod.invoke(bean, args);
...
generate the exception:
...
EjbTransactionUtil.handleSystemException: object is not an instance of declaring class
...
Thank!
Resolved... i have missed the 'ejbPostCreate' method in BmpEntityBean.class class (Business class)....
So, I'm doing a JavaFX multiview GUI application.
Below is the code so that you can refer to it, don't read through it to find an error yet, I'll explain the problem underneath first ;)
I have a main - which starts the application
public class MyFXMLMain extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Wireframe.fxml"));
stage.setTitle("My Fitness App");
Scene mainScene = new Scene(root,805,809);
stage.setScene(mainScene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
ScreensController - that controls loading/setting screens.
public class ScreensController extends StackPane {
private HashMap<String, Node> screens = new HashMap<>();
public ScreensController() {
super();
}
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
public Node getScreen(String name) {
return screens.get(name);
}
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenController = ((ControlledScreen) myLoader.getController());
myScreenController.setScreenParent(this);
addScreen(name, loadScreen);
return true;
}catch(Exception e) {
System.out.println(e.getMessage());
return false;
}
}
public boolean setScreen(final String name) {
if (screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
if (!getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
getChildren().remove(0); //remove the displayed screen
getChildren().add(0, screens.get(name)); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(800), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
setOpacity(0.0);
getChildren().add(screens.get(name)); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}
}
public boolean unloadScreen(String name) {
if (screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
A screen framework - that links the screens to the FXML files.
public class ScreensFramework extends Application {
public static String MAIN_SCREEN = "MyFXMLController";
public static String MAIN_SCREEN_FXML = "Wireframe.fxml";
public static String calendarScreen = "CalendarscreenController";
public static String calendarScreenFXML = "Calendarscreen.fxml";
public static String guideScreen = "GuideScreenController";
public static String guideScreenFXML ="Guidescreen.fxml";
#Override
public void start(Stage primaryStage) {
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(ScreensFramework.MAIN_SCREEN, ScreensFramework.MAIN_SCREEN_FXML);
mainContainer.loadScreen(ScreensFramework.calendarScreen,ScreensFramework.calendarScreenFXML);
mainContainer.loadScreen(ScreensFramework.guideScreen,ScreensFramework.guideScreenFXML);
mainContainer.setScreen(ScreensFramework.MAIN_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
An FXML controller - which links to the FXML files and tells FXML what to do when something is clicked.
public class MyFXMLController implements ControlledScreen{
#FXML private TextField givenName;
#FXML private Text targetText;
//#FXML private static TableView<Mass> theTable;
//#FXML private static TableColumn<Mass, String> dateCol;
//#FXML private static TableColumn<Mass, String> massCol;
#FXML private static LineChart<Number,Number> weightChart;
#FXML private static NumberAxis axisX;
#FXML private static NumberAxis axisY;
#FXML private static Label myLabel;
//private static User theUser = new User();
private static ScreensController myController;
#Override
public void setScreenParent(ScreensController screenPage) {
myController = screenPage;
}
#FXML protected void handlePressedCalendarButtonAction(ActionEvent event){
System.out.println("Hello");
}
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
}
A controlledscreen - that does this:
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
And a CalendarScreenController - that controls one of the multi screens
public class CalendarScreenController implements Initializable, ControlledScreen {
ScreensController myController;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
public void setScreenParent(ScreensController screenParent){
myController = screenParent;
}
#FXML
private void goToMain(ActionEvent event){
myController.setScreen(ScreensFramework.MAIN_SCREEN);
}
}
PROBLEM BELOW
When I run my program it works fine, but then if I click on a button that activates the calendar onclick code here:
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
which should set the screen to CalendarScreen.fxml,one of my multi screens but instead, it causes an error below:
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$ClickGenerator.postProcess(Unknown Source)
at javafx.scene.Scene$ClickGenerator.access$8600(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1900(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$3$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 31 more
Caused by: java.lang.NullPointerException
at myfxml.MyFXMLController.mouseclickedcal(MyFXMLController.java:125)
... 40 more
Line 125 is the code:
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
Thank you so much for having a look at this. I can't seem to find the error ;(
Turns out I had 2 mains and they were conflicting and also in my xml code I was calling something that didn't exist in its controller.
I &m trying to expose my data base using a web service , i am using a postgresql data base , ejb 3.1 and , CXF as webservice framework.
This is the entity
package persistance.model;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: ENVOI
*
*/
#Entity
#Table(name = "Envoi")
#NamedQueries({#NamedQuery(name="Envoi.getAll", query="Select e from Envoi e")})
public class Envoi implements Serializable {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column
private int Numet;
#Column
private int Numseq;
#Column
private int Valadler;
#Column
private String Typemess;
#Column
#Temporal(TemporalType.DATE)
private Date Horodatage;
#Column
private String Appli;
#Column
private String Versproto;
#Column
private String Data;
#Column
private String ACK;
private static final long serialVersionUID = 1L;
public Envoi() {
super();
}
public int getNumet() {
return this.Numet;
}
public void setNumet(int Numet) {
this.Numet = Numet;
}
public int getNumseq() {
return this.Numseq;
}
public void setNumseq(int Numseq) {
this.Numseq = Numseq;
}
public int getValadler() {
return this.Valadler;
}
public void setValadler(int Valadler) {
this.Valadler = Valadler;
}
public String getTypemess() {
return this.Typemess;
}
public void setTypemess(String Typemess) {
this.Typemess = Typemess;
}
public Date getHorodatage() {
return this.Horodatage;
}
public void setHorodatage(Date Horodatage) {
this.Horodatage = Horodatage;
}
public String getAppli() {
return this.Appli;
}
public void setAppli(String Appli) {
this.Appli = Appli;
}
public String getVersproto() {
return this.Versproto;
}
public void setVersproto(String Versproto) {
this.Versproto = Versproto;
}
public int getId() {
return this.Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getData() {
return this.Data;
}
public void setData(String Data) {
this.Data = Data;
}
public String getACK() {
return this.ACK;
}
public void setACK(String ACK) {
this.ACK = ACK;
}
}
Now here the DAO
this one is generic
package persistance.dao;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//import javax.persistence.criteria.CriteriaQuery;
public abstract class GenericDAO<T> {
private final static String UNIT_NAME = "MestaPU";
#PersistenceContext(unitName = UNIT_NAME)
private EntityManager em;
private Class<T> entityClass;
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void save(T entity) {
em.persist(entity);
}
protected void delete(Object id, Class<T> classe) {
T entityToBeRemoved = em.getReference(classe, id);
em.remove(entityToBeRemoved);
}
public T update(T entity) {
return em.merge(entity);
}
public T find(int entityID) {
return em.find(entityClass, entityID);
}
// Using the unchecked because JPA does not have a
// em.getCriteriaBuilder().createQuery()<T> method
/* #SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}*/
// Using the unchecked because JPA does not have a
// ery.getSingleResult()<T> method
/* #SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = em.createNamedQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}*/
/* private void populateQueryParameters(Query query, Map<String, Object> parameters) {
for (Entry<String, Object> entry : parameters.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}*/
}
this one is spécifique to Envoi entity
package persistance.dao;
import javax.ejb.Stateless;
import persistance.model.*;
#Stateless
public class EnvoiDAO extends GenericDAO<Envoi> {
public EnvoiDAO() {
super(Envoi.class);
}
public void delete(Envoi envoi) {
super.delete(envoi.getId(), Envoi.class);
}
}
This is the Facade to expose the ejb
package persistance.facade;
import java.util.List;
import javax.ejb.Local;
import javax.jws.WebService;
import persistance.model.Envoi;
#WebService
#Local
public interface EnvoiFacade {
public abstract void save(Envoi envoi);
public abstract Envoi update(Envoi envoi);
public abstract void delete(Envoi envoi);
public abstract Envoi find(int entityID);
public abstract List<Envoi> findAll();
}
package persistance.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import persistance.dao.EnvoiDAO;
import persistance.model.Envoi;
#WebService
#Stateless
public class EnvoiFacadeImp implements EnvoiFacade {
#EJB
private EnvoiDAO envoiDAO;
public void save(Envoi envoi) {
envoiDAO.save(envoi);
}
public Envoi update(Envoi envoi) {
return envoiDAO.update(envoi);
}
public void delete(Envoi envoi) {
envoiDAO.delete(envoi);
}
public Envoi find(int entityID) {
// TODO Auto-generated method stub
return null;
}
public List<Envoi> findAll() {
// TODO Auto-generated method stub
return null;
}
/*public Envoi find(int entityID) {
return envoiDAO.find(entityID);
}*/
/*public List<Envoi> findAll() {
return envoiDAO.findAll();
}*/
}
Now you will find the spring bean that publishes the service
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint
id="orderProcess"
implementor="demo.order.OrderProcessImpl"
address="/OrderProcess" />
<jaxws:endpoint
id="EnvoiFacade"
implementor="persistance.facade.EnvoiFacadeImp"
address="/EnvoiFacade" />
</beans>
Now you'll find the client and the bean associated to it
package demo.ejb.client;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import persistance.facade.EnvoiFacade;
import persistance.model.Envoi;
public final class Client {
public Client() {
}
public static void main(String args[]) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "demo/ejb/client/client-beans.xml" });
EnvoiFacade client = (EnvoiFacade) context.getBean("envoiClient");
Envoi p1 = new Envoi();
p1.setNumet(3690);
p1.setNumseq(9990);
client.save(p1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:client id="envoiClient" serviceClass="persistance.facade.EnvoiFacade" address="http://localhost:8080/orderapp/EnvoiFacade" >
</jaxws:client>
</beans>
Now my webservice deploy just fin in JBOSS 7.1.0 AS , i created the datasources and included the driver for postgres my sql , the problem is when a run the client i get this error
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Fault occurred while processing.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:143)
at $Proxy57.save(Unknown Source)
at demo.ejb.client.Client.main(Client.java:23)
Caused by: org.apache.cxf.binding.soap.SoapFault: Fault occurred while processing.
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.unmarshalFault(Soap11FaultInInterceptor.java:75)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:46)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:35)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:96)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:69)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:34)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:658)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2139)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2022)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1947)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:632)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:472)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:302)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:254)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:123)
... 2 more
I had a similar stack trace recently and I found out I was missing a classic setter on one of my fields.