Hi Could any one please help me to resolve this exception.Here I have entity class called Person and the thisclass having the instance variable has name and petnames, here petnames I have taken as simple value type that data type is collection and have mapped by using jpa annotation, Please look at my following code and corresponding exception that is generating . And I am facing this exception from so many days.I am struggling to resolve this problem I don not understand where I am going wrong.
Person Class
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#ElementCollection
#CollectionTable(name = "petname")
// #Column(name = "ColumnName")
private Set<String> petname = new HashSet<String>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPetname(Set<String> petname) {
this.petname = petname;
}
public Set<String> getPetname() {
return petname;
}
public boolean addPets(String p) {
return petname.add(p);
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Person)) {
return false;
}
Person other = (Person) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.myapp.struts.Person[ id=" + id + " ]";
}
Excaption
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(petname)]
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.myapp.struts.NewHibernateUtil.<clinit>(NewHibernateUtil.java:28)
at com.myapp.struts.Test.main(Test.java:16)
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(petname)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
aJava Result: 1
#CollectionOfElements
#JoinTable(name = "PET", joinColumns = { #JoinColumn(name = "person_id") })
#Column(name = "petname")
private Set<String> petname = new HashSet<String>();
Related
I've recently started working with JPA and Hibernate for a school project, and it basically stores continents, countries and cities in a database.
When trying to use the persist method on an entity, I get the error mentioned in the title.
Whichever threads I've visited tackle a lot more complex problems, and don't really help my case. I'm hoping to find some guidance by posting here.
This is the database creation script. It's a PostgreSQL database.
create table continents(
id integer primary key,
name varchar
);
create table countries(
id integer primary key,
name varchar,
code varchar,
continent_ID integer,
constraint fk_continents
foreign key (continent_ID)
references continents(id)
);
create table cities(
id integer primary key,
country_ID integer,
name varchar,
hasCapital boolean,
latitude float,
longitude float,
constraint fk_countries
foreign key (country_ID)
references countries(id)
);
Basically, the countries table uses the continents table's ID as a foreign key, and the cities table uses the countries table's ID again, as a foreign key.
The error I get is caused by me trying to persist a new continent entity. This is the code that gets executed:
public static void main(String[] args) {
EntityManagerFactory ef = Persistence.createEntityManagerFactory("default");
EntityManager em = ef.createEntityManager();
EntityTransaction transaction = em.getTransaction();
try{
transaction.begin();
ContinentsEntity continentEntity = new ContinentsEntity();
continentEntity.setId(1);
continentEntity.setName("Europe");
em.persist(continentEntity);
transaction.commit();
} finally {
if(transaction.isActive()){
transaction.rollback();
}
em.close();
ef.close();
}
}
All the entity classes are generated by Intellij, through the persistence tool.
Here are the classes.
ContinentsEntity:
package entity;
import javax.persistence.*;
#Entity
#Table(name = "continents", schema = "public", catalog = "postgres")
public class ContinentsEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id")
private int id;
#Basic
#Column(name = "name")
private String name;
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;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContinentsEntity that = (ContinentsEntity) o;
if (id != that.id) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
CountriesEntity:
package entity;
import javax.persistence.*;
#Entity
#Table(name = "countries", schema = "public", catalog = "postgres")
public class CountriesEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id")
private int id;
#Basic
#Column(name = "name")
private String name;
#Basic
#Column(name = "code")
private String code;
#Basic
#Column(name = "continent_id")
private Integer continentId;
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getContinentId() {
return continentId;
}
public void setContinentId(Integer continentId) {
this.continentId = continentId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CountriesEntity that = (CountriesEntity) o;
if (id != that.id) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (code != null ? !code.equals(that.code) : that.code != null) return false;
if (continentId != null ? !continentId.equals(that.continentId) : that.continentId != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + (continentId != null ? continentId.hashCode() : 0);
return result;
}
}
CitiesEntity:
package entity;
import javax.persistence.*;
#Entity
#Table(name = "cities", schema = "public", catalog = "postgres")
public class CitiesEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id")
private int id;
#Basic
#Column(name = "country_id")
private Integer countryId;
#Basic
#Column(name = "name")
private String name;
#Basic
#Column(name = "hascapital")
private Boolean hascapital;
#Basic
#Column(name = "latitude")
private Double latitude;
#Basic
#Column(name = "longitude")
private Double longitude;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getCountryId() {
return countryId;
}
public void setCountryId(Integer countryId) {
this.countryId = countryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getHascapital() {
return hascapital;
}
public void setHascapital(Boolean hascapital) {
this.hascapital = hascapital;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CitiesEntity that = (CitiesEntity) o;
if (id != that.id) return false;
if (countryId != null ? !countryId.equals(that.countryId) : that.countryId != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (hascapital != null ? !hascapital.equals(that.hascapital) : that.hascapital != null) return false;
if (latitude != null ? !latitude.equals(that.latitude) : that.latitude != null) return false;
if (longitude != null ? !longitude.equals(that.longitude) : that.longitude != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (countryId != null ? countryId.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (hascapital != null ? hascapital.hashCode() : 0);
result = 31 * result + (latitude != null ? latitude.hashCode() : 0);
result = 31 * result + (longitude != null ? longitude.hashCode() : 0);
return result;
}
}
It might be something with my DB design, or the way Intellij generated my entity classes, but I just can't figure it out.
EDIT: My DB design was the fault, as well as me trying to persist the id. I modified all pk's to be serial, as well as removing the line of code where I added the id, and that did the trick.
The problem is, that you're trying to persist an entity with id being set and Hibernate thinks it's an existing entity, but can't find it in it's Persistence Context. Try to persist the entity without the ID, it should be generated automatically.
I just had the same thing and removing the #GeneratedValue annotation from the id of an entity that is joined by another entity in a OneToMany relationship solved it.
I faced this problem. Then after removing (cascade = CascadeType.ALL) my problem solved.
I have two related entities, one a main table and a column in the main table has a reference table.
The error is:
Caused by : javax.el.ELException: /jsf/submit.xhtml #20,76 listener="#{BankLocationMB.saveLocation}": org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException:
Not-null property references a transient value - transient instance must be saved before current operation : bank.entity.BankLocation.bankFormat -> bank.entity.RefBankFormat;
nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation :
bank.entity.BankLocation.bankFormat -> bank.entity.RefBankFormat
#Entity
#Table(name = "BANK_LOCATION", schema = "OWNR")
public class BankLocation implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "BANK_LOCATION_ID")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BANK_LOCATION_ID_SEQ")
#SequenceGenerator(name = "BANK_LOCATION_ID_SEQ", sequenceName = "OWNR.BANK_LOCATION_ID_SEQ", allocationSize = 1)
private Long bankLocationId;
#Size(max = 32)
#Column(name = "BANK_NAME")
private String bankName;
#JoinColumn(name = "BANK_FORMAT_ID", referencedColumnName = "BANK_FORMAT_ID")
#ManyToOne(targetEntity=RefBankFormat.class, optional = false)
private RefBankFormat bankFormat;
public RefBankFormat getBankFormat() {
return bankFormat;
}
public void setBankFormat(RefBankFormat bankFormat) {
this.bankFormat = bankFormat;
}
#Override
public int hashCode() {
int hash = 0;
hash += (bankLocationId != null ? bankLocationId.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 BankLocation)) {
return false;
}
BankLocation other = (BankLocation) object;
if ((this.bankLocationId == null && other.bankLocationId != null) || (this.bankLocationId != null && !this.bankLocationId.equals(other.bankLocationId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "bank.entity.BankLocation[ bankLocationId=" + bankLocationId + " ]";
}
}
Reference Table Entity
#Entity
#Table(name = "REF_BANK_FORMAT", schema = "OWNR")
public class RefBankFormat implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "BANK_FORMAT_ID")
private Integer bankFormatId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "DISPLAY_NAME")
private String displayName;
#Size(max = 50)
#Column(name = "DESCRIPTION")
private String description;
public RefBankFormat() {
}
public RefBankFormat(Integer bankFormatId) {
this.bankFormatId = bankFormatId;
}
public RefBankFormat(Integer bankFormatId, String displayName) {
this.bankFormatId = bankFormatId;
this.displayName = displayName;
}
public Integer getbankFormatId() {
return bankFormatId;
}
public void setbankFormatId(Integer bankFormatId) {
this.bankFormatId = bankFormatId;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public int hashCode() {
int hash = 0;
hash += (bankFormatId != null ? bankFormatId.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 RefBankFormat)) {
return false;
}
RefBankFormat other = (RefBankFormat) object;
if ((this.bankFormatId == null && other.bankFormatId != null) || (this.bankFormatId != null && !this.bankFormatId.equals(other.bankFormatId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "bank.entity.RefBankFormat[ bankFormatId=" + bankFormatId + " ]";
}
}
Could anyone provide a fix where I'm going wrong?
#ManyToOne(targetEntity=RefBankFormat.class, optional = false)
private RefBankFormat bankFormat;
bankFormat is set mandatory(not null) so you first have to save this object in the database and then you are allowed to save BankLocation object.
OR
define a strategy for transitive persistence, a.k.a CascadeType.
This question already has answers here:
Foreign key constraint failure when trying to insert because of key change
(2 answers)
Closed 3 years ago.
I am trying to set up a system very similar to the one shown here:
https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/
The PostgreSQL schema is set up the same way with the content class shown below, mapping to the tag class in a table with a content_id and a tag_id which have foreign key constraints on their respective tables. The issue I am having is when attempting to persist a new content object I am checking if the tags of the object exist and if they do I am adding them using the addTag method and then persisting the object. Otherwise I create them and persist the object. The POST method for doing this is also shown below. The repository successfully finds the tags since they are already persisted but I get the following error when I attempt to then persist the content:
org.postgresql.util.PSQLException: ERROR: insert or update on table
"content_tag" violates foreign key constraint "tag_id_fkey"
Detail: Key (tag_id)=(11) is not present in table "tag".
I stepped through the code and when the tags are added to the content using the addTag method it shows that their ids match the tags that are already in the database so I don't understand why when I persist the content it is a different id. Does anyone know how I can prevent this from happening and have the persisting of content work?
#Entity(name = "Content")
#Table(name = "content")
#TypeDef( name= "StringJsonObject", typeClass = StringJsonUserType.class)
public class Content implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Type(type = "StringJsonObject")
#Column(name = "text")
private String text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#ManyToMany(cascade = {
CascadeType.MERGE
})
#JoinTable(name = "content_tag",
joinColumns = #JoinColumn(name = "tag_id"),
inverseJoinColumns = #JoinColumn(name="content_id")
)
private Set<Tag> tags = new HashSet<>();
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
public void addTag(Tag tag) {
tags.add(tag);
tag.getContents().add(this);
}
public void removeTag(Tag tag) {
tags.remove(tag);
tag.getContents().remove(this);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Content)) return false;
return id != null && id.equals(((Content) o).getId());
}
#Override
public int hashCode() {
return 31;
}
}
#Entity(name = "Tag")
#Table(name = "tag")
public class Tag implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "name")
private String name;
#ManyToMany(mappedBy = "tags")
private Set<Content> contents = new HashSet<>();
public Tag() {}
public Tag(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Content> getContents() {
return contents;
}
public void setContents(Set<Content> contents) {
this.contents = contents;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return Objects.equals(name, tag.name);
}
#Override
public int hashCode() {
return Objects.hash(name);
}
}
#PostMapping(value = "/content", consumes = { MediaType.APPLICATION_JSON_VALUE },
produces = { MediaType.APPLICATION_JSON_VALUE })
public ContentJSON createContent(#RequestBody(required = false) final String payload) {
if (StringUtils.isEmpty(payload)) {
throw new IllegalArgumentException(ServiceErrorCode.INVALID_REQUEST_BODY);
}
final ContentRequest request = convertPayloadToRequest(payload, ContentRequest.class);
final Content content = new Content();
content.setText(request.getContent().getText().toString());
for (final String tag : request.getContent().getTags()) {
final List<Tag> current = tagRepository.findByName(tag);
if (current.isEmpty()) {
final Tag newTag = new Tag(tag);
tagRepository.save(newTag);
content.addTag(newTag);
} else {
content.addTag(current.get(0));
}
}
final Content response = contentRepository.save(content);
Set<String> tagNames = new HashSet<>();
for (final Tag tag : content.getTags()) {
tagNames.add(tag.getName());
}
return new ContentJSON(response, tagNames);
}
The issue was the annotation below.
#JoinTable(name = "content_tag",
joinColumns = #JoinColumn(name = "content_id"),
inverseJoinColumns = #JoinColumn(name="tag_id")
)
the joinColumns and inverseJoinColumns were reversed
I am trying to create two entities which have many-to-many relation between them. First entity is Person with PID as primary key, second is Serie with SID as primary key. In database there is a table TJV_5_SERIE_2_PERSON, which represents many to many relationship between these entities.
tables in database
The problem is when I retrieve any entity, Collection annotated with #ManyToMany is always empty. So I assume I've messed up something in my code that explains why my many-to-many relation doesn't work.
I retrieve these two entities by generating (in Netbeans 9.0) 'Restful Web Services from Entity classes'. This way I can use these services to retrieve all attributes succesfully, except Collection with #ManyToMany annotation is always empty.
Any idea why it is not woking appreciated. It is first time trying this, so pardon me for any dumm mistakes.
Person class:
#Entity
#Table(name = "TJV_5_PERSON")
#XmlRootElement
public class Person implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PID")
private Integer id;
#Column(name = "PNAME")
private String name;
#ManyToMany()
#JoinTable(
name = "TJV_5_SERIE_2_PERSON",
joinColumns = #JoinColumn(name = "PID", referencedColumnName = "PID"),
inverseJoinColumns = #JoinColumn(name = "SID", referencedColumnName = "SID")
)
// always empty
private Collection<Serie> favourites = new ArrayList<Serie>();
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public Collection<Serie> getFavourites() {
return favourites;
}
public void setFavourites(Collection<Serie> favourites) {
this.favourites = favourites;
}
#Override
public int hashCode() {
int hash = 5;
hash = 31 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Person{" + "id=" + id + ", name=" + name + ", favourites=" + favourites + '}';
}
}
Serie class:
#Entity
#Table(name = "TJV_5_SERIE")
#XmlRootElement
public class Serie implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SID")
private Integer id;
#Column(name = "STITLE")
private String title;
// always empty
#ManyToMany(mappedBy = "favourites")
private Collection<Person> fans = new ArrayList<Person>();
public Serie() {
}
public Serie(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#XmlTransient
public Collection<Person> getFans() {
return fans;
}
public void setFans(Collection<Person> fans) {
this.fans = fans;
}
#Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Serie other = (Serie) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Serie{" + "id=" + id + ", title=" + title + ", fans=" + fans + '}';
}
}
I am not 100% sure, but you may not retrieving any results beacuse of #XMLTransiet annotation above the Serie.class method
#XmlTransient
public Collection<Person> getFans() {
return fans;
}
Try to look in documentation https://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlTransient.html or in connected posts Hide an entity variable from xml message - #XmlTransient not working
The other issue is cascading data between two corresponding #ManyToMany tables. It means that you have intersection and the data appears in this table automatically when you use some type of cascade but you need send a POST request. It means in your service class layer you can create a method responsible for creating Person and assign a Serie to this Person object which is a foreign key. The article about cascading is here :) https://vladmihalcea.com/a-beginners-guide-to-jpa-and-hibernate-cascade-types/
I am not getting how to write Hibernate criteria query to achieve the result similar to the result obtained by below SQL query. Please suggest me what are all steps need to be followed to achieve the result.
SELECT PRODUCT.PRODUCTNAME, ITEM.ITEMNAME
FROM PRODUCT_ITEM
JOIN PRODUCT
ON PRODUCT_ITEM.ID = PRODUCT.ID
JOIN ITEM
ON PRODUCT_ITEM.ID = ITEM.ID
Above is my Sql Query to fetch the product_name and item_name. It is working correctly.
I tried get the same result using HIBERNATE CRITERIA QUERY.
Criteria criteria = session.createCriteria(ProductItem.class,"pi");
criteria.createAlias("pi.pk.product", "pip");
criteria.createAlias("pi.pk.item", "pii");
criteria.setProjection(Projections.projectionList().add(Projections.property("pip.id")).add(Projections.property("pii.id")));
List<Object[]> list = criteria.list();
i am getting error saying
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2147)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2028)
at org.hibernate.loader.Loader.list(Loader.java:2023)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:95)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at checkComposite.main(checkComposite.java:38)
Caused by: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "pip1_"
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1668)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2144)
Here my ENTITYS are as below.
#Entity
#Table(name = "item")
public class Item {
private Integer id;
private String name;
private List<ProductItem> productItems = new LinkedList<ProductItem>();
public Item() {
}
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "item_id", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.item")
public List<ProductItem> getProductItems() {
return this.productItems;
}
public void setProductItems(List<ProductItem> productItems) {
this.productItems = productItems;
}
}
Product Entity
#Entity
#Table(name = "product")
public class Product {
private Integer id;
private String name;
private List<ProductItem> productItems = new LinkedList<ProductItem>();
public Product() {
}
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "product_id", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.product")
public List<ProductItem> getProductItems() {
return this.productItems;
}
public void setProductItems(List<ProductItem> productItems) {
this.productItems = productItems;
}
}
PRODUCT_ITEM entity.
#Entity
#Table(name = "product_item")
#AssociationOverrides({
#AssociationOverride(name = "pk.item", joinColumns = #JoinColumn(name = "item_id")),
#AssociationOverride(name = "pk.product", joinColumns = #JoinColumn(name = "product_id"))
})
public class ProductItem {
private ProductItemPk pk = new ProductItemPk();
#EmbeddedId
private ProductItemPk getPk() {
return pk;
}
private void setPk(ProductItemPk pk) {
this.pk = pk;
}
#Transient
public Item getItem() {
return getPk().getItem();
}
public void setItem(Item item) {
getPk().setItem(item);
}
#Transient
public Product getProduct() {
return getPk().getProduct();
}
public void setProduct(Product product) {
getPk().setProduct(product);
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductItem that = (ProductItem) o;
if (getPk() != null ? !getPk().equals(that.getPk()) : that.getPk() != null) return false;
return true;
}
public int hashCode() {
return (getPk() != null ? getPk().hashCode() : 0);
}
}
Embedable Class is as below.
#Embeddable
public class ProductItemPk implements Serializable {
private Item item;
private Product product;
#ManyToOne
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
#ManyToOne
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductItemPk that = (ProductItemPk) o;
if (item != null ? !item.equals(that.item) : that.item != null) return false;
if (product != null ? !product.equals(that.product) : that.product != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (item != null ? item.hashCode() : 0);
result = 31 * result + (product != null ? product.hashCode() : 0);
return result;
}
}
Try changing the query to:
Criteria criteria = session.createCriteria(ProductItem.class,"pi");
criteria.createAlias("pi.pk", "pipk");
criteria.createAlias("pipk.product", "pip");
criteria.createAlias("pipk.item", "pii");
criteria.setProjection(Projections.projectionList().add(Projections.property("pip.id")).add(Projections.property("pii.id")));
List<Object[]> list = criteria.list();