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();
}
Related
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);
}
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 am writing a JPA query using TopLink which involves the following three entities.
#Entity
#Table(name = "OFFERS")
public class Offers implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="offers_seq_gen")
#SequenceGenerator(name="offers_seq_gen", sequenceName="OFFERS_SEQ")
#Basic(optional = false)
#Column(name = "OFFERID")
private Long offerid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "offers", fetch = FetchType.LAZY)
private List<Coupons> couponsList;
}
#Entity
#Table(name = "COUPONS")
public class Coupons implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="coupons_seq_gen")
#SequenceGenerator(name="coupons_seq_gen", sequenceName="COUPONS_SEQ")
#Basic(optional = false)
#Column(name = "COUPONID")
private Long couponid;
#Basic(optional = false)
#Column(name = "ISSUED", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
#Temporal(TemporalType.TIMESTAMP)
private Date issued;
#JoinColumn(name = "USERID", referencedColumnName = "USERID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Users users;
#JoinColumn(name = "OFFERID", referencedColumnName = "OFFERID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Offers offers;
#Entity
#Table(name = "USERS")
public class Users implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="users_seq_gen")
#SequenceGenerator(name="users_seq_gen", sequenceName="USERS_SEQ")
#Basic(optional = false)
#Column(name = "USERID")
private Long userid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "users", fetch = FetchType.LAZY)
private List<Coupons> couponsList;
I need to find all the Offers who either have no coupons for a given user or all the coupons for the user were issued more than a day ago.
I have tried many different approaches and the only query I have come up with so far, which does not crash the server on deployment is:
SELECT o
FROM Offers o
LEFT JOIN o.couponsList c
WHERE
c.users.userid = :userid AND c.issued < :yesterday
OR
NOT EXISTS
(SELECT c1
FROM Coupons c1
WHERE c1.offers = o AND c1.users.userid = :userid)
But it does not return the Offer when the Coupons entry does not exist.
I managed to find a working query. Leaving it here for reference if anyone had similar issues:
SELECT o FROM Offers o WHERE
NOT EXISTS
(SELECT c FROM Coupons c WHERE c.users.userid = :userid
AND c.issued > :yesterday AND c.offers = o)
OR NOT EXISTS
(SELECT c1 FROM Coupons c1 WHERE c1.offers = o
AND c1.users.userid = :userid)
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());
}
}
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.