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
Related
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?
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());
}
}
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();
}
I have web application developed in JSF2 in which i have to persist two entity class with a One to Many bidirectional relationship. when I try to persist a record of a table (Documenti_tg) I have this error :
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461):
org.eclipse.persistence.exceptions.DatabaseException Internal Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Result consisted of more
than one row Error Code: 1172 Call:
INSERT INTO DOCUMENTI_TG (ANNO, CODDOC, DTAGLIAR, NRIGO, PROGRESSIVO, QUANTITA, TABCOLORI, TAGLIA, IDDOCR) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) bind => [9 parameters bound] Query: InsertObjectQuery(entity.DocumentiTg[ id=null ])
at
org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:786)
atcom.sun.enterprise.container.common.impl.EntityManagerWrapper.flush(EntityManagerWrapper.java:418) at controller.kontabT.sincronizaDoc(kontabT.java:419)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java :1052) at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124) at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388) at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619) at
com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800) at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571) at
com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162) at
com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at
java.lang.reflect.Method.invoke(Method.java:601) at
com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861) at
com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800) at
com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370) at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360) at
com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214) ... 47 more
For every DocumentiR entity I have many DocumentiTG entity, and these are the classes :
Documenti_R
#Entity
#Table(name = "DOCUMENTI_R")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "DocumentiR.findAll", query = "SELECT d FROM DocumentiR d"),
#NamedQuery(name = "DocumentiR.findById", query = "SELECT d FROM DocumentiR d WHERE d.id = :id"),
#NamedQuery(name = "DocumentiR.findByCodart", query = "SELECT d FROM DocumentiR d WHERE d.codart = :codart"),
#NamedQuery(name = "DocumentiR.findBySeriale", query = "SELECT d FROM DocumentiR d WHERE d.seriale = :seriale"),
#NamedQuery(name = "DocumentiR.findByDescart", query = "SELECT d FROM DocumentiR d WHERE d.descart = :descart"),
#NamedQuery(name = "DocumentiR.findByUm", query = "SELECT d FROM DocumentiR d WHERE d.um = :um"),
#NamedQuery(name = "DocumentiR.findByQuantita", query = "SELECT d FROM DocumentiR d WHERE d.quantita = :quantita"),
#NamedQuery(name = "DocumentiR.findByPrezzounit", query = "SELECT d FROM DocumentiR d WHERE d.prezzounit = :prezzounit"),
#NamedQuery(name = "DocumentiR.findByCodcolore", query = "SELECT d FROM DocumentiR d WHERE d.codcolore = :codcolore"),
#NamedQuery(name = "DocumentiR.findByImpnet", query = "SELECT d FROM DocumentiR d WHERE d.impnet = :impnet"),
#NamedQuery(name = "DocumentiR.findByIva", query = "SELECT d FROM DocumentiR d WHERE d.iva = :iva"),
#NamedQuery(name = "DocumentiR.findBySconto", query = "SELECT d FROM DocumentiR d WHERE d.sconto = :sconto"),
#NamedQuery(name = "DocumentiR.findByProgressivo", query = "SELECT d FROM DocumentiR d WHERE d.progressivo = :progressivo"),
#NamedQuery(name = "DocumentiR.findByNrigo", query = "SELECT d FROM DocumentiR d WHERE d.nrigo = :nrigo"),
#NamedQuery(name = "DocumentiR.findByAnno", query = "SELECT d FROM DocumentiR d WHERE d.anno = :anno"),
#NamedQuery(name = "DocumentiR.findByCoddoc", query = "SELECT d FROM DocumentiR d WHERE d.coddoc = :coddoc"),
#NamedQuery(name = "DocumentiR.findByTabcolori", query = "SELECT d FROM DocumentiR d WHERE d.tabcolori = :tabcolori"),
#NamedQuery(name = "DocumentiR.findByCompo", query = "SELECT d FROM DocumentiR d WHERE d.compo = :compo"),
#NamedQuery(name = "DocumentiR.findBySconti", query = "SELECT d FROM DocumentiR d WHERE d.sconti = :sconti")})
public class DocumentiR implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Size(max = 255)
#Column(name = "CODART")
private String codart;
#Column(name = "SERIALE")
private Integer seriale;
#Size(max = 255)
#Column(name = "DESCART")
private String descart;
#Size(max = 255)
#Column(name = "UM")
private String um;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "QUANTITA")
private Float quantita;
#Column(name = "PREZZOUNIT")
private Float prezzounit;
#Size(max = 25)
#Column(name = "CODCOLORE")
private String codcolore;
#Column(name = "IMPNET")
private Float impnet;
#Column(name = "IVA")
private Float iva;
#Column(name = "SCONTO")
private Float sconto;
#Column(name = "PROGRESSIVO")
private Integer progressivo;
#Column(name = "NRIGO")
private Integer nrigo;
#Column(name = "ANNO")
private Integer anno;
#Size(max = 255)
#Column(name = "CODDOC")
private String coddoc;
#Size(max = 10)
#Column(name = "TABCOLORI")
private String tabcolori;
#Size(max = 10)
#Column(name = "COMPO")
private String compo;
#Size(max = 20)
#Column(name = "SCONTI")
private String sconti;
#JoinColumn(name = "IDDOCT", referencedColumnName = "ID")
#ManyToOne
private DocumentiT iddoct;
#OneToMany(mappedBy = "iddocr")
private Collection<DocumentiTg> documentiTgCollection;
//CONSTRUCTOR, GETTER AND SETTER....
And documenti_Tg class :
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "DOCUMENTI_TG")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "DocumentiTg.findAll", query = "SELECT d FROM DocumentiTg d"),
#NamedQuery(name = "DocumentiTg.findById", query = "SELECT d FROM DocumentiTg d WHERE d.id = :id"),
#NamedQuery(name = "DocumentiTg.findByProgressivo", query = "SELECT d FROM DocumentiTg d WHERE d.progressivo = :progressivo"),
#NamedQuery(name = "DocumentiTg.findByNrigo", query = "SELECT d FROM DocumentiTg d WHERE d.nrigo = :nrigo"),
#NamedQuery(name = "DocumentiTg.findByTaglia", query = "SELECT d FROM DocumentiTg d WHERE d.taglia = :taglia"),
#NamedQuery(name = "DocumentiTg.findByQuantita", query = "SELECT d FROM DocumentiTg d WHERE d.quantita = :quantita"),
#NamedQuery(name = "DocumentiTg.findByAnno", query = "SELECT d FROM DocumentiTg d WHERE d.anno = :anno"),
#NamedQuery(name = "DocumentiTg.findByCoddoc", query = "SELECT d FROM DocumentiTg d WHERE d.coddoc = :coddoc"),
#NamedQuery(name = "DocumentiTg.findByDtagliar", query = "SELECT d FROM DocumentiTg d WHERE d.dtagliar = :dtagliar"),
#NamedQuery(name = "DocumentiTg.findByTabcolori", query = "SELECT d FROM DocumentiTg d WHERE d.tabcolori = :tabcolori")})
public class DocumentiTg implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Column(name = "PROGRESSIVO")
private Integer progressivo;
#Column(name = "NRIGO")
private Integer nrigo;
#Column(name = "TAGLIA")
private Integer taglia;
#Size(max = 100)
#Column(name = "QUANTITA")
private String quantita;
#Column(name = "ANNO")
private Integer anno;
#Size(max = 255)
#Column(name = "CODDOC")
private String coddoc;
#Size(max = 6)
#Column(name = "DTAGLIAR")
private String dtagliar;
#Size(max = 10)
#Column(name = "TABCOLORI")
private String tabcolori;
#JoinColumn(name = "IDDOCR", referencedColumnName = "ID")
#ManyToOne
private DocumentiR iddocr;
// CONSTRUCTOR, GETTER AND SETTER....
The program code where I encounter the error above is the following :
DocumentiR driga=new DocumentiT();
//HERE I SET SEVERAL ENTITY PROPERTIES AND SAVE THIS RECORD ON MY DB
driga.setCodart("a string");
driga.setCompo("a string");
driga.setTabcolori("a string");
driga.setCoddoc("a string");
driga.setSeriale(an integer);
driga.setProgressivo(an integer);
driga.setNrigo(an integer);
driga.setDescart("a string");
driga.setImpnet(a float);
driga.setPrezzounit(a float);
driga.setSconto(rs2.getFloat(29));
driga.setAnno(an integer);
driga.setCodcolore("a string");
driga.setQuantita(a float);
driga.setUm("a string");
driga.setIva(a float);
entityManager.persist(driga);
//FOR every driga i have many DocumentiTg entity
for(int i=0; i<N;i++){ //Where N depends on the specific entity driga above
DocumentiTg dtaglia= new DocumentiTg();
//HERE I SET SEVERAL dtaglia PROPERTIES
dtaglia.setAnno(an integer);
dtaglia.setCoddoc("a string");
dtaglia.setProgressivo(an integer);
dtaglia.setNrigo(an integer);
dtaglia.setTaglia(an integer);
dtaglia.setQuantita(an integer);
entityManager.persist(dtaglia);
entityManager.flush()
}
My persistence file is :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="FattGimerPU" transaction-type="JTA">
<jta-data-source>jdbc/fattGimer</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
</properties>
</persistence-unit>
</persistence>
I solve the problem by myself. There was a TRIGGER statement on my DB ( I'didn't konow it's existence ), that perform the same operations over theese entity. So when i try to persist an entity, this Trigger statement recall the same code operation, and so I have the error above ( result consisted in more than one row). Simply delete this TRIGGER STATEMENT on my MySql Database and all works fine.
I have three tables in MySQL database.
zone_table
zone_id (PK)
zone_name
transporter_id (FK references the transporter table - unrelated here).
weight
weight_id (PK)
weight
zone_charge
zone_id (FK refernces zone_table) |
weight_id (FK references weight) | composite primary key.
charge | extra column in join.
Since a many-to-many relationship between zone_table and weight is expressed by the zone_charge table with an extra column in it (which is charge), an embeddable class ZoneChargePK representing the composite primary key has been created.
With this relationship, I need to retrieve a list of rows consisting of three fields, weight_id and weight from the weight table and charge from the zone_charge table for a given zone.
The native SQL would be as follows.
SELECT w.weight_id, w.weight, zc.charge
FROM weight w
LEFT OUTER JOIN zone_charge zc ON w.weight_id=zc.weight_id
WHERE zc.zone_id=?
ORDER BY w.weight ASC
The corresponding JPQL would be as under.
SELECT w.weightId, w.weight, zc.charge
FROM Weight w
LEFT JOIN w.zoneChargeSet zc
WITH zc.zone.zoneId=:id
ORDER BY w.weight
I would like the same thing to be expressed by JPA criteria query, since this query would, in turn be generated dynamically. I have left with the following incomplete criteria query.
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple>criteriaQuery=criteriaBuilder.createTupleQuery();
Root<Weight> root = criteriaQuery.from(entityManager.getMetamodel().entity(Weight.class));
SetJoin<Weight, ZoneCharge> join = root.join(Weight_.zoneChargeSet, JoinType.LEFT);
criteriaQuery.multiselect(root.get(Weight_.weightId), root.get(Weight_.weight), join.get(ZoneCharge_.zoneTable));
TypedQuery<Tuple> typedQuery = entityManager.createQuery(criteriaQuery);
List<Tuple> tuples = typedQuery.getResultList();
But this results in an inner join between zone_table and zone_charge in addition to a left join between zone_charge and weight. The generated SQL query looks like the following.
select
weight0_.weight_id as col_0_0_,
weight0_.weight as col_1_0_,
zonecharge1_.zone_id as col_2_0_,
zonetable2_.zone_id as zone1_34_,
zonetable2_.transporter_id as transpor3_34_,
zonetable2_.zone_name as zone2_34_
from
social_networking.weight weight0_
left outer join
social_networking.zone_charge zonecharge1_
on weight0_.weight_id=zonecharge1_.weight_id
inner join
social_networking.zone_table zonetable2_
on zonecharge1_.zone_id=zonetable2_.zone_id
It should actually be,
select
weight0_.weight_id as col_0_0_,
weight0_.weight as col_1_0_,
zonecharge1_.charge as col_2_0_
from
social_networking.weight weight0_
left outer join
social_networking.zone_charge zonecharge1_
on weight0_.weight_id=zonecharge1_.weight_id
Except for where and order by. So how would the actual criteria query look like?
EDIT :
The ZoneTable entity (only if needed):
#Entity
#Table(name = "zone_table", catalog = "social_networking", schema = "", uniqueConstraints = {
#UniqueConstraint(columnNames = {"zone_id"})})
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ZoneTable.findAll", query = "SELECT z FROM ZoneTable z"),
#NamedQuery(name = "ZoneTable.findByZoneId", query = "SELECT z FROM ZoneTable z WHERE z.zoneId = :zoneId"),
#NamedQuery(name = "ZoneTable.findByZoneName", query = "SELECT z FROM ZoneTable z WHERE z.zoneName = :zoneName")})
public class ZoneTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "zone_id", nullable = false)
private Long zoneId;
#Column(name = "zone_name", length = 45)
private String zoneName;
#JoinColumn(name = "transporter_id", referencedColumnName = "transporter_id")
#ManyToOne(fetch = FetchType.LAZY)
private Transporter transporterId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "zoneTable", fetch = FetchType.LAZY)
private Set<ZoneCharge> zoneChargeSet; //<--------------------------
#OneToMany(mappedBy = "zoneId", fetch = FetchType.LAZY)
private Set<Country> countrySet;
}
The Weight entity:
#Entity
#Table(name = "weight", catalog = "social_networking", schema = "", uniqueConstraints = {
#UniqueConstraint(columnNames = {"weight_id"})})
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Weight.findAll", query = "SELECT w FROM Weight w"),
#NamedQuery(name = "Weight.findByWeightId", query = "SELECT w FROM Weight w WHERE w.weightId = :weightId"),
#NamedQuery(name = "Weight.findByWeight", query = "SELECT w FROM Weight w WHERE w.weight = :weight")})
public class Weight implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "weight_id", nullable = false)
private Long weightId;
#Column(name = "weight", precision = 35, scale = 2)
private BigDecimal weight;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "weight", fetch = FetchType.LAZY)
private Set<ZoneCharge> zoneChargeSet; //<-------------------------
}
The ZoneCharge entity:
#Entity
#Table(name = "zone_charge", catalog = "social_networking", schema = "")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ZoneCharge.findAll", query = "SELECT z FROM ZoneCharge z"),
#NamedQuery(name = "ZoneCharge.findByZoneId", query = "SELECT z FROM ZoneCharge z WHERE z.zoneChargePK.zoneId = :zoneId"),
#NamedQuery(name = "ZoneCharge.findByWeightId", query = "SELECT z FROM ZoneCharge z WHERE z.zoneChargePK.weightId = :weightId"),
#NamedQuery(name = "ZoneCharge.findByCharge", query = "SELECT z FROM ZoneCharge z WHERE z.charge = :charge")})
public class ZoneCharge implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected ZoneChargePK zoneChargePK;
#Column(name = "charge", precision = 35, scale = 2)
private BigDecimal charge;
#JoinColumn(name = "zone_id", referencedColumnName = "zone_id", nullable = false, insertable = false, updatable = false)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private ZoneTable zoneTable;
#JoinColumn(name = "weight_id", referencedColumnName = "weight_id", nullable = false, insertable = false, updatable = false)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Weight weight;
The ZoneChargePK entity:
#Embeddable
public class ZoneChargePK implements Serializable {
#Basic(optional = false)
#Column(name = "zone_id", nullable = false)
private long zoneId;
#Basic(optional = false)
#Column(name = "weight_id", nullable = false)
private long weightId;
}
According to this relationship, the JPQL query as shown above works correctly.
It is not a social networking project. It was just originally intended. Therefore it was named such. It is about a shopping site.