#OnetoMany class call - java

i need some help for my class...
package com.it.ese.orbit.entity;
import javax.persistence.*;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Shahriar Newaz
* Date: 07/03/11
* Time: 10.07
*/
#Entity
#Inheritance(strategy =InheritanceType.JOINED)
public class OrbitObject {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="id",nullable = false)
private Long id;
#Column(name="Scenario",nullable = false)
private String scenario; // not sure about how to map scenario
#Column(name="code",nullable = true)
private String code;
#Column(name="name",nullable = true)
private String name;
#OneToOne(cascade=CascadeType.ALL)
private Bia bia;
#OneToOne(cascade=CascadeType.ALL)
public Impatti impatti;
#Column(name="parent",nullable = true)
#OneToMany(cascade=CascadeType.ALL)
private OrbitObject OrbitObject;
public Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScenario() {
return scenario;
}
public void setScenario(String scenario) {
this.scenario = scenario;
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
// LOG
#Override
public String toString(){
return "com.it.ese.orbit.models.OrbitObject["
+ " - name="+name + " - scenario="+scenario +" - id= "+id+"]";
}
}
But i get thi error...
Caused by: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: com.it.ese.orbit.entity.OrbitObject.OrbitObject
I wish i create an OrbitObject field as like an object of the same class...
Help please!

You either do
#Column(name="parent",nullable = true)
#ManyToOne(cascade=CascadeType.ALL)
private OrbitObject OrbitObject;
Or
#Column(name="parent",nullable = true)
#OneToMany(cascade=CascadeType.ALL)
private Set<OrbitObject> OrbitObject;
The first case implies this entity will be the owning side, namely, it will have the foreign key.

OneToMany means that OrbitObject has many OrbitObject children, which is not true because the OrbitObject property is not a collection.
You must convert it to a ManyToOne

you can use #OneToMany referring to a collection of elements, for example
#OneToMany
List<OrbitObject> orbitList;

Related

JPA system exception error accesing field

I'm trying to implement a unidirectional many to many relationship between entities with spring+JPA.
After a few tries changing hibernate versions I don't know whats the cause
Caused by: org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Integer com.uca.refactor2.model.Achievement.id] by reflection for persistent property [com.uca.refactor2.model.Achievement#id] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer com.uca.refactor2.model.Achievement.id] by reflection for persistent property [com.uca.refactor2.model.Achievement#id] : 1
User.java
#Entity
#Table(name="USER")
public class User implements Serializable {
private static final long serialVersionUID = 4402583037980335445L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
#Column(unique = true)
private String username;
private String password;
#Enumerated(EnumType.STRING)
private UserType userType;
#OneToMany(cascade=CascadeType.ALL, mappedBy="joinedUserAchievementId.user")
private List<JoinedUserAchievement> joinedUserAchievementList = new ArrayList<JoinedUserAchievement>();
public User() {}
public User(Integer id) {
this.id = id;
}
public User(String username, String firstName, String lastName,
String password, UserType userType) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.userType = userType;
}
public List<JoinedUserAchievement> getAllAchievement() {
return joinedUserAchievementList;
}
public void addAchievement(Achievement achievement) {
// Notice a JoinedUserAchievement object
Date dateOfAcquisition = new Date();
JoinedUserAchievement joinedUserAchievement = new JoinedUserAchievement(new JoinedUserAchievement.JoinedUserAchievementId(this, achievement),dateOfAcquisition );
joinedUserAchievement.setAchievementId(achievement.getId());
joinedUserAchievementList.add(joinedUserAchievement);
}
//set and gets
JoinedUserAchievement.java
#Entity
#Table(name="USER_ACHIEVEMENT")
public class JoinedUserAchievement {
public JoinedUserAchievement() {}
public JoinedUserAchievement(JoinedUserAchievementId joinedUserAchievementId, Date dateOfAcquisition) {
this.joinedUserAchievementId = joinedUserAchievementId;
this.dateOfAcquisition = dateOfAcquisition;
}
#ManyToOne(targetEntity = Achievement.class)
#JoinColumn(name="id", insertable=false, updatable=false)
private Integer achievementId;
private Date dateOfAcquisition;
public String getDate() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = dateOfAcquisition;
return dateFormat.format(date);
}
public Integer getAchievementId() {
return achievementId;
}
public void setAchievementId(Integer achievementId) {
this.achievementId = achievementId;
}
#EmbeddedId
private JoinedUserAchievementId joinedUserAchievementId;
// required because JoinedUserAchievments contains composite id
#Embeddable
public static class JoinedUserAchievementId implements Serializable {
/**
*
*/
private static final long serialVersionUID = -9180674903145773104L;
#ManyToOne
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne
#JoinColumn(name="ACHIEVEMENT_ID")
private Achievement achievement;
// required no arg constructor
public JoinedUserAchievementId() {}
public JoinedUserAchievementId(User user, Achievement achievement) {
this.user = user;
this.achievement = achievement;
}
public JoinedUserAchievementId(Integer userId, Integer achievementId) {
this(new User(userId), new Achievement(achievementId));
}
public User getUser() {
return user;
}
public Achievement getAchievement() {
return achievement;
}
public void setUser(User user) {
this.user = user;
}
public void setAchievement(Achievement achievement) {
this.achievement = achievement;
}
#Override
public boolean equals(Object instance) {
if (instance == null)
return false;
if (!(instance instanceof JoinedUserAchievementId))
return false;
final JoinedUserAchievementId other = (JoinedUserAchievementId) instance;
if (!(user.getId().equals(other.getUser().getId())))
return false;
if (!(achievement.getId().equals(other.getAchievement().getId())))
return false;
return true;
}
#Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + (this.user != null ? this.user.hashCode() : 0);
hash = 47 * hash + (this.achievement != null ? this.achievement.hashCode() : 0);
return hash;
}
}
}
Achievement.java
#Entity
#Table(name="ACHIEVEMENT")
public class Achievement implements Serializable{
private static final long serialVersionUID = 7747630789725422177L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer points;
public Achievement() {
}
public Achievement(String name, Integer points) {
this.name = name;
this.points = points;
}
public Achievement(Integer id) {
this.id = id;
}
//set and gets
I've also tried to make this relationship bidirectional and it didn't work, so I may be missing something
Also before this I had achievement objects instead of achievementId on joinedUserAchievement, it worked but I think its not what I need, I don't need to get every achievement object always, with only the id is fine.
From the docs:
Relationship mappings defined within an embedded id class are not supported
You should put the ids only in JoinedUserAchievementId, and put User and Achievement associations in JoinedUserAchievement directly like so:
public class JoinedUserAchievementId {
private Long userId;
private Long achievementId;
...
}
public class JoinedUserAchievement {
#EmbeddedId
private JoinedUserAchievementId joinedUserAchievementId;
#ManyToOne
#MapsId("userId")
#JoinColumn(name = "USER_ID")
private User user;
#ManyToOne(optional = false, fetch = LAZY)
#MapsId("achievementId")
#JoinColumn(name = "ACHIEVEMENT_ID")
private Achievement achievement;
//if you absolutely need to map the achievement_id column here as well
//note that it will already be mapped to joinedUserAchievementId.achievementId
#Column(name = "ACHIEVEMENT_ID", insertable=false, updatable=false)
private Long achievementId;
...
}
Remember to update the User.joinedUserAchievementList mapping to mappedBy="user".

JSON Infinite string when using hibernate one to many and many to one mapping REST web service

I am facing some weird issue when using Hibernate one to many and many to one mapping and returning data using JSON to my swing client from rest web service.
When my web service is returning salesOrder object. i have checked that it does contains orderlines objects set. But, if i open one of the orderLine object, it again has sales order object.
This chaining is causing issue as client side that infinite string of json is being returned.
Like below...
[
{
"salesOrderNumber":"1",
"customerCode":"1",
"totalPrice":50.0,
orderLines":
[
{
"salesOrderNumber":"1",
"productCode":"2",
"quantity":1,
"salesOrder":{"salesOrderNumber":"1","customerCode":"1","totalPrice":50.0,"orderLines":[{"salesOrderNumber":"1","productCode":"2","quantity":1,"salesOrder":{"salesOrderNumber":"1","customerCode":"1","totalPrice":50.0,"orderLines":
.............................................
...............................
I have tried to set #JSONIgnore as i don't want those to be sent to client, but, it didn't help.
My Two entities are like below:
#Entity
#Table(name = "salesorder")
//#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class SalesOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "SalesOrderNumber", unique = true, nullable = false)
private String salesOrderNumber;
#Column(name = "CustomerCode")
private String customerCode;
#Column(name = "TotalPrice")
private double totalPrice;
#JsonIgnore
#OneToMany(fetch = FetchType.EAGER, mappedBy="salesOrder",cascade=CascadeType.ALL)
private Set<OrderLines> orderLines = new HashSet<OrderLines>();
public Set<OrderLines> getOrderLines() {
return orderLines;
}
public void setOrderLines(Set<OrderLines> orderLines) {
this.orderLines = orderLines;
}
public String getSalesOrderNumber() {
return salesOrderNumber;
}
public void setSalesOrderNumber(String salesOrderNumber) {
this.salesOrderNumber = salesOrderNumber;
}
public String getCustomerCode() {
return customerCode;
}
public void setCustomerCode(String customerCode) {
this.customerCode = customerCode;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
}
#Entity
#Table(name = "orderlines")
//#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class OrderLines implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "SalesOrderNumber", unique = true, nullable = false)
private String salesOrderNumber;
#Id
#Column(name = "ProductCode")
private String productCode;
#Column(name = "Quantity")
private int quantity;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="SalesOrderNumber")
private SalesOrder salesOrder;
public SalesOrder getSalesOrder() {
return salesOrder;
}
public void setSalesOrder(SalesOrder salesOrder) {
this.salesOrder = salesOrder;
}
public String getSalesOrderNumber() {
return salesOrderNumber;
}
public void setSalesOrderNumber(String salesOrderNumber) {
this.salesOrderNumber = salesOrderNumber;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
It's a really bad idea to send your entities as json, as it will couple your clients to the internal representation of your system... and bad hacks come from this. If you do want to do this regardless and suffer later (or let one of your future colleagues suffer and curse you), keep reading.
The reason why it doesn't work is because Hibernate creates proxies from the objects that it gets from the DB, and the annotations are lost. There is a Jackson extension that will take care of this jackson-datatype-hibernate, but please don't do it (unless your app is trivial and will never change)

Retrieve data using hsql - relation many to one

I define the following entities :BaseEntity , magasin and article :
#Entity(name = "magasin")
#Table(name = "magasin")
public class Magasin extends BaseEntity {
private static final long serialVersionUID = 1L;
#Basic
#Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
#OneToMany(cascade=CascadeType.ALL, mappedBy="magasin")
#Valid
private Set<Article> article;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Article> getArticle() {
return article;
}
public void setArticle(Set<Article> article) {
this.article = article;
}
}
#Entity(name="article")
#Table(name="article")
public class Article extends BaseEntity {
private static final long serialVersionUID = 1L;
#ManyToOne
private Magasin magasin;
#Basic
#Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
#Basic
private float price;
public Magasin getMagasin() {
return magasin;
}
public void setMagasin(Magasin magasin) {
this.magasin = magasin;
}
public String getName() {
return name;
}
public void setName(String nom) {
this.name = nom;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public boolean isNew() {
return (this.id == null);
}
}
How can create a hql query in order to retrieve all Article for a magasin selected ?
I try this
#Override
public List<Article> findArticle(Magasin magasin) {
String query = "From Article m where m.magasin.id = "+magasin.getId();
System.out.print(query);
Session session = getSessionFactory().getCurrentSession();
if((session.createQuery(query).list()!=null) && (session.createQuery(query).list().size()!=0))
return (List<Article>) session.createQuery(query).list();
else
return null;
}
But it returns nothing , always null .How can I resolve it ?
I don't know the type of your magasin id so adapt the code below.
First get the Magasin instance for the id:
Magasin mag = (Magasin)session.get(Magasin.class, id);
Next you can access the articles for the magasin mag via accessor
Set<Article> articles = mag.getArticle();
Try this:
"Select * From Article,Mgasin where Article.mgasin.id = "+magasin.getId();

A cycle is detected in the object graph. This will cause infinitely deep XML

I have two DTO objects say A and B which are having getters and setters and are used to take data from the database. The problem is when I am calling A, B gets called and B again points itself to A and a cycle is created.
I cannot ignore/hide the method which is creating the cycle. I need to take the whole data of A and B.
Is there any way to achieve it ?
Please help
This is my code which is causing the problem. This is application DTO which is calling environment DTO
#OneToMany(mappedBy="application", fetch=FetchType.LAZY
,cascade=CascadeType.ALL
)
public Set<EnvironmentDTO> getEnvironment() {
return environment;
}
public void setEnvironment(Set<EnvironmentDTO> environment) {
this.environment = environment;
}
And this is environment DTO which is calling the application DTO
#ManyToOne(targetEntity=ApplicationDTO.class )
#JoinColumn(name="fk_application_Id")
public ApplicationDTO getApplication() {
return application;
}
public void setApplication(ApplicationDTO application) {
this.application = application;
}
Here cycle is getting created
This is my rest call which will give result in XML format and I think while creating XML cycle is getting created
#GET
#Path("/get")
#Produces({MediaType.APPLICATION_XML})
public List<ApplicationDTO> getAllApplications(){
List<ApplicationDTO> allApplication = applicationService.getAllApplication();
return allApplication;
}
This is the Application DTO class
#Entity
#Table(name="application")
#org.hibernate.annotations.GenericGenerator(
name ="test-increment-strategy",strategy = "increment")
#XmlRootElement
public class ApplicationDTO implements Serializable {
#XmlAttribute
public Long appTypeId;
private static final long serialVersionUID = -8027722210927935073L;
private Long applicationId;
private String applicationName;
private ApplicationTypeDTO applicationType;
private String applicationDescription;
private Integer owner;
private Integer createdBy;
private Integer assignedTo;
private Date createTime;
private Date modifiedTime;
private Set<EnvironmentDTO> environment;
#Id
#GeneratedValue(generator = "test-increment-strategy")
#Column(name = "applicationId")
public Long getApplicationId() {
return applicationId;
}
private void setApplicationId(Long applicationId) {
this.applicationId = applicationId;
}
#Column(name = "applicationName")
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
#ManyToOne(targetEntity=ApplicationTypeDTO.class
,fetch = FetchType.LAZY
)
#JoinColumn(name="applicationType")
public ApplicationTypeDTO getApplicationType() {
return applicationType;
}
public void setApplicationType(ApplicationTypeDTO applicationType) {
this.applicationType = applicationType;
}
#Column(name = "description")
public String getApplicationDescription() {
return applicationDescription;
}
public void setApplicationDescription(String applicationDescription) {
this.applicationDescription = applicationDescription;
}
#Column(name = "owner")
public Integer getOwner() {
return owner;
}
public void setOwner(Integer owner) {
this.owner = owner;
}
#Column(name = "createdBy")
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
#Column(name = "assignedTo")
public Integer getAssignedTo() {
return assignedTo;
}
public void setAssignedTo(Integer assignedTo) {
this.assignedTo = assignedTo;
}
#Column(name = "createTime")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#Column(name = "modifiedTime")
public Date getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(Date modifiedTime) {
this.modifiedTime = modifiedTime;
}
#OneToMany(mappedBy="application", fetch=FetchType.LAZY
,cascade=CascadeType.ALL
)
public Set<EnvironmentDTO> getEnvironment() {
return environment;
}
public void setEnvironment(Set<EnvironmentDTO> environment) {
this.environment = environment;
}
This is the Environment DTO class
#Entity
#Table(name="environment")
#org.hibernate.annotations.GenericGenerator(
name = "test-increment-strategy",
strategy = "increment")
#XmlRootElement
public class EnvironmentDTO implements Serializable {
#XmlAttribute
public Long envTypeId;
#XmlAttribute
public Long appId;
private static final long serialVersionUID = -2756426996796369998L;
private Long environmentId;
private String environmentName;
private EnvironmentTypeDTO environmentType;
private Integer owner;
private Date createTime;
private Set<InstanceDTO> instances;
private ApplicationDTO application;
#Id
#GeneratedValue(generator = "test-increment-strategy")
#Column(name = "envId")
public Long getEnvironmentId() {
return environmentId;
}
private void setEnvironmentId(Long environmentId) {
this.environmentId = environmentId;
}
#Column(name = "envName")
public String getEnvironmentName() {
return environmentName;
}
public void setEnvironmentName(String environmentName) {
this.environmentName = environmentName;
}
#ManyToOne(targetEntity=EnvironmentTypeDTO.class)
#JoinColumn(name = "envType")
public EnvironmentTypeDTO getEnvironmentType() {
return environmentType;
}
public void setEnvironmentType(EnvironmentTypeDTO environmentType) {
this.environmentType = environmentType;
}
#Column(name = "owner")
public Integer getOwner() {
return owner;
}
public void setOwner(Integer owner) {
this.owner = owner;
}
#Temporal(TemporalType.DATE)
#Column(name = "createTime")
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#OneToMany(mappedBy="environment", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
public Set<InstanceDTO> getInstances() {
return instances;
}
public void setInstances(Set<InstanceDTO> instances) {
this.instances = instances;
}
#ManyToOne(targetEntity=ApplicationDTO.class )
#JoinColumn(name="fk_application_Id")
//#XmlTransient
public ApplicationDTO getApplication() {
return application;
}
public void setApplication(ApplicationDTO application) {
this.application = application;
}
Your object graph is cyclic. There is nothing intrinsically wrong with that, and it is a natural consequence of using JPA.
Your problem is not that your object graph is cyclic, but that you are encoding it in a format which cannot handle cycles. This isn't a Hibernate question, it's a JAXB question.
My suggestion would be to stop JAXB from attempting to marshal the application property of the EnvironmentDTO class. Without that property the cyclic graph becomes a tree. You can do this by annotating that property with #XmlTransient.
(confession: i learned about this annotation by reading a blog post by Mr Doughan, which i came across after reading his answer to this question!)
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
MOXy offers the #XmlInverseReference extension to handle this use case. Below is an example of how to apply this mapping on two entities with a bidirectional relationship.
Customer
import javax.persistence.*;
#Entity
public class Customer {
#Id
private long id;
#OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
private Address address;
}
Address
import javax.persistence.*;
import org.eclipse.persistence.oxm.annotations.*;
#Entity
public class Address implements Serializable {
#Id
private long id;
#OneToOne
#JoinColumn(name="ID")
#MapsId
#XmlInverseReference(mappedBy="address")
private Customer customer;
}
For More Information
http://blog.bdoughan.com/2010/07/jpa-entities-to-xml-bidirectional.html
http://blog.bdoughan.com/2013/03/moxys-xmlinversereference-is-now-truly.html
My advice is not exposing your JPA entity class to your webservices. You can create different POJO class and convert your JPA entity to the POJO. For example:
this is your JPA entity
import javax.persistence.*;
#Entity
public class Customer {
#Id
private long id;
#OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
private Address address;
}
you should use this class for your webservices:
public class CustomerModel{
private long id;
//you can call different WS to get the Address class, or combine to this model
public void setFromJpa(Customer customer){
this.id = customer.id;
}
}

Tagging System in Hibernate with Annotations

I am trying to implement a tagging system in my database (MySQL V5.1.61), and then get that working in hibernate. Here are the relevant parts of my database:
And the data contained:
If I am doing this correctly, then 'nir' should have 3 tags associated with him, 'Food','Sorority', and 'Summer Internship'.
What I am having trouble with is implementing this relationship in hibernate (Using annotations):
The UserHibernate class (I'm using GWT so I need separate hibernate and DTO objects):
#Entity
#Table(name="user")
public class UserHibernate implements Serializable{
private int ID;
//removed fields for brevity
private Set<UserTagsHibernate> tags;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "uID")
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
/**
* #return the tags
*/
#OneToMany(mappedBy="user", fetch=FetchType.EAGER)
public Set<UserTagsHibernate> getTags() {
return tags;
}
/**
* #param tags the tags to set
*/
public void setTags(Set<UserTagsHibernate> tags) {
this.tags = tags;
}
}
The UserTagsHibernate Class:
#Entity
#Table(name="usertags")
public class UserTagsHibernate {
private int usertagsID;
private UserHibernate user;
private TagsHibernate tags;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="userforeignkey")
public UserHibernate getUser() {
return user;
}
public void setUser(UserHibernate userHibernate) {
this.user = userHibernate;
}
#OneToOne
#JoinColumn(name="tagforeignkey")
public TagsHibernate getTags() {
return tags;
}
public void setTags(TagsHibernate tagsHibernate) {
this.tags = tagsHibernate;
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "usertagsID")
public int getUsertagsID() {
return usertagsID;
}
public void setUsertagsID(int usertagsID) {
this.usertagsID = usertagsID;
}
}
The TagsHibernate Class:
#Entity
#Table(name = "tags")
public class TagsHibernate {
private int tagID;
//removed for brevity
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "tagID")
public int getTagID() {
return tagID;
}
public void setTagID(int tagID) {
this.tagID = tagID;
}
}
The problem that I am having is that when I try and retrieve a user, here 'nir', he shows up three times. I believe it is because he has 3 tags, so for some reason, when I issue the query "session.createCriteria(UserHibernate.class).add(Restrictions.eq("username", "nir")).list();" I get a list of length 3. Any ideas why this is happening?
This problem pops up all the time when using the Criteria API...it's a known quirk. The workarounds are either to use HQL instead or to add a transformer that filters out the duplicates like so:
session.createCriteria(UserHibernate.class)
.add(Restrictions.eq("username", "nir"))
.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
.list();

Categories