Hibernate - fetch only the latest versions of elements in contained collection - java

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();

Related

Managing both #NamedQueries and #NamedNativeQueries under the same Entity

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")
})

'select count(*) from' is replaced by 'select count(where)' in spring jpa native query when using pagination

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
);

SQL Query with Entity Manager

I've been thinking about how to create a proper query for my purpose but I'm not sure how should I approach it. It's a Spring web app, the website is similar to Twitter.
What I'm trying is to get the messages from who the user that requested the function follows. Saying shortly, a Twitter timeline, there are the classes:
User class
//Imports
#Entity
#Table (name = "USUARIOS")
public class UsuarioVO implements Serializable {
//Not important class attributes and their getters/setters
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "USER_FOLLOW",
joinColumns = #JoinColumn(name = "FOLLOWED_ID"),
inverseJoinColumns = #JoinColumn(name = "FOLLOWER_ID"))
public Set<UsuarioVO> getFollowers() {
return followers;
}
public void setFollowers(Set<UsuarioVO> followers) {
this.followers = followers;
}
public void addFollower(UsuarioVO user) {
followers.add(user);
user.following.add(this);
}
#ManyToMany(mappedBy = "followers")
public Set<UsuarioVO> getFollowing() {
return following;
}
public void setFollowing(Set<UsuarioVO> following) {
this.following = following;
}
public void addFollowing(UsuarioVO user) {
user.addFollower(this);
}
}
Message class
#Entity
#Table(name = "MENSAJES")
public class MensajeVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2819136255644301650L;
private Long id;
private UsuarioVO sender;
private String body;
private Date fecha;
private HashtagVO hashtag;
public MensajeVO() {}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "ID_SENDER")
public UsuarioVO getSender() {
return sender;
}
public void setSender(UsuarioVO sender) {
this.sender = sender;
}
#Column(name = "BODY")
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "FECHA_ENVIO")
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_HASHTAG")
public HashtagVO getHashtag() {
return hashtag;
}
public void setHashtag(HashtagVO hashtag) {
this.hashtag = hashtag;
}
}
The first approach I thought was getting the Set of following from the user and query each one of them to retrieve the messages, but there is a problem with that, I want to order the query by date, with that approach it would only order by date the message of each user, like:
User1 messages ordered by Date
User2 messages ordered by Date
etc..
I was thinking about doing this with an Inner Join, but I'm not sure how should I build the query. An example of a working query:
public Set<MensajeVO> findByUser(Long userid) {
Query query = this.entityManager.createQuery(
"SELECT m FROM MensajeVO m WHERE m.sender.id = ?1 ORDER BY m.fecha DESC", MensajeVO.class);
query.setParameter(1, userid);
return new HashSet<MensajeVO>(query.getResultList());
}
Thanks in advance.
EDIT
In SQL this is the query
SELECT * FROM mensajes INNER JOIN user_follow ON mensajes.ID_SENDER = user_follow.FOLLOWED_ID WHERE user_follow.FOLLOWER_ID = ?
But I don't know how to get user_follow in Java, since is a ManyToMany field.
Figured it out, posting it in case it helps anyone:
Query query = this.entityManager.createQuery(
"SELECT m FROM MensajeVO m WHERE EXISTS(SELECT 1 FROM UsuarioVO u JOIN u.followers fr WHERE fr.id = ?1) OR m.sender.id = ?2 ORDER BY m.fecha DESC", MensajeVO.class);
query.setParameter(1, userid);
query.setParameter(2, userid);
Search for the messages sent by people followed by the user or messages sent by the user.

ResultSet error executing #Query in JPA Reposity, using nativeQuery = true

I am working on a web application using:
Spring Boot
PostgreSQL
JPA and Hibernate.
I have a table called role and another page. Among them there is a many-to-many table with ID's. What I'm trying to get is the list of pages that correspond to a role, so I'm trying to retrieve the list of pages from the id of the role and executing a query to bring the list. The problem is that I have an error in the ResultSet because it tells me that it does not find a column with the name page_id.
Example:
I have executed the query separately and this brings me results correctly.
select p.url from role_page rp, page p where rp.role_id = 6 and rp.page_id = p.page_id;
Output:
Output of the query
Then I made a call to the function to get the list and check it to make sure I get results.
public void rolesAndPages(){
List<Page> pages = pageRepository.findPagePerRole(6);
for (Page page: pages
) {
System.out.println(page.getUrl());
}
}
And throws the error described above:
org.postgresql.util.PSQLException: The column name page_id was not found in this ResultSet.
My Repository:
#Repository("pageRepository")
public interface PageRepository extends JpaRepository<Page, Long> {
#Query(value = "select p.url from role_page rp, page p where rp.role_id = ?1 and rp.page_id = p.page_id", nativeQuery = true)
List<Page> findPagePerRole(Integer id);
}
Role.java
#Entity
#Table(name = "app_role")
public class Role {
#Id
#SequenceGenerator(name="pk_sequence",sequenceName="messagesounds_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="pk_sequence")
#Column(name="role_id")
private int id;
#Column(name="authority")
#NotEmpty(message = "*Please provide a name")
private String authority;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "role_page", joinColumns = #JoinColumn(name = "role_id"), inverseJoinColumns = #JoinColumn(name = "page_id"))
private Set<Page> pages;
public void setPages(Set<Page> pages) {
this.pages = pages;
}
public Set<Page> getPages() {
return pages;
}
public Role() {}
public Role(String authority) {
this.authority = authority;
}
public Role(String authority, Set<Page> pages){
this.authority = authority;
this.pages = pages;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
Page.java
#Entity
#Table(name = "page")
public class Page {
#Id
#SequenceGenerator(name = "pk_sequence", sequenceName = "messagesounds_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence")
#Column(name = "page_id")
private int id;
#Column(name = "name_page")
#NotEmpty(message = "*Please provide a name")
private String name;
#Column(name = "url")
#NotEmpty(message = "*Please provide an url")
private String url;
#Column(name = "description")
#NotEmpty(message = "*Please provide a description")
private String description;
#ManyToMany(mappedBy = "pages")
private Set<Role> roles;
public Page() {
}
public Page(String name_page) {
this.name = name_page;
}
public Page(String name_page, Set<Role> roles) {
this.name = name_page;
this.roles = roles;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
The error is quite explicite, you need to select page_id column to make it work, not only p.url.
Try this to retrieve every column of Page :
#Query(value = "select p.* from role_page rp, page p where rp.role_id = ?1 and rp.page_id = p.page_id", nativeQuery = true)
Or, this to retrieve every columns of tables Page and Role_Page :
#Query(value = "from role_page rp, page p where rp.role_id = ?1 and rp.page_id = p.page_id", nativeQuery = true)
The both queries should work.
Did you tried :
#Query(value = "select p.url from role_page rp, page p where rp.id = ?1 and rp.id = p.id")

delete query with where clause in HQL

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<>();
...

Categories

Resources