I wanted to use anotations in order to keep the code clean but all I get are headaches.
I know the problem has to do with a column's name with an underscore as: rental_rate. If I used #NamedQuery, it is going to throw an error.
Here are the anotations
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
,#NamedQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
})
The anotation that I am struggling with is:
#NamedQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
it throws this error which I believe it has to do with the underscore in the column's name.
Caused by: org.hibernate.HibernateException: Errors in named queries: Film.prices
After some research I found about #NamedNativeQuery in this question and so I decided to change the anotation to:
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
//,#NamedQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
})
#NamedNativeQueries({
#NamedNativeQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
})
but then it would be outside the Entity
Caused by: org.hibernate.MappingException: Unknown entity: java.lang.String
How can I manage this issue?
NOTES
Java 8
Netbeans 11
JPA (Hibernate 4.3.1)
EDIT
Full class file
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
,#NamedQuery(name = "Film.prices", query = "SELECT f.rentalRate FROM Film f")
})
/*#NamedNativeQueries({
#NamedNativeQuery(name = "Film.prices", query = "SELECT f.rentalRate FROM Film f")
})*/
public class Film implements Serializable{
#Id
private int filmId;
private String title;
private String Description;
private String releaseYear;
#NaturalId
private int languageId;
#NaturalId
#Column(nullable=true)
private Integer originalLanguageId;
private int rentalDuration;
private float rentalRate;
private int length;
private float replacementCost;
private String rating;
private String specialFeatures;
private Timestamp lastUpdate;
#ManyToMany(cascade = CascadeType.ALL , fetch = FetchType.EAGER)
#JoinTable(
name = "film_category",
joinColumns = { #JoinColumn(name = "film_id") },
inverseJoinColumns = { #JoinColumn(name = "category_id") }
)
private Set<Category> categories = new HashSet<Category>();
#ManyToMany(cascade = CascadeType.ALL , fetch = FetchType.EAGER)
#JoinTable(
name = "inventory",
joinColumns = { #JoinColumn(name = "film_id") },
inverseJoinColumns = { #JoinColumn(name = "inventory_id") }
)
private List<Store> stores = new ArrayList<Store>();
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public String getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(String releaseYear) {
this.releaseYear = releaseYear;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(int languageId) {
this.languageId = languageId;
}
public int getOriginalLanguageId() {
return originalLanguageId;
}
public void setOriginalLanguageId(int originalLanguageId) {
this.originalLanguageId = originalLanguageId;
}
public int getRentalDuration() {
return rentalDuration;
}
public void setRentalDuration(int rentalDuration) {
this.rentalDuration = rentalDuration;
}
public float getRentalRate() {
return rentalRate;
}
public void setRentalRate(float rentalRate) {
this.rentalRate = rentalRate;
}
public int getLenght() {
return length;
}
public void setLenght(int lenght) {
this.length = lenght;
}
public float getReplacementCost() {
return replacementCost;
}
public void setReplacementCost(float replacementCost) {
this.replacementCost = replacementCost;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getSpecialFeatures() {
return specialFeatures;
}
public void setSpecialFeatures(String specialFeatures) {
this.specialFeatures = specialFeatures;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
public Set<Category> getCategories() {
return this.categories;
}
public List<Store> getStores() {
return stores;
}
public void setStores(List<Store> stores) {
this.stores = stores;
}
#Override
public String toString() {
return "Film{" + "filmId=" + filmId + ", title=" + title + ", Description=" + Description + ", releaseYear=" + releaseYear + ", languageId=" + languageId + ", originalLanguageId=" + originalLanguageId + ", rentalDuration=" + rentalDuration + ", rentalRate=" + rentalRate + ", length=" + length + ", replacementCost=" + replacementCost + ", rating=" + rating + ", specialFeatures=" + specialFeatures + ", lastUpdate=" + lastUpdate + ", categories=" + categories + '}';
}
}
You should test if the attribute in File class is something like rentalRate not rental_rate
So in JPA, we use the attributes' names from the class not the columns' names in Database
Update your entity class and use #Column annotation with the name in the database and you can use any name related to java convention and use it in JPA
Check if your id is auto increment use #GeneratedValue annotation if not like PostgreSQL use this one where name_seq is the sequence name
#SequenceGenerator(name="name_seq",
sequenceName="name_seq",
allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator="name_seq")
, Entity
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int filmId;
#Column(name="title")
private String title;
#Column(name="description")
private String Description;
#Column(name="release_year")
private String releaseYear;
#NaturalId
private int languageId;
#NaturalId
#Column(name="original_languageId", nullable=true)
private Integer originalLanguageId;
#Column(name="rental_duration")
private int rentalDuration;
#Column(name="rental_rate")
private float rentalRate;
#Column(name="length")
private int length;
#Column(name="replacement_cost")
private float replacementCost;
#Column
private String rating;
#Column(name="special_features")
private String specialFeatures;
#Column(name="last_update")
private Timestamp lastUpdate;
Update the query to match the attribute names in the Film class, like this:
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
,#NamedQuery(name = "Film.prices", query = "SELECT f.rentalRate FROM Film f")
})
Related
I am using a native query in JPA repository inside #Query annotation
#Query(value = " select * from message where id in(select if(coalesce(a.maxId,0)>coalesce(b.maxId,0), a.maxId, b.maxId) maxId from (select from_number, to_number, " +
" max(id) maxId,direction,type from message where direction='INCOMING' group by from_number, to_number having sum(type= :type)) as a " +
" left join ( select from_number, to_number, max(id) maxId, direction, type from message where direction = 'OUTGOING' and schedule_id is null " +
" group by from_number, to_number) as b on a.from_number=b.to_number and a.to_number=b.from_number) order by generated_time desc ", nativeQuery = true)
Page<Message> getLatestMessageFromThread(#Param("type") String type, Pageable page);
The problem is when i execute this query i am getting syntax error. When i checked the logs it is showing that the query to take count of total messages in query is like below
select count(where) from message where id in(select if(coalesce(a.maxId,0)>coalesce(b.maxId,0),
a.maxId, b.maxId) maxId from (select from_number, to_number, max(id) maxId,direction,type from
message where direction='INCOMING' group by from_number, to_number having sum(type= 'REVIEW'))
as a left join ( select from_number, to_number, max(id) maxId, direction, type from message
where direction = 'OUTGOING' and schedule_id is null group by from_number, to_number) as b
on a.from_number=b.to_number and a.to_number=b.from_number)
The count(*) is replaced by count(where)
The entity class for message table is here.
#Entity
#Table(name = "message")
public class Message implements Comparable<Message> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "to_number")
private String toNumber;
#Column(name = "from_number")
private String fromNumber;
#Column(name = "message")
private String message;
#Enumerated(EnumType.STRING)
#Column(name = "direction")
private MessageDirection direction;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private MessageStatus status;
#Enumerated(EnumType.STRING)
#Column(name = "type")
private KeywordType type;
#Column(name = "keyword_matched")
private String keywordMatched;
#Column(name = "generated_time")
private Timestamp generatedTime;
#Column(name = "scheduled_time")
private Timestamp scheduledTime;
#Column(name = "details")
private String details;
#Enumerated(EnumType.STRING)
#Column(name = "read_status")
private MessageReadStatus readStatus;
#Column(name = "delivery_code")
private String deliveryCode;
#Column(name = "delivery_description")
private String deliveryDescription;
#Column(name = "data", columnDefinition = "json")
private String messageData;
#ManyToOne
#JoinColumn(name = "schedule_id")
private Schedule schedule;
public Message() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getToNumber() {
return toNumber;
}
public void setToNumber(String toNumber) {
this.toNumber = toNumber;
}
public String getFromNumber() {
return fromNumber;
}
public void setFromNumber(String fromNumber) {
this.fromNumber = fromNumber;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MessageDirection getDirection() {
return direction;
}
public void setDirection(MessageDirection direction) {
this.direction = direction;
}
public MessageStatus getStatus() {
return status;
}
public void setStatus(MessageStatus status) {
this.status = status;
}
public KeywordType getType() {
return type;
}
public void setType(KeywordType type) {
this.type = type;
}
public Timestamp getGeneratedTime() {
return generatedTime;
}
public void setGeneratedTime(Timestamp generatedTime) {
this.generatedTime = generatedTime;
}
public Timestamp getScheduledTime() {
return scheduledTime;
}
public void setScheduledTime(Timestamp scheduledTime) {
this.scheduledTime = scheduledTime;
}
public Schedule getSchedule() {
return schedule;
}
public void setSchedule(Schedule schedule) {
this.schedule = schedule;
}
public String getKeywordMatched() {
return keywordMatched;
}
public void setKeywordMatched(String keywordMatched) {
this.keywordMatched = keywordMatched;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public MessageReadStatus getReadStatus() {
return readStatus;
}
public void setReadStatus(MessageReadStatus readStatus) {
this.readStatus = readStatus;
}
public String getDeliveryCode() {
return deliveryCode;
}
public void setDeliveryCode(String deliveryCode) {
this.deliveryCode = deliveryCode;
}
public String getMessageData() {
return messageData;
}
public void setMessageData(String messageData) {
this.messageData = messageData;
}
public String getDeliveryDescription() {
return deliveryDescription;
}
public void setDeliveryDescription(String deliveryDescription) {
this.deliveryDescription = deliveryDescription;
}
}
Why it is getting replaced. How can i write the query in correct way ?
The solution is to use countQuery annotation parameter :
public interface Repository extends JpaRepository<Entity, Long> {
String QUERY = "FROM entity " +
" WHERE name ILIKE :name ";
#Query(
value = "SELECT * " + QUERY,
countQuery = "SELECT count(*) " + QUERY,
nativeQuery = true
)
Page<KDeploymentView> findBy(
#Param("name") String name,
Pageable p
);
I am new to hql and trying to delete the complete row in case of a match based on email.
Following is what I have tried.
Still I get a Persistence Exception.
public void unsubscribeEmailList(EmailListDto dataList) {
EmailList e =new EmailList(dataList);
Query q =sessionFactory.getCurrentSession().createQuery("delete from EmailList where email=:e");
q.setParameter("e", dataList);
int i=q.executeUpdate();
System.out.println(i);
}
Class EmailList is
#Entity
#Table(name = "email_list")
public class EmailList implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String email;
public EmailList(EmailListDto dto)
{
this.email=dto.getEmail();
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "email", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Try use this:
q.setParameter("e", e.getEmail());
public void unsubscribeEmailList(EmailListDto dataList) {
EmailList e =new EmailList(dataList);
Query q =sessionFactory.getCurrentSession().createQuery("delete from EmailList where email = :e");
q.setParameter("e", e.egetEmail() );
int i=q.executeUpdate();
System.out.println(i);
}
...
#NamedQueries(
{
#NamedQuery(name = "FindAllJobsEngineersParticipateInInterval",
query = "SELECT je.id FROM Stage1JobEngineer AS je " +
"JOIN je.job AS s1j " +
"WHERE "
+ " :absenceStartDateTime <= :absenceEndDateTime "
+ " AND :absenceStartDateTime <= s1j.endTime AND :absenceEndDateTime >= s1j.startTime " +
" AND je.engineer.id IN (:engineerIds) ")
})
#Entity
#Table(name = "ho_stage1_job_has_engineers")
public class Stage1JobEngineer extends CreatedByUserEntity implements Serializable {
...
...
// dao service call :
Query query = getSession().getNamedQuery( "FindAllJobsEngineersParticipateInInterval" );
query.setParameter( "absenceStartDateTime", startDate )
.setParameter( "absenceEndDateTime", endDate )
.setParameterList( "engineerIds", Arrays.asList(1L, 2L, 33L) );
List<Long> queryResult = query.list();
List<Long> result = queryRes != null ? queryResult : new ArrayList<>();
...
I have an ObtainedSkill table as well as a Resource table. There is no column in the Resource table for ObtainedSkill. There are only get/set methods. The ObtainedSkill table has a forien key to a Resource Serial Number.
When I call setObtainedSkill() and then update the Resource with the new ObtainedSkills list, it doesn't update. The Resource's ObtainedSkills are still null.
My question is, how do I go about adding ObtainedSkills to my Resource? Do I have to have another column in the Resource table for ObtainedSkills?
Here's my test class:
public static void main(String[] args) throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("XRM_JPA");
ResourcezManager rm = new ResourcezManager(emf);
Resourcez resource = rm.getNewResourcez();
resource = rm.findResourcezBySerialNumber("2G9933");
for (int i = 0; i < resource.getObtainedSkills().size(); i++) {
if (resource.getObtainedSkills().get(i) != null) {
System.out.println(resource.getObtainedSkills().get(i).toString());
}
}
emf.close();
}
I get a NullPointerException when it tries to execute the System.out.
Here are the relevant entities
Skill Entity
package xrm.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the SKILL database table.
*
*/
#Entity
#NamedQueries({#NamedQuery(name = "getSkillBySkillName", query = "SELECT s FROM Skill s WHERE s.skillName = :skillName"),#NamedQuery(name = "getSkillBySkillDescription", query = "SELECT s FROM Skill s WHERE s.skillDescription = :skillDescription"),
#NamedQuery(name = "getSkillBySkillId", query = "SELECT s FROM Skill s WHERE s.skillId = :skillId"),
#NamedQuery(name = "getSkill", query = "SELECT s FROM Skill s")})
public class Skill implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SKILL_ID")
private int skillId;
#Column(name="SKILL_DESCRIPTION")
private String skillDescription;
#Column(name="SKILL_NAME")
private String skillName;
//bi-directional many-to-one association to ObtainedSkill
#OneToMany(mappedBy="skill")
private List<ObtainedSkill> obtainedSkills;
public Skill() {
}
public int getSkillId() {
return this.skillId;
}
public void setSkillId(int skillId) {
this.skillId = skillId;
}
public String getSkillDescription() {
return this.skillDescription;
}
public void setSkillDescription(String skillDescription) {
this.skillDescription = skillDescription;
}
public String getSkillName() {
return this.skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public List<ObtainedSkill> getObtainedSkills() {
return this.obtainedSkills;
}
public void setObtainedSkills(List<ObtainedSkill> obtainedSkills) {
this.obtainedSkills = obtainedSkills;
}
}
Obtained Skill entity
package xrm.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the OBTAINED_SKILL database table.
*
*/
#Entity
#Table(name="OBTAINED_SKILL")
#NamedQueries({#NamedQuery(name = "getObtainedSkillBySkill", query = "SELECT o FROM ObtainedSkill o WHERE o.skill.skillId = :skill_skillId"),
#NamedQuery(name = "getObtainedSkillByResourcez", query = "SELECT o FROM ObtainedSkill o WHERE o.resourcez.serialNumber = :resourcez_serialNumber"),
#NamedQuery(name = "getObtainedSkillBySkillLevel", query = "SELECT o FROM ObtainedSkill o WHERE o.skillLevel = :skillLevel"),
#NamedQuery(name = "getObtainedSkillByObtainedSkillId", query = "SELECT o FROM ObtainedSkill o WHERE o.obtainedSkillId = :obtainedSkillId"),
#NamedQuery(name = "getObtainedSkill", query = "SELECT o FROM ObtainedSkill o")})
public class ObtainedSkill implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="OBTAINED_SKILL_ID")
private int obtainedSkillId;
#Column(name="SKILL_LEVEL")
private int skillLevel;
//bi-directional many-to-one association to Resourcez
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="SERIAL_NUMBER")
private Resourcez resourcez;
//bi-directional many-to-one association to Skill
#ManyToOne (cascade=CascadeType.DETACH)
#JoinColumn(name="SKILL_ID")
private Skill skill;
public ObtainedSkill() {
}
public int getObtainedSkillId() {
return this.obtainedSkillId;
}
public void setObtainedSkillId(int obtainedSkillId) {
this.obtainedSkillId = obtainedSkillId;
}
public int getSkillLevel() {
return this.skillLevel;
}
public void setSkillLevel(int skillLevel) {
this.skillLevel = skillLevel;
}
public Resourcez getResourcez() {
return this.resourcez;
}
public void setResourcez(Resourcez resourcez) {
this.resourcez = resourcez;
}
public Skill getSkill() {
return this.skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
}
Resource Entity
package xrm.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the RESOURCEZ database table.
*
*/
#Entity
#NamedQueries({#NamedQuery(name = "getResourcezByUserInformation", query = "SELECT r FROM Resourcez r WHERE r.userInformation.ibmEmailAddress = :userInformation_ibmEmailAddress"),#NamedQuery(name = "getResourcezBySource", query = "SELECT r FROM Resourcez r WHERE r.source.sourceId = :source_sourceId"),
#NamedQuery(name = "getResourcezByRole", query = "SELECT r FROM Resourcez r WHERE r.role.roleId = :role_roleId"),
#NamedQuery(name = "getResourcezByLocation", query = "SELECT r FROM Resourcez r WHERE r.location.locationId = :location_locationId"),
#NamedQuery(name = "getResourcezByMiddleInitial", query = "SELECT r FROM Resourcez r WHERE r.middleInitial = :middleInitial"),
#NamedQuery(name = "getResourcezByLastName", query = "SELECT r FROM Resourcez r WHERE r.lastName = :lastName"),
#NamedQuery(name = "getResourcezByHireDate", query = "SELECT r FROM Resourcez r WHERE r.hireDate = :hireDate"),
#NamedQuery(name = "getResourcezByFirstName", query = "SELECT r FROM Resourcez r WHERE r.firstName = :firstName"),
#NamedQuery(name = "getResourcezByBirthday", query = "SELECT r FROM Resourcez r WHERE r.birthday = :birthday"),
#NamedQuery(name = "getResourcezBySerialNumber", query = "SELECT r FROM Resourcez r WHERE r.serialNumber = :serialNumber"),
#NamedQuery(name = "getResourcez", query = "SELECT r FROM Resourcez r")})
public class Resourcez implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="SERIAL_NUMBER")
private String serialNumber;
#Temporal( TemporalType.DATE)
private Date birthday;
#Column(name="FIRST_NAME")
private String firstName;
#Temporal( TemporalType.DATE)
#Column(name="HIRE_DATE")
private Date hireDate;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="MIDDLE_INITIAL")
private String middleInitial;
//bi-directional many-to-one association to Assignment
#OneToMany(mappedBy="resourcez", cascade=CascadeType.DETACH)
private List<Assignment> assignments;
//bi-directional many-to-one association to ObtainedCertification
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<ObtainedCertification> obtainedCertifications;
//bi-directional many-to-one association to ObtainedSkill
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<ObtainedSkill> obtainedSkills;
//bi-directional many-to-one association to PhoneNumber
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<PhoneNumber> phoneNumbers;
//bi-directional many-to-one association to PrivilegeRequest
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<PrivilegeRequest> privilegeRequests;
//bi-directional many-to-one association to Location
#ManyToOne
#JoinColumn(name="LOCATION_ID")
private Location location;
//bi-directional many-to-one association to Role
#ManyToOne
#JoinColumn(name="ROLE_ID")
private Role role;
//bi-directional many-to-one association to Source
#ManyToOne
#JoinColumn(name="SOURCE_ID")
private Source source;
//bi-directional many-to-one association to UserInformation
#ManyToOne
#JoinColumn(name="IBM_EMAIL_ADDRESS")
private UserInformation userInformation;
public Resourcez() {
}
public String getSerialNumber() {
return this.serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public Date getBirthday() {
return this.birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getHireDate() {
return this.hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleInitial() {
return this.middleInitial;
}
public void setMiddleInitial(String middleInitial) {
this.middleInitial = middleInitial;
}
public List<Assignment> getAssignments() {
return this.assignments;
}
public void setAssignments(List<Assignment> assignments) {
this.assignments = assignments;
}
public List<ObtainedCertification> getObtainedCertifications() {
return this.obtainedCertifications;
}
public void setObtainedCertifications(List<ObtainedCertification> obtainedCertifications) {
this.obtainedCertifications = obtainedCertifications;
}
public List<ObtainedSkill> getObtainedSkills() {
return this.obtainedSkills;
}
public void setObtainedSkills(List<ObtainedSkill> obtainedSkills) {
this.obtainedSkills = obtainedSkills;
}
public List<PhoneNumber> getPhoneNumbers() {
return this.phoneNumbers;
}
public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List<PrivilegeRequest> getPrivilegeRequests() {
return this.privilegeRequests;
}
public void setPrivilegeRequests(List<PrivilegeRequest> privilegeRequests) {
this.privilegeRequests = privilegeRequests;
}
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
public Source getSource() {
return this.source;
}
public void setSource(Source source) {
this.source = source;
}
public UserInformation getUserInformation() {
return this.userInformation;
}
public void setUserInformation(UserInformation userInformation) {
this.userInformation = userInformation;
}
}
Skill Table
Obtained Skill Table
Resource Table
The first field is the Serial Number which is a varchar
The other collapsed fields are also varchars Middle and Last name.
How I can to do this query:
#NamedQuery(name = "Scuser.findFriends", query = "SELECT s FROM Scuser s, friends f WHERE f.firstid = :iduser and s.iduser = f.secondid")
in this class:
#Entity
#Table(name = "scuser")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Scuser.findAll", query = "SELECT s FROM Scuser s"),
#NamedQuery(name = "Scuser.findByIduser", query = "SELECT s FROM Scuser s WHERE s.iduser = :iduser"),
#NamedQuery(name = "Scuser.findByUpassword", query = "SELECT s FROM Scuser s WHERE s.upassword = :upassword"),
#NamedQuery(name = "Scuser.findByUname", query = "SELECT s FROM Scuser s WHERE s.uname = :uname"),
#NamedQuery(name = "Scuser.findByTpoints", query = "SELECT s FROM Scuser s WHERE s.tpoints = :tpoints"),
// #NamedQuery(name = "Scuser.findFriends", query = "SELECT s FROM Scuser s, friends f WHERE f.firstid = :iduser and s.iduser = f.secondid"),
#NamedQuery(name = "Scuser.findByUnameUpassword", query = "SELECT s FROM Scuser s WHERE s.uname = :uname and s.upassword = :upassword")})
public class Scuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 2147483647)
#Column(name = "iduser")
private String iduser;
#Size(max = 200)
#Column(name = "upassword")
private String upassword;
#Size(max = 200)
#Column(name = "uname")
private String uname;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "tpoints")
private Double tpoints;
#JoinTable(name = "friends", joinColumns = {
#JoinColumn(name = "firstid", referencedColumnName = "iduser")}, inverseJoinColumns = {
#JoinColumn(name = "secondid", referencedColumnName = "iduser")})
#ManyToMany
private Collection<Scuser> scuserCollection;
#ManyToMany(mappedBy = "scuserCollection")
private Collection<Scuser> scuserCollection1;
#ManyToMany(mappedBy = "scuserCollection")
private Collection<Beach> beachCollection;
public Scuser() {
}
public Scuser(String iduser) {
this.iduser = iduser;
}
public String getIduser() {
return iduser;
}
public void setIduser(String iduser) {
this.iduser = iduser;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Double getTpoints() {
return tpoints;
}
public void setTpoints(Double tpoints) {
this.tpoints = tpoints;
}
#XmlTransient
public Collection<Scuser> getScuserCollection() {
return scuserCollection;
}
public void setScuserCollection(Collection<Scuser> scuserCollection) {
this.scuserCollection = scuserCollection;
}
#XmlTransient
public Collection<Scuser> getScuserCollection1() {
return scuserCollection1;
}
public void setScuserCollection1(Collection<Scuser> scuserCollection1) {
this.scuserCollection1 = scuserCollection1;
}
#XmlTransient
public Collection<Beach> getBeachCollection() {
return beachCollection;
}
public void setBeachCollection(Collection<Beach> beachCollection) {
this.beachCollection = beachCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (iduser != null ? iduser.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Scuser)) {
return false;
}
Scuser other = (Scuser) object;
if ((this.iduser == null && other.iduser != null) || (this.iduser != null && !this.iduser.equals(other.iduser))) {
return false;
}
return true;
}
#Override
public String toString() {
return "REST.Scuser[ iduser=" + iduser + " ]";
}
}
If I understand correctly, you have the ID of a user, and you want to get the friends of the user identified by this ID. The easiest way is to do
Scuser user = em.find(User.class, userId);
Collection<Scuser> friends = user.getScuserCollection();
If you want to do it using a JPQL query, you just need
select friend from Scuser user
inner join user.scuserCollection friend
where user.id = :userId
Note that your mapping isn't right: scuserCollection1 and beachCollection are both mapped by the same attribute. You should also choose better names for your associations (like friends for example, instead of scuserCollection).
I have an entity :
#Entity
#DiscriminatorValue("News")
public class News extends TVProduction {
private int audience;
private Collection<Reportage> reportages;
public News() {
super();
setAudience(0);
}
#Column(name = "audience")
public int getAudience() {
return audience;
}
public void setAudience(int audience) {
this.audience = audience;
}
#OneToMany
#JoinTable(name = "Reportages_News",
joinColumns = #JoinColumn(name = "news_id"),
inverseJoinColumns = #JoinColumn(name = "reportage_id")
)
public Collection<Reportage> getReportages() {
return reportages;
}
public void setReportages(Collection<Reportage> reportages) {
this.reportages = reportages;
}
}
And Reportage class looks like this:
#Entity
#Table(name = "Reportage")
public class Reportage {
private Long id;
private String subject;
private int version;
private String content;
private Reporter reporter;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name = "reporter_fk")
public Reporter getReporter() {
return reporter;
}
public void setReporter(Reporter reporter) {
this.reporter = reporter;
}
}
What I want is to have only the highest versions of Reportages fetched while fetching News. I tried to annotate Reportage with:
#Loader(namedQuery = "fetchFinal")
#NamedNativeQuery(name = "fetchFinal", query = "SELECT t.* FROM" +
"(SELECT id, subject, max(version) maxVersion, content, reporter" +
"FROM reportage GROUP BY id) x" +
"JOIN reportage t ON x.id = t.id AND x.maxVersion = t.version AND t.id = ?"
)
but It doesn't work, saying:
Initial SessionFactory creation failed.org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported
Any idea how to get it done?
How about:
select * from reportage t where t.version = (select max(t2.version) from reportage t2)
UPDATE:
Have not tried this myself:
#NamedNativeQuery(name = "fetchFinal", query = "SELECT t.* FROM" +
"(SELECT id, subject, max(version) maxVersion, content, reporter" +
"FROM reportage GROUP BY id) x" +
"JOIN reportage t ON x.id = t.id AND x.maxVersion = t.version AND t.id = ?",
resultClass=Reportage.class)
= add Resultclass
UPDATE2
If that doesn't work this certainly will (since I've done this myself); using Criteria:
Criteria crit = getSession().createCriteria(Reportage.class);
DetachedCriteria dc = DetachedCriteria.forClass(Reportage.class);
dc.setProjection(Projections.max("version"));
crit.add(Property.forName("version").eq(dc));
return crit.list();