Hibernate query to get a different user table data not working - java

I am trying to simply fetch the records from a table with the following scenario:
User: abc is the one with which I am loggin into my db it has the rights to select.
Table I am trying to access is xyz.customer, DB user xyz has this table customer.
The error that I am getting is that entity not found. even the I have clearly mentioned my class in the package scan. I tried making SqlResultSetMapping and then it said not found again. I put it in another entity class which is working fine and it still said SqlResultSetMapping not found. My code is as follow:
The code where I am calling it and gives error:
List<SampleClass> sampleClass=
entityIBSManager.createNativeQuery("select * from xyz.customer","CustomerMapping").getResultList();
The code of my entity class:
#Entity
#Table(name = "CUSTOMER", catalog = "XYZ")
#NamedQuery(name = "SampleClass.findAll", query = "select p from SampleClass p")
#SqlResultSetMapping(
name = "CustomerMapping",
entities = #EntityResult(
entityClass = SampleClass.class,
fields = {
#FieldResult(name = "customerNo", column = "CUSTOMER_ID"),
#FieldResult(name = "countryCode", column = "COUNTRY_CODE"),
#FieldResult(name = "status", column = "STATUS")}))
public class SampleClass implements Serializable {
#Id
#Column(name="CUSTOMER_ID")
private Long customerNo;
#Id
#Column(name="COUNTRY_CODE")
private String countryCode;
#Column(name="STATUS")
private int status;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Long getCustomerNo() {
return customerNo;
}
public void setCustomerNo(Long customerNo) {
this.customerNo = customerNo;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Override
public String toString() {
return "PurgeCustomersIBS [customerNo=" + customerNo + ", countryCode=" + countryCode + ", status=" + status + "]";
}
}
In My DB table I have a composite key combination of country code and customer no.
and I have tried using the direct call to my named query and it gives the error of no named query found.
Thankyou for your help in advance.
Here is my stacktrace
07:57:12.006 [readTask_Worker-3] ERROR org.quartz.core.JobRunShell - Job DEFAULT.cSVFileJob threw an unhandled Exception: java.lang.IllegalArgumentException: No query defined for that name [PurgeCustomersIBS.findAll] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.buildQueryFromName(AbstractEntityManagerImpl.java:753) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:890) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]

Related

Hibernate query returns null, but entity gets loaded on object anyway

This will take some explaining. So, I have an entity called Invoice and a related table called Errors, which is used to store some processing errors.
In a DAO class, I have a query for fetch the errors with some specific criteria:
public Errors loadLastError(Invoice i) {
try (Session session = factory.openSession()) {
Query query = session.createQuery("select er from Errors er" +
" inner join er.invoice i" +
" where er.invoice = :invoice" +
" and i.status <> :code" +
" and i.proccessStatus = :status" +
" order by er.id desc");
query.setParameter("invoice", invoice);
query.setParameter("code", "001");
query.setParameter("status", "form_error");
var result = query.getSingleResult();
return (Errors) result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This works fine: will only get results when the conditions match. When they don't, I get the expected null result where this method is called:
this.invoice.setError(loadLastError(this.invoice);
When inspecting the code, I can see that the this.invoice object was updated correctly with a null result.
But, as soon as I pass this object invoice to another class in order to do some proccessing (send notifications basically by JSON), it gets there with a Errors object loaded, as if my original query had actually found something, which it didn't.
The following are a shortened example of my entity classes:
The Invoice:
#Entity
#DynamicUpdate
#Table(name = "data.invoice")
#TypeDef(
name = "pgsql_enum",
typeClass = PostgreSQLEnumType.class
)
public class Invoice implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#JsonIgnore
#Column(name = "proccessStatus")
private String proccessStatus;
#JsonIgnore
#Column(name = "status")
private String status;
#JsonIgnore
#OneToOne(mappedBy = "invoice", fetch = FetchType.LAZY)
private Errors errors;
public Integer getId() {
return id;
}
public String getProccessStatus() {
return proccessStatus;
}
public void setProccessStatus(String proccessStatus) {
this.proccessStatus= proccessStatus;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status= status;
}
public Errors getErrosr() {
return errors;
}
public void setErrors(Errorserrors) {
this.errors= errors;
}
The Errors entity:
#Entity
#Table(name = "data.invoice_errors")
public class Errors implements Serializable {
public Errors() {
}
public Errors(Invoice invoice, String error) {
this.invoice= invoice;
this.error = error;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#OneToOne
#JoinColumn(name = "id_invoice")
private Invoice invoice;
private String error;
#Column(name = "created_at")
private LocalDateTime createdAt;
public Integer getId() {
return id;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
This behaviour seems very strange and I don't know how to diagnose it and what may be wrong. Any input would be very appreciated.
What I'm expecting is that the entity don't get updated out of nowhere with a result that wasn't found initially because it simply didn't match the search criteria in the first place.
I'm a colossal idiot. The issue was that the notification class was refreshing the model. Changed the database search to go after the refresh and fixed the problem.

How do I add a foreign key to my entity in Room 2.3.0?

I have a project that I have worked with Room 2.2.5, I just updated to version 2.3.0 this is the code of an entity called photo:
#Entity(tableName = Photo.TABLE_NAME, foreignKeys = #ForeignKey(entity = Event.class,
parentColumns = "_id",
childColumns = "id_event_ft",
onDelete = ForeignKey.CASCADE))
public class Photo {
public static final String TABLE_NAME = "Photo";
public static final String COLUMN_ID = BaseColumns._ID;
#PrimaryKey(autoGenerate = true)
#ColumnInfo(index = true, name = COLUMN_ID)
public Long id_photo;
#ColumnInfo(name = "path")
private String path;
#ForeignKey(entity = Event.class,
parentColumns = "_id",
childColumns = "id_event_ft",
onDelete = ForeignKey.CASCADE)
private Long id_event_ft;
public Photo(Long id_photo, String path, Long id_event_ft) {
this.id_photo = id_photo;
this.path = path;
this.id_event_ft = id_event_ft;
}
public Long getId_photo() {
return id_photo;
}
public void setId_photo(Long id_photo) {
this.id_photo = id_photo;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Long getId_event_ft() {
return id_event_ft;
}
public void setId_event_ft(Long id_event_ft) {
this.id_event_ft = id_event_ft;
}
}
Now I am getting the following error when trying to compile
error: annotation type not applicable to this kind of declaration
#ForeignKey(entity = Event.class, parentColumns = "_id", childColumns = "id_event_ft", onDelete = ForeignKey.CASCADE)
^
The error is in the #ForeignKey that is above the variable private Long id_event_ft;
In the documentation I found this:
Added missing target to #ForeignKey annotation preventing its usage outside of the #Entity annotation. (Iced1e)
It is clear that using #ForeignKey outside of the #Entity annotation is no longer allowed, but then how do I bind the id_event_ft variable to the foreign key?, How do I assign a value to it now?
I hope someone can help me, thank you very much
Using ForeignKey does not automatically (magically) make a relationship. Rather it allows a relationship to be supported primarily by enforcing referential integrity.
There is no need for a ForeignKey definition for a Foreign Key (relationship) to exist.
That is it is defining a rule that says that the value of the child column (id_event_ft) MUST be a value that is present in the parent column (_id). It also supports handling if there is a Foreign Key Conflict (e.g. onDelete as you have used).
Actually providing a suitable value is something that you have to do programmatically, that is id adding a photo you have to determine which Event the photo is to be linked/related to.
You can use #Relation to simplify extracting related data.
So consider the following:
An Event Entity (nice and simple for demonstration)
#Entity
public class Event {
#PrimaryKey(autoGenerate = true)
Long _id = null;
String other_columns;
public Event(){}
#Ignore
public Event(String other_columns) {
this.other_columns = other_columns;
}
}
A Photo's parent column will be the _id column.
Second Ignored (i.e. Ignored by Room) constructor otherwise Room issue a warning like *warning: There are multiple good constructors and Room will pick the no-arg constructor. *
A slightly changed Photo Entity :-
#Entity(tableName = Photo.TABLE_NAME,
foreignKeys = #ForeignKey(
entity = Event.class,
parentColumns = "_id",
childColumns = "id_event_ft",
onDelete = ForeignKey.CASCADE),
indices = #Index("id_event_ft") //<<<<<<<<<< ADDED as Room warns if omitted
)
public class Photo {
public static final String TABLE_NAME = "Photo";
public static final String COLUMN_ID = BaseColumns._ID;
#PrimaryKey(autoGenerate = true)
#ColumnInfo(index = true, name = COLUMN_ID)
public Long id_photo;
#ColumnInfo(name = "path")
private String path;
/* <<<<<<<< COMMENTED OUT >>>>>>>>>>
#ForeignKey(entity = Event.class,
parentColumns = "_id",
childColumns = "id_event_ft",
onDelete = ForeignKey.CASCADE)
*/
private Long id_event_ft;
public Photo(Long id_photo, String path, Long id_event_ft) {
this.id_photo = id_photo;
this.path = path;
this.id_event_ft = id_event_ft;
}
public Long getId_photo() {
return id_photo;
}
public void setId_photo(Long id_photo) {
this.id_photo = id_photo;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Long getId_event_ft() {
return id_event_ft;
}
public void setId_event_ft(Long id_event_ft) {
this.id_event_ft = id_event_ft;
}
}
For demonstration of retrieving via a relationship the POJO EventWithPhotos :-
public class EventWithPhotos {
#Embedded
Event event;
#Relation(entity = Photo.class,parentColumn = "_id",entityColumn = "id_event_ft")
List<Photo> photos;
}
Now a Dao AllDao:-
#Dao
interface AllDao {
#Insert
long insert(Event event);
#Insert
long insert(Photo photo);
#Transaction
#Query("SELECT * FROM event")
List<EventWithPhotos> getAllEventsWithPhotos();
}
How do I assign a value to it now?
Now an example that puts it all together adding 2 Events the first with 2 photos, the second with 1 photo. Note the different techniques used:-
dao = db.getAllDao();
// Prepare to add an Event
Event newEvent = new Event();
newEvent.other_columns = "Event1";
// Add the Event retrieving the id (_id column)
long eventId = dao.insert(newEvent);
// Prepare a photo to be added to Event1
Photo newPhoto = new Photo(null,"photo1",eventId);
// Add the Photo to Event1
long photoid = dao.insert(newPhoto);
// Add second photo to Event 1 using the 2nd constructor
dao.insert(new Photo(null,"photo2",eventId));
// Add Event2 with a photo all in a single line (again using the 2nd constrcutor)
long event2Id;
dao.insert(new Photo(null,"photo3",event2Id = dao.insert(new Event("Event2"))));
// Get and output Each Event with the Photos for that Event
List<EventWithPhotos> allEventsWithPhotosList = dao.getAllEventsWithPhotos();
for (EventWithPhotos ewp: allEventsWithPhotosList) {
Log.d("EVENTPHOTOINFO","Event is " + ewp.event.other_columns);
for (Photo p: ewp.photos) {
Log.d("EVENTWITHPHOTO","\tPhoto is " + p.getPath() + " ID is " + p.getId_photo());
}
}
Result
When run the log contains :-
D/EVENTPHOTOINFO: Event is Event1
D/EVENTWITHPHOTO: Photo is photo1 ID is 1
D/EVENTWITHPHOTO: Photo is photo2 ID is 2
D/EVENTPHOTOINFO: Event is Event2
D/EVENTWITHPHOTO: Photo is photo3 ID is 3
The Database (view with Database Inspector) shows:-
The Event table :-
The Photo table :-
Relations
#Many To One
if the relation is many photo for one event, use ORM Hibernate, this is the easiest way to define foreign key with constraint on your Photo Entity
#ManyToOne
#JoinColumn(name = "id", nullable = false)
private Event id_event_ft;

org.hibernate.hql.internal.ast.QuerySyntaxException: REPORT Table is not mapped

I have a simple API that expects three parameters and sends a response back, whenever I try to pass the three parameters I end up with an error
org.hibernate.hql.internal.ast.QuerySyntaxException: REPORTS
is not mapped [SELECT e FROM REPORTS e WHERE e.country =
:country AND e.projectId = :projectId AND e.code = :code]
The Model class
#Entity(name = "REPORTS")
#Table(name = "REPORTS")
public class DashboardModel {
public String Country;
public String Project;
public String HtmlContent;
public String FileName;
public String Code;
public String TeamLead;
public String Team;
public DateTime CreateDate;
public DateTime UpdateDate;
//boiler plate code
My Controller
#GetMapping(path = "/report/reportsheet")
public ResponseEntity<String> getReportSheet(#RequestParam("country") String country,
#RequestParam("projectId") String projectId,
#RequestParam("clusterNumber") String clusterNumber){
String report = dashboardService.getReport(country,projectId,clusterNumber);
//String report_ = wallboardService.getStateReportLabelByCountryProjectAndType(country,projectId,reportType);
return ResponseEntity.status(HttpStatus.OK).body(report);
My Service
public String getReport(String country,String projectId,String code){
TypedQuery<DashboardModel> query = entityManager.createQuery(
"SELECT e FROM REPORTS e WHERE e.country = :country AND e.projectId = :projectId AND e.code = :clusterNumber" , DashboardModel.class);
List<DashboardModel> dashboard = query
.setParameter("country", country)
.setParameter("projectId", projectId)
.setParameter("clusterNumber", code)
.getResultList();
return String.valueOf(dashboard);
}
How should I map the table correctly?
You have to use entity class names like DashboardModel in the JPQL and a table name REPORTS in the SQL.
The second parameter DashboardModel.class in the createQuery() is not related to entity class name in the SELECT clause.
You can just use createQuery(jpql) with one parameter, but that method returns a List without element type. So what the second parameter DashboardModel.class for.
You don't need to specify table name here #Entity(name = "REPORTS")
just #Entity
I guess the entity is not in a package that is scanned by Spring Boot. Here is an article about this: https://springbootdev.com/2017/11/13/what-are-the-uses-of-entityscan-and-enablejparepositories-annotations/

Getting entity from table without having primary key in Hibernate

I'm currently working on a project where I'm trying to get a list of enities from table which does not have a primary key (dk_systemtherapie_merkmale). This table is 1:n related to another table (dk_systemtherapie). See the screenshot for the table structure.
When getting an entry for dk_systemtherapie, the program fetches the Collection "dkSystemtherapieMerkmalesById". However, the first table entry is fetched as often as the number of actual entries in the table is. It never fetches the other entries from dk_systemtherapie_merkmale. I assume it has something to do with the fact that hibernate can't differ between the entries, but I don't know how to fix it.
Table schema
I've created two corresponding entity classes, dk_systemtherapie:
#Entity
#Table(name = "dk_systemtherapie", schema = "***", catalog = "")
public class DkSystemtherapieEntity {
private int id;
private Collection<DkSystemtherapieMerkmaleEntity> dkSystemtherapieMerkmalesById;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(mappedBy = "dkSystemtherapieByEintragId")
public Collection<DkSystemtherapieMerkmaleEntity> getDkSystemtherapieMerkmalesById() {
return dkSystemtherapieMerkmalesById;
}
public void setDkSystemtherapieMerkmalesById(Collection<DkSystemtherapieMerkmaleEntity> dkSystemtherapieMerkmalesById) {
this.dkSystemtherapieMerkmalesById = dkSystemtherapieMerkmalesById;
}
}
Here the second one, which is accessing the table without a primary key, dk_systhemtherapie_merkmale:
#Entity #IdClass(DkSystemtherapieMerkmaleEntity.class)
#Table(name = "dk_systemtherapie_merkmale", schema = "***", catalog = "")
public class DkSystemtherapieMerkmaleEntity implements Serializable {
#Id private Integer eintragId;
#Id private String feldname;
#Id private String feldwert;
private DkSystemtherapieEntity dkSystemtherapieByEintragId;
#Basic
#Column(name = "eintrag_id")
public Integer getEintragId() {
return eintragId;
}
public void setEintragId(Integer eintragId) {
this.eintragId = eintragId;
}
#Basic
#Column(name = "feldname")
public String getFeldname() {
return feldname;
}
public void setFeldname(String feldname) {
this.feldname = feldname;
}
#Basic
#Column(name = "feldwert")
public String getFeldwert() {
return feldwert;
}
public void setFeldwert(String feldwert) {
this.feldwert = feldwert;
}
#Id
#ManyToOne
#JoinColumn(name = "eintrag_id", referencedColumnName = "id")
public DkSystemtherapieEntity getDkSystemtherapieByEintragId() {
return dkSystemtherapieByEintragId;
}
public void setDkSystemtherapieByEintragId(DkSystemtherapieEntity dkSystemtherapieByEintragId) {
this.dkSystemtherapieByEintragId = dkSystemtherapieByEintragId;
}
}
I assume the problem is releated to the fact that Hibernate is using the following annotation as the one and only id for fetching data from database.
#Id
#ManyToOne
#JoinColumn(name = "eintrag_id", referencedColumnName = "id")
public DkSystemtherapieEntity getDkSystemtherapieByEintragId() {
return dkSystemtherapieByEintragId;
}
This leads to the problem that when getting more than one entry with the same id (as the id is not unique), you will get the number of entries you would like to but hibernate is always fetching the first entry for this id. So in fact you are getting dublicate entries.
So how to fix this?
According to this question: Hibernate and no PK, there are two workarounds which are actually only working when you don't have NULL entries in your table (otherwise the returning object will be NULL as well) and no 1:n relationship. For my understanding, hibernate is not supporting entities on tables without primary key (documentation). To make sure getting the correct results, I would suggest using NativeQuery.
Remove the Annotations and private DkSystemtherapieEntity dkSystemtherapieByEintragId; (incl. beans) from DkSystemtherapieMerkmaleEntity.java und add a constructor.
public class DkSystemtherapieMerkmaleEntity {
private Integer eintragId;
private String feldname;
private String feldwert;
public DkSystemtherapieMerkmaleEntity(Integer eintragId, String feldname, String feldwert) {
this.eintragId = eintragId;
this.feldname = feldname;
this.feldwert = feldwert;
}
public Integer getEintragId() {
return eintragId;
}
public void setEintragId(Integer eintragId) {
this.eintragId = eintragId;
}
public String getFeldname() {
return feldname;
}
public void setFeldname(String feldname) {
this.feldname = feldname;
}
public String getFeldwert() {
return feldwert;
}
public void setFeldwert(String feldwert) {
this.feldwert = feldwert;
}
}
Remove private Collection<DkSystemtherapieMerkmaleEntity> dkSystemtherapieMerkmalesById; (incl. beans) from DkSystemtherapieEntity.java.
Always when you need to get entries for a particular eintrag_id, use the following method instead of the Collection in DkSystemtherapieEntity.java.
public List<DkSystemtherapieMerkmaleEntity> getDkSystemtherapieMerkmaleEntities(int id) {
Transaction tx = session.beginTransaction();
String sql = "SELECT * FROM dk_systemtherapie_merkmale WHERE eintrag_id =:id";
List<Object[]> resultList;
resultList = session.createNativeQuery(sql)
.addScalar("eintrag_id", IntegerType.INSTANCE)
.addScalar("feldname", StringType.INSTANCE)
.addScalar("feldwert", StringType.INSTANCE)
.setParameter("id", id).getResultList();
tx.commit();
List<DkSystemtherapieMerkmaleEntity> merkmale = new ArrayList<>();
for (Object[] o : resultList) {
merkmale.add(new DkSystemtherapieMerkmaleEntity((Integer) o[0], (String) o[1], (String) o[2]));
}
return merkmale;
}
Call getDkSystemtherapieMerkmaleEntities(dkSystemtherapieEntityObject.getid()) instead of getDkSystemtherapieMerkmalesById().

IN and = operator in JPA query language

I have a problem regarding jpa query.
There are two tables i.e. Post table and Tag table
There is many to many relationship between Post and Tag
Now I want to write a query such that when multiple tags are chosen then all the posts associated with those tags should be selected.
For example,
post1 has tags friends and motivation
post2 has tags motivation and pune
post3 has tag boxing
if tags friends and pune are chosen then post1 and post 2 should be retrieved
if tag boxing is chosen then only post 3 should be retrieved
if tags boxing and motivation are chosen then all three posts should be retrieved.
I tried following things
SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags IN :tags
but it gives validator error that
The state field path 'p.tags' cannot be resolved to a collection type.
If I try like this
SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags = :tags
then it complies fine but after passing a list of tags it gives error
java.lang.IllegalArgumentException: You have attempted to set a value of type class java.util.ArrayList for parameter tags with expected type of class com.justme.model.entities.Tag from query string SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags = :tags.
Thank you for reading this much :) can you please guide me on this?
how can I achieve the results mentioned above?
my persistence provider is eclipseLink
This is Post entity
#Entity
#NamedQueries({
#NamedQuery(name = "Post.selectAllPosts", query = "SELECT p FROM Post p ORDER BY p.dateCreated DESC"),
#NamedQuery(name = "Post.selectPostForUser", query = "SELECT p FROM Post p WHERE p.user = :user ORDER BY p.dateCreated DESC"),
#NamedQuery(name = "Post.selectPostsByTags", query = "SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE p.tags IN :tags") })
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idpost;
#Lob
private String content;
private String title;
// bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "iduser")
private User user;
// bi-directional many-to-many association to Tag
#ManyToMany(cascade = CascadeType.PERSIST)
#JoinTable(name = "post_tag", joinColumns = #JoinColumn(name = "idpost"), inverseJoinColumns = #JoinColumn(name = "idtag"))
private List<Tag> tags = new ArrayList<Tag>();
#Temporal(TemporalType.DATE)
private Date date = null;
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreated = new Date();
public Post() {
}
public int getIdpost() {
return this.idpost;
}
public void setIdpost(int idpost) {
this.idpost = idpost;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public List<Tag> getTags() {
return this.tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Override
public String toString() {
return "Post [idpost=" + idpost + ", content=" + content + ", title="
+ title + ", date=" + date + "]";
}
}
This is Tag Entity
#Entity
#NamedQueries({
#NamedQuery(name = "Tag.selectTags", query = "SELECT tag FROM Tag tag WHERE tag.tagName LIKE :keyword"),
#NamedQuery(name = "Tag.selectMatchingTags", query = "SELECT t.tagName FROM Tag t WHERE t.tagName LIKE :keyword"),
#NamedQuery(name = "Tag.selectTagByName", query = "SELECT tag FROM Tag tag WHERE tag.tagName = :tagName"),
#NamedQuery(name = "Tag.selectTagsForAllPosts", query = "SELECT DISTINCT tag FROM Tag tag, Post post JOIN tag.posts posts WHERE post.user = :user")})
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idtag;
private String tagName;
// bi-directional many-to-many association to Post
#ManyToMany(mappedBy = "tags", cascade = CascadeType.PERSIST)
private List<Post> posts;
public Tag() {
}
public Tag(String tagName) {
this.tagName = tagName;
}
public int getIdtag() {
return this.idtag;
}
public void setIdtag(int idtag) {
this.idtag = idtag;
}
public String getTagName() {
return this.tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public List<Post> getPosts() {
return this.posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
#Override
public String toString() {
return tagName;
}
}
Try:
...
#NamedQuery(name = "Post.selectPostsByTags", query =
"SELECT DISTINCT p FROM Post p JOIN p.tags tags WHERE tags IN (:tags)") })
public class Post implements Serializable {
...
Use it like this:
#PersistenceContext
public EntityManager em;
...
List<Tag> ltags = new ArrayList<Tag>();
ltags.add(tagOne);
ltags.add(tagTwo);
List<?> list = em.createNamedQuery("Post.selectPostsByTags")
.setParameter("tags", ltags)
.getResultList();
for (Object object : list) {
System.out.println("Results: "+object);
}

Categories

Resources