One-to-many JPA EntityManager Primefaces - jpa

I have the following form inside a dialog:
<h:form id="CommentCreateForm">
<h:panelGroup id="display">
<p:outputPanel id="commentsPanel">
<p:row>
<p:column>
<p:inputTextarea id="commentText" value="#{commentsController.selected.commentText}" cols="100" rows="20" style="margin-bottom:10px"/>
</p:column>
</p:row>
</p:outputPanel>
<p:commandButton actionListener="#{commentsController.savePropReception}" value="#{myBundle.Save}" update="display,:PmMainListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,PF('CommentCreateDialog'));">
<p:confirm header="#{myBundle.ConfirmationHeader}" message="#{myBundle.ConfirmEditMessage}" icon="ui-icon-alert"/>
</p:commandButton>
</h:panelGroup>
</h:form>
With it's corresponding parent entity called Comments:
#Entity
#Table(name = "comments")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Comments.findAll", query = "SELECT c FROM Comments c")
, #NamedQuery(name = "Comments.findByCommentText", query = "SELECT c FROM Comments c WHERE c.commentText = :commentText")
, #NamedQuery(name = "Comments.findByIdComments", query = "SELECT c FROM Comments c WHERE c.idComments = :idComments")})
public class Comments implements Serializable {
private static final long serialVersionUID = 1L;
#Size(max = 2147483647)
#Column(name = "comment_text")
private String commentText;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_comments")
private Long idComments;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "propReceptionComment")
private List<PmMain> pmMainCollection5;
[... Getters and Setters ...]
public void setPropReception(PmMain pmMain){
pmMain.setPropReceptionComment(this);
pmMainCollection5.add(pmMain);
}
And it's child entity called PmMain:
#Entity
#Table(name = "pm_main")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "PmMain.findAll", query = "SELECT p FROM PmMain p")
, #NamedQuery(name = "PmMain.findByPropId", query = "SELECT p FROM PmMain p WHERE p.propId = :propId")
, #NamedQuery(name = "PmMain.findByPropName", query = "SELECT p FROM PmMain p WHERE p.propName = :propName")
, #NamedQuery(name = "PmMain.findByPropStatus", query = "SELECT p FROM PmMain p WHERE p.propStatus = :propStatus")
, #NamedQuery(name = "PmMain.findByIdPmMain", query = "SELECT p FROM PmMain p WHERE p.idPmMain = :idPmMain")})
public class PmMain implements Serializable {
private static final long serialVersionUID = 1L;
#Size(max = 25)
#Column(name = "prop_id")
private String propId;
#Size(max = 125)
#Column(name = "prop_name")
private String propName;
#Size(max = 25)
#Column(name = "prop_status")
private String propStatus;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_pm_main")
private Long idPmMain;
#JoinColumn(name = "prop_reception_comment", referencedColumnName = "id_comments")
#ManyToOne
private Comments propReceptionComment;
[... Getters and Setters ...]
And the CommentsController contains a method called savePropReception:
public void savePropReception(){
PmMain pmMain = new PmMain();
Comments comments = new Comments();
pmMain.setPropReceptionComment(comments);
comments.setPropReception(pmMain);
commentsFacadeEJB.edit(comments);
}
While commentsFacadeEJB contains:
public void edit(T entity) {
getEntityManager().merge(entity);
}
So, when a PmMain is already created, I can't get PmMain.propRecetionComment to update with the ID of a new 'Comments'. What am I missing?

Related

JPA JSF creating a new record doesn't update the page

The following p:dialog creates a new comment using:
<p:dialog id="buyDlg" widgetVar="buyDialog" modal="true" resizable="false" appendTo="#(body)"
header="#{myBundle.CreateCommentsTitle}" closeOnEscape="true" width="auto" height="auto">
<h:form id="buyCommentCreateForm">
<h:panelGroup id="buyDisplay">
<p:outputPanel id="buyCommentsPanel">
<p:row>
<p:column>
<p:editor id="commentText" value="#{commentsController.selected.commentText}" style="margin-bottom:10px"/>
</p:column>
</p:row>
</p:outputPanel>
<p:commandButton actionListener="#{commentsController.setBuyComment(pmMainController.selected.idPmMain, commentsController.selected.commentText)}" value="#{myBundle.Save}" update=":PmMainEditForm:display" oncomplete="handleSubmit(xhr,status,args,PF('buyDialog'));">
<p:confirm header="#{myBundle.ConfirmationHeader}" message="#{myBundle.ConfirmEditMessage}" icon="ui-icon-alert"/>
</p:commandButton>
<p:commandButton value="#{myBundle.Cancel}" oncomplete="PF('buyDialog').hide()" update="buyDisplay" process="#this" immediate="true" resetValues="true"/>
</h:panelGroup>
</h:form>
</p:dialog>
Where the save method is:
public void setBuyComment(long idPmMain, String commentText){
PmMain pmMain = pmMainFacadeEJB.find(idPmMain);
Comments comments = new Comments();
pmMain.setBuyComment(comments);
comments.setBuyComment(pmMain);
comments.setCommentText(commentText);
commentsFacadeEJB.edit(comments);
}
Everything works fine but I need to reload the page in order to visualize the comment id in PmMain (it gets inserted above where it says PmMain.setBuyComments(comments)). Any ideas?
EDIT
Adding information about setBuyComment:
For PmMain.setBuyComment I have:
public void setBuyComment(Comments buyComment) {
this.buyComment = buyComment;
}
And for comments.setBuyComment:
public void setBuyComment(PmMain pmMain){
pmMain.setBuyComment(this);
pmMainCollection24.add(pmMain);
}
EDIT 2
The backing Bean from PmMain looks like this:
#Entity
#Table(name = "pm_main")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "PmMain.findAll", query = "SELECT p FROM PmMain p")
, #NamedQuery(name = "PmMain.findByPropId", query = "SELECT p FROM PmMain p WHERE p.propId = :propId")
, #NamedQuery(name = "PmMain.findByPropName", query = "SELECT p FROM PmMain p WHERE p.propName = :propName")
, #NamedQuery(name = "PmMain.findByIdPmMain", query = "SELECT p FROM PmMain p WHERE p.idPmMain = :idPmMain")})
public class PmMain implements Serializable {
private static final long serialVersionUID = 1L;
#Size(max = 25)
#Column(name = "prop_id")
private String propId;
#Size(max = 125)
#Column(name = "prop_name")
private String propName;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_pm_main")
private Long idPmMain;
#JoinColumn(name = "buy_comment", referencedColumnName = "id_comments")
#ManyToOne
private Comments buyComment;
[... Getters and Setters ...]
And the Comments bean looks like:
#Entity
#Table(name = "comments")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Comments.findAll", query = "SELECT c FROM Comments c")
, #NamedQuery(name = "Comments.findByCommentText", query = "SELECT c FROM Comments c WHERE c.commentText = :commentText")
, #NamedQuery(name = "Comments.findByIdComments", query = "SELECT c FROM Comments c WHERE c.idComments = :idComments")})
public class Comments implements Serializable {
private static final long serialVersionUID = 1L;
#Size(max = 2147483647)
#Column(name = "comment_text")
private String commentText;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_comments")
private Long idComments;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "buyComment")
private List<PmMain> pmMainCollection24 = new ArrayList<>();
[... Getters and Setters ...]
public void setBuyComment(PmMain pmMain){
pmMain.setBuyComment(this);
pmMainCollection24.add(pmMain);
}

Criteria JPA - Specific attribute

I need to create a criteria query that represents the follow JPQL:
I tryed to specify the class RegraContrato but no success.
SELECT G FROM Grupo G JOIN G.regras R WHERE TYPE(R) = RegraContrato AND R.numeroContrato in(123)
#Entity
#Table(name = "GRUPO_ACESSO")
public class Grupo {
#OneToMany(mappedBy = "grupo",cascade = CascadeType.ALL,fetch = FetchType.EAGER,orphanRemoval = true)
private Set<Regra> regras = Sets.newHashSet();
}
#Entity
#Table(name = "REGRA_ACESSO")
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class Regra {
private static final long serialVersionUID = 5994730323053219858L;
#Id
#SequenceGenerator(name = "REGRA_ID_GENERATOR",sequenceName = "REGRA_SEQUENCE",allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "REGRA_ID_GENERATOR")
#Column(name = "ID")
private Long id;
}
#Entity
#PrimaryKeyJoinColumn(name = "ID")
#Table(name = "REGRA_CNPJ")
public class RegraCNPJ extends Regra {
#Column(name = "CNPJ")
private String cnpj;
}
#Entity
#PrimaryKeyJoinColumn(name = "ID")
#Table(name = "REGRA_CONTRATO")
public class RegraContrato extends Regra {
private static final long serialVersionUID = -2840125767126128182L;
#Column(name = "NUMERO_CONTRATO")
private Long numeroContrato;
}

Error in using JPA prepared statement

I am new to JPA. I'm trying to execute a prepared statement but I kept getting an error. Can you tell what's wrong? Thank you.
This is the entity with prepared statement:
#Entity
#Table(name = "TCMSPRUSR", schema="TCMS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.getName", query = "SELECT u.empnam FROM User u"),
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findByUserid", query = "SELECT u FROM User u WHERE u.userid = :userid"),
#NamedQuery(name = "User.findByEmpno", query = "SELECT u FROM User u WHERE u.empno = :empno"),
#NamedQuery(name = "User.findByEmpnam", query = "SELECT u FROM User u WHERE u.empnam = :empnam"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
#NamedQuery(name = "User.findByPassword1", query = "SELECT u FROM User u WHERE u.password1 = :password1"),
#NamedQuery(name = "User.findByPassword2", query = "SELECT u FROM User u WHERE u.password2 = :password2"),
#NamedQuery(name = "User.findByPassword3", query = "SELECT u FROM User u WHERE u.password3 = :password3"),
#NamedQuery(name = "User.findByPassword4", query = "SELECT u FROM User u WHERE u.password4 = :password4"),
#NamedQuery(name = "User.findByEffdte", query = "SELECT u FROM User u WHERE u.effdte = :effdte"),
#NamedQuery(name = "User.findByPcname", query = "SELECT u FROM User u WHERE u.pcname = :pcname"),
#NamedQuery(name = "User.findByAtmptcnt", query = "SELECT u FROM User u WHERE u.atmptcnt = :atmptcnt"),
#NamedQuery(name = "User.findByDaysexp", query = "SELECT u FROM User u WHERE u.daysexp = :daysexp"),
#NamedQuery(name = "User.findByPwdate", query = "SELECT u FROM User u WHERE u.pwdate = :pwdate"),
#NamedQuery(name = "User.findByStatdesc", query = "SELECT u FROM User u WHERE u.statdesc = :statdesc"),
#NamedQuery(name = "User.findByStatcode", query = "SELECT u FROM User u WHERE u.statcode = :statcode"),
#NamedQuery(name = "User.findByUseflg", query = "SELECT u FROM User u WHERE u.useflg = :useflg"),
#NamedQuery(name = "User.findByCuser", query = "SELECT u FROM User u WHERE u.cuser = :cuser"),
#NamedQuery(name = "User.findByCdate", query = "SELECT u FROM User u WHERE u.cdate = :cdate")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "USERID")
private String userid="0";
#Basic(optional = false)
#NotNull
#Column(name = "EMPNO")
private int empno;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "EMPNAM")
private String empnam;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "PASSWORD")
private String password;
#Size(max = 255)
#Column(name = "PASSWORD1")
private String password1;
#Size(max = 255)
#Column(name = "PASSWORD2")
private String password2;
#Size(max = 255)
#Column(name = "PASSWORD3")
private String password3;
#Size(max = 255)
#Column(name = "PASSWORD4")
private String password4;
#Basic(optional = false)
#NotNull
#Column(name = "EFFDTE")
#Temporal(TemporalType.DATE)
private Date effdte;
#Size(max = 255)
#Column(name = "PCNAME")
private String pcname;
#Basic(optional = false)
#NotNull
#Column(name = "ATMPTCNT")
private short atmptcnt;
#Basic(optional = false)
#NotNull
#Column(name = "DAYSEXP")
private short daysexp;
#Basic(optional = false)
#NotNull
#Column(name = "PWDATE")
#Temporal(TemporalType.DATE)
private Date pwdate;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "STATDESC")
private String statdesc;
#Basic(optional = false)
#NotNull
#Column(name = "STATCODE")
private long statcode;
#Column(name = "USEFLG")
private Short useflg;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "CUSER")
private String cuser;
#Basic(optional = false)
#NotNull
#Column(name = "CDATE")
#Temporal(TemporalType.DATE)
private Date cdate;
#JoinColumn(name = "ORGACODE", referencedColumnName = "ORGACODE")
#ManyToOne(optional = false)
private Organization orgacode;
#JoinColumn(name = "ROLEID", referencedColumnName = "ROLEID")
#ManyToOne(optional = false)
private Role roleid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userid")
private Collection<AuditTrail> auditTrailCollection;
This is the class that uses the prepared statement:
#Stateless
public class UserFacade {
#PersistenceContext(unitName = "TCMS-ejbPU")
private EntityManager em;
#SuppressWarnings("unchecked")
public List<User> findAll() {
List<User> uList = em.createQuery("SELECT u FROM User u").getResultList();
return uList;
}
#SuppressWarnings("unchecked")
public List<User> getName() {
List<User> uList = em.createQuery("SELECT u.empnam FROM User u").getResultList();
return uList;
}
}
The getName() method executed with no problem, but the findAll() method has error.
HERE IS THE STACK TRACE
[5/3/16 9:32:19:456 CST] 00000244 BusinessExcep E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "findAll" on bean "BeanId(TCMS#TCMSEJB.jar#UserFacade, null)". Exception data: <openjpa-2.2.3-SNAPSHOT-r422266:1686911 fatal general error> org.apache.openjpa.persistence.PersistenceException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=ASG2.TCMSPRUSR, DRIVER=4.13.127 {prepstmnt 1878102677 SELECT t0.USERID, t0.ATMPTCNT, t0.CDATE, t0.CUSER, t0.DAYSEXP, t0.EFFDTE, t0.EMPNAM, t0.EMPNO, t1.ORGACODE, t1.CDATE, t1.CUSER, t1.ORGAABBR, t1.ORGADESC, t1.STATUS, t0.PASSWORD, t0.PASSWORD1, t0.PASSWORD2, t0.PASSWORD3, t0.PASSWORD4, t0.PCNAME, t0.PWDATE, t2.ROLEID, t2.ACCTIND, t2.CDATE, t2.CUSER, t2.ROLEDESC, t2.UNITCAT, t0.STATCODE, t0.STATDESC, t0.USEFLG FROM TCMSPRUSR t0 INNER JOIN CFASFA0740 t1 ON t0.ORGACODE = t1.ORGACODE INNER JOIN TCMSPRROL t2 ON t0.ROLEID = t2.ROLEID optimize for 1 row} [code=-204, state=42704]SQLCA OUTPUT[Errp=SQLNQ1F7, Errd=-2145779603, 0, 0, 0, -10, 0]
DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=ASG2.TCMSPRUSR, DRIVER=4.13.127
DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-204;42704;ASG2.TCMSPRUSR, DRIVER=4.13.127
DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-204;42704;ASG2.TCMSPRUSR, DRIVER=4.13.127
FailedObject: SELECT u FROM User u [java.lang.String]
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4996)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4956)
at org.apache.openjpa.jdbc.sql.DB2Dictionary.newStoreException(DB2Dictionary.java:571)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:136)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:118)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:70)
at org.apache.openjpa.jdbc.kernel.SelectResultObjectProvider.handleCheckedException(SelectResultObjectProvider.java:155)
at org.apache.openjpa.lib.rop.EagerResultList.<init>(EagerResultList.java:40)
at org.apache.openjpa.kernel.QueryImpl.toResult(QueryImpl.java:1258)
at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:1014)
at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:870)
at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:801)
at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:542)
at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:286)
at org.apache.openjpa.persistence.QueryImpl.getResultList(QueryImpl.java:302)
at com.ibm.ws.persistence.QueryImpl.getResultList(QueryImpl.java:118)
at org.apache.openjpa.persistence.QueryImpl.getSingleResult(QueryImpl.java:330)
at ph.gov.bsp.tcms.core.UserFacade.findAll(UserFacade.java:29)
at ph.gov.bsp.tcms.core.EJSLocalNSLUserFacade_55a49658.findAll(EJSLocalNSLUserFacade_55a49658.java)
at ph.gov.bsp.tcms.test.Test.print(Test.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.apache.el.parser.AstValue.invoke(AstValue.java:268)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:83)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:51)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:404)
at javax.faces.component.UICommand.broadcast(UICommand.java:103)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:995)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:278)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1307)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:733)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:34)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:172)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:119)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1232)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:781)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:940)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1881)
Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=ASG2.TCMSPRUSR, DRIVER=4.13.127 {prepstmnt 1878102677 SELECT t0.USERID, t0.ATMPTCNT, t0.CDATE, t0.CUSER, t0.DAYSEXP, t0.EFFDTE, t0.EMPNAM, t0.EMPNO, t1.ORGACODE, t1.CDATE, t1.CUSER, t1.ORGAABBR, t1.ORGADESC, t1.STATUS, t0.PASSWORD, t0.PASSWORD1, t0.PASSWORD2, t0.PASSWORD3, t0.PASSWORD4, t0.PCNAME, t0.PWDATE, t2.ROLEID, t2.ACCTIND, t2.CDATE, t2.CUSER, t2.ROLEDESC, t2.UNITCAT, t0.STATCODE, t0.STATDESC, t0.USEFLG FROM TCMSPRUSR t0 INNER JOIN CFASFA0740 t1 ON t0.ORGACODE = t1.ORGACODE INNER JOIN TCMSPRROL t2 ON t0.ROLEID = t2.ROLEID optimize for 1 row} [code=-204, state=42704]
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:219)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:203)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.access$700(LoggingConnectionDecorator.java:59)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection$LoggingPreparedStatement.executeQuery(LoggingConnectionDecorator.java:1118)
at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:268)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$CancelPreparedStatement.executeQuery(JDBCStoreManager.java:1801)
at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:258)
at org.apache.openjpa.jdbc.sql.SelectImpl.executeQuery(SelectImpl.java:499)
at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:424)
at com.ibm.ws.persistence.jdbc.sql.SelectImpl.execute(SelectImpl.java:89)
at org.apache.openjpa.jdbc.sql.SelectImpl.execute(SelectImpl.java:391)
at org.apache.openjpa.jdbc.sql.LogicalUnion$UnionSelect.execute(LogicalUnion.java:427)
at org.apache.openjpa.jdbc.sql.LogicalUnion.execute(LogicalUnion.java:230)
at org.apache.openjpa.jdbc.sql.LogicalUnion.execute(LogicalUnion.java:220)
at org.apache.openjpa.jdbc.kernel.SelectResultObjectProvider.open(SelectResultObjectProvider.java:94)
at org.apache.openjpa.lib.rop.EagerResultList.<init>(EagerResultList.java:34)
... 52 more

Netbeans wizard Entity Classes from Database, not all tables mapped

I used this wizard to create entity classes from my database. Some tables have not been transformed into classes, but there are attributes that identify the relationships.
this is my db ERD (mysql)
and this is the user entity class (attributes)
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findByOid", query = "SELECT u FROM User u WHERE u.oid = :oid"),
#NamedQuery(name = "User.findByUsername", query = "SELECT u FROM User u WHERE u.username = :username"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
#NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email"),
#NamedQuery(name = "User.findByAddress", query = "SELECT u FROM User u WHERE u.address = :address"),
#NamedQuery(name = "User.findBySince", query = "SELECT u FROM User u WHERE u.since = :since")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "oid")
private Integer oid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 15)
#Column(name = "username")
private String username;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 15)
#Column(name = "password")
private String password;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "email")
private String email;
#Size(max = 50)
#Column(name = "address")
private String address;
#Basic(optional = false)
#NotNull
#Column(name = "since")
#Temporal(TemporalType.DATE)
private Date since;
#JoinTable(name = "favorite", joinColumns = {
#JoinColumn(name = "user_oid", referencedColumnName = "oid")}, inverseJoinColumns = {
#JoinColumn(name = "wheelchair_oid", referencedColumnName = "oid")})
#ManyToMany
private List<Wheelchair> wheelchairList;
#ManyToMany(mappedBy = "userList1")
private List<Wheelchair> wheelchairList1;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "senderOid")
private List<Comment> commentList;
#JoinColumn(name = "role_oid", referencedColumnName = "oid")
#ManyToOne(optional = false)
private Role roleOid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userOid")
private List<Orthopedy> orthopedyList;
public User() {
}
...
i can't understand something:
where is the OWN join table?
why i have userList1 and wheelchairList1? should it identifies OWN table? in this case i can rename it here or i have to rename it in some xml file?
why of
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userOid")
private List<Orthopedy> orthopedyList;
?
it should be OneToOne...
moreover the "JSF from entities class" wizard creates CRUD operation to manage Users, how can i manage join tables? I need to write something in the controller like what?
can you please link me some resource where i can learn this?
thank you so much
While Creating Entities It Creates Classes For All Tables With Primary Key
But not for tables that have many to many relations . its managed by their parent classes it is maintained as a list.
This is my code for managing my many to many table of SubjectFaculty which has details of Faculty and Subjects
Assigning A Subject To Faculty
public void assignFacultyToSubject(String facultyUname, Integer subjectId) {
try {
Subject oSubject = em.find(Subject.class, subjectId);
Faculty oFaculty = em.find(Faculty.class, facultyUname);
College oCollege = em.find(College.class, oFaculty.getCollegeUname().getCollegeUname());
List<Faculty> lstFaculty = oSubject.getFacultyList();
List<Subject> lstSubject = oFaculty.getSubjectList();
if (!lstSubject.contains(oSubject)) {
lstFaculty.add(oFaculty);
lstSubject.add(oSubject);
oSubject.setFacultyList(lstFaculty);
oFaculty.setSubjectList(lstSubject);
em.merge(oSubject);
em.getEntityManagerFactory().getCache().evictAll();
} else {
System.out.println("Entry Already Found");
}
} catch (Exception e) {
System.out.println("Error :- " + e.getMessage());
}
}
Removing Subject And Faculty Details Form Many to Many Table
#Override
public void removeFacultySubject(String facultyUname, Integer subjectId) {
try {
Subject oSubject = em.find(Subject.class, subjectId);
Faculty oFaculty = em.find(Faculty.class, facultyUname);
List<Subject> lstSubject = oFaculty.getSubjectList();
List<Faculty> lsFaculty = oSubject.getFacultyList();
lstSubject.remove(oSubject);
lsFaculty.remove(oFaculty);
em.merge(oSubject);
} catch (Exception e) {
System.out.println("Error :- " + e.getMessage());
}
}

How to get the Max of Total in JPA?

Hi I have to write JPQL command that does something specific the question is exactly:
"Find those students that has the greatest total of studypoint scores?"
There are just two Entity classes that looks like :
#Entity
#Table(name = "student")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s"),
#NamedQuery(name = "Student.findById", query = "SELECT s FROM Student s WHERE s.id = :id"),
#NamedQuery(name = "Student.findByFirstname", query = "SELECT s FROM Student s WHERE s.firstname = :firstname"),
#NamedQuery(name = "Student.findByLastname", query = "SELECT s FROM Student s WHERE s.lastname = :lastname")})
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "LASTNAME")
private String lastname;
#OneToMany(mappedBy = "studentId", cascade = CascadeType.PERSIST)
private List<Studypoint> studypointCollection;
public void addStudyPoint(Studypoint cc) {
if (studypointCollection == null) {
studypointCollection = new ArrayList<>();
}
studypointCollection.add(cc);
cc.setStudentId(this);
}
and the other class
#Entity
#Table(name = "studypoint")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Studypoint.findAll", query = "SELECT s FROM Studypoint s"),
#NamedQuery(name = "Studypoint.findById", query = "SELECT s FROM Studypoint s WHERE s.id = :id"),
#NamedQuery(name = "Studypoint.findByDescription", query = "SELECT s FROM Studypoint s WHERE s.description = :description"),
#NamedQuery(name = "Studypoint.findByMaxval", query = "SELECT s FROM Studypoint s WHERE s.maxval = :maxval"),
#NamedQuery(name = "Studypoint.findByScore", query = "SELECT s FROM Studypoint s WHERE s.score = :score")})
public class Studypoint implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "MAXVAL")
private Integer maxval;
#Column(name = "SCORE")
private Integer score;
#JoinColumn(name = "STUDENT_ID", referencedColumnName = "ID")
#ManyToOne
private Student studentId;
As you can see Student can have many Studypoints. Which I really struggle is this JPQl: Please help.
I tried for sometime to get this working with JQL and I can't see how you wrap the max in the sum, so I switched to SQL.
It's not ideal, but here is my repository:
package net.isban.fmis.repository;
import net.isban.fmis.entity.Studypoint;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudyPointRepository extends CrudRepository<Studypoint, Integer> {
#Query(value="select top 1 id from (select sum(score) scoresum, student.id from studypoint join student on student.id=studypoint.student_id group by student.id) order by scoresum desc", nativeQuery=true)
Integer findStudentIdWithMaxScore();
}