Why does JPA execute a delete statement for the wrong table? - java

I am programming a simple forum using Java EE. The forum has thread and post entities. All the basic CRUD operations for the posts and threads are working.
Only when I try to delete a thread, JPA is making a wrong SQL statement and I don't understand why. I am using the Oracle 11g database.
Wrong statement from JPA:
delete from THREAD_POST where Thread_id=?
How it should be:
delete from FORUM.THREAD where Thread.id=?
It looks like JPA is trying to use a join table between thread and post.
Hope fully someone can point me to the right direction to fix this error.
The code I execute to delete a thread:
#PersistenceContext
private EntityManager em;
em.remove(em.find(Thread.class, id));
My Thread entity:
package ee.forum.ejb.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Entity
#Table(schema = "FORUM", name = "THREAD")
public class Thread implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(
name = "THREAD_ID_GENERATOR",
sequenceName = "SEQ_THREAD",
schema = "FORUM",
allocationSize = 1,
initialValue = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "THREAD_ID_GENERATOR"
)
private Long id;
#NotNull
#Size(max = 20)
private String name;
#NotNull
#ManyToOne
private Board board;
#NotNull
#ManyToOne
private User author;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#OneToMany
private List<Post> posts;
public Thread() {}
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 Board getBoard() {
return board;
}
public void setBoard(Board board) {
this.board = board;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public boolean addPost(Post post) {
if (posts == null) {
posts = new ArrayList<>();
}
post.setThread(this);
return this.posts.add(post);
}
}
And my Post entity:
package ee.forum.ejb.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(schema = "FORUM", name = "POST")
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(
name = "POST_ID_GENERATOR",
sequenceName = "SEQ_POST",
schema = "FORUM",
allocationSize = 1,
initialValue = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "POST_ID_GENERATOR"
)
private Long id;
#NotNull
#Size(min = 5, max = 1000)
private String text;
#NotNull
#ManyToOne
private Thread thread;
#NotNull
#ManyToOne
private User author;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
private Date created;
public Post() {}
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;
}
public Thread getThread() {
return thread;
}
public void setThread(Thread thread) {
this.thread = thread;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
}

Related

Can't persist object to DB

I am trying to persist an object to the DB, where the id of the object is auto generated. The issue is that for some reason the ID remains null(I also tried hardcoding a id in the constructor, but it is still seen as null). I tested inserting an object to the DB running a sql query and I can see the entry in the table.The model class is:`
package com.dealFinder.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
#ToString
#Entity
#Table(name = "deals")
public class DealModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotBlank(message = "Title is mandatory")
private String title;
#NotBlank(message = "Url is mandatory")
private String url;
private float price;
public DealModel(String title, String url, float price){
// this.id = 1;
this.title=title;
this.url = url;
this.price= price;
}
public DealModel(){}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "url", nullable = false)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Column(name = "price", nullable = false)
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
I create the object with `
model = new DealModel(title, productUrl, price);
where title, productUrl and price are not null, and I persist it to the DB with
dealsRepository.save(dealModel);
where the dealRepository class is
#Repository
public interface DealsRepository extends JpaRepository<DealModel, Integer> {
}
` Not sure what wrong change I made recently, as it was working fine previously.
I am trying to persist the delModel object to the DB. Running a manual query to insert a dealModel entry to the table works fine

Java-Oracle - Unable to create specific table

I always get error java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier and java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist when creating table. This is some of my tables
package com.domibowo.salestracking.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(schema = "SALES_TRACKING", name="CUSTOMER")
public class Customer {
#Id
#GeneratedValue(generator = "seq", strategy= GenerationType.SEQUENCE)
#SequenceGenerator(name="seq", sequenceName = "SEQ1")
private Long id;
#Column(name="citizen_id")
private Long citizenId;
#Column(name = "full_name")
private String fullName;
#Column(name = "address")
private String address;
#Column(name="city")
private String city;
#ManyToOne
#JoinColumn(name="region_id")
#JsonIgnoreProperties(value = {"salesList","customerList"})
private Region region;
#Transient
private Long regionId;
#OneToMany(mappedBy = "customer")
private List<Details> details;
public Customer() {
}
public Customer(Long id, Long citizenId, String fullName, String address, String city, Region region, Long regionId, List<Details> details) {
this.id = id;
this.citizenId = citizenId;
this.fullName = fullName;
this.address = address;
this.city = city;
this.region = region;
this.regionId = regionId;
this.details = details;
}
public Long getId() {
return id;
}
public Long getCitizenId() {
return citizenId;
}
public void setCitizenId(Long citizen_id) {
this.citizenId = citizen_id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String full_name) {
this.fullName = full_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
public Long getRegionId() {
return regionId;
}
public void setRegionId(Long regionId) {
this.regionId = regionId;
}
}
The product table and the rest are able to create without any problem.
But this,
package com.domibowo.salestracking.models;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(schema = "SALES_TRACKING",name="HISTORY")
public class History {
#Id
#GeneratedValue(generator = "seq", strategy= GenerationType.SEQUENCE)
#SequenceGenerator(name="seq", sequenceName = "SEQ1")
private Long id;
#ManyToOne
#JoinColumn(name = "sales_id")
#JsonIgnoreProperties(value = {"region"})
private Sales sales;
#OneToOne
#JoinColumn(name = "details_id")
#JsonIgnoreProperties(value = {"history"})
private Details details;
#Column(name = "date")
#JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate date;
#Column(name = "total")
private Double total;
#Transient
private Long detailsId;
#Transient
private Long salesId;
public History() {
}
public History(Long id, Sales sales, Long salesId, Details details, LocalDate date, Double total, Long detailsId) {
this.id = id;
this.sales = sales;
this.details = details;
this.date = date;
this.total = total;
this.detailsId = detailsId;
this.salesId = salesId;
}
public Long getDetailsId() {
return detailsId;
}
public void setDetailsId(Long detailsId) {
this.detailsId = detailsId;
}
public Long getId() {
return id;
}
public Sales getSales() {
return sales;
}
public void setSales(Sales sales) {
this.sales = sales;
}
public Details getDetails() {
return details;
}
public void setDetails(Details details) {
this.details = details;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Long getSalesId() {
return salesId;
}
public void setSalesId(Long salesId) {
this.salesId = salesId;
}
}
I always get ORA-00904 and ORA-00942 errors when creating History table even if the generator id used is the same as others. Any help much appreciated!!
Even while using Hibernate JPA you must not forget you use the Oracle database and you must avoid using reserved words as columns names.
So please review all columns names, particularly this one
#Column(name = "date")
The error ORA-00904 invalid identifier point in this direction. DATE is a reserved word and can't be used as column name.
The second one (ORA-00942 table or view does not exist) is a followup message caused by the fact that the table can't be created.

Deserialize Exception in spring hibernate with OneToOne Mapping

I am using Spring boot 2.1.2 with hibernate , and i have simple two model classes like user and user account, and these 2 models are connected with oneToOne mapping. When we call user, i need to get user account also. I just mapped user account model to user model with oneToOne mapping. But when i call user am facing one Deserialize Exception.
User model
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "tbl_user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_account_id")
UserAccount userAccount;
#Column(name = "first_name",nullable = false)
private String firstName;
#Column(name = "active",nullable = false)
private Integer active;
#Column(name = "created_date",nullable = false)
private Calendar createdDate;
#Column(name = "created_by",nullable = false)
private Integer created_by;
#Column(name = "updated_date")
private Calendar updatedDate;
#Column(name = "updated_by")
private Integer updated_by;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, UserAccount userAccount, String firstName, Integer active, Calendar createdDate,
Integer created_by, Calendar updatedDate, Integer updated_by) {
super();
this.id = id;
this.userAccount = userAccount;
this.firstName = firstName;
this.active = active;
this.createdDate = createdDate;
this.created_by = created_by;
this.updatedDate = updatedDate;
this.updated_by = updated_by;
}
public Integer getId() {
return id;
}
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Integer getCreated_by() {
return created_by;
}
public void setCreated_by(Integer created_by) {
this.created_by = created_by;
}
public Calendar getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Calendar updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getUpdated_by() {
return updated_by;
}
public void setUpdated_by(Integer updated_by) {
this.updated_by = updated_by;
}
}
UserAccount Model
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "tbl_user_account")
public class UserAccount implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "usere_name",nullable = false)
UserAccount usereName;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "active",nullable = false)
private Integer active;
#Column(name = "created_date",nullable = false)
private Calendar createdDate;
#Column(name = "created_by",nullable = false)
private Integer created_by;
#Column(name = "updated_date")
private Calendar updatedDate;
#Column(name = "updated_by")
private Integer updated_by;
public UserAccount(Integer id, UserAccount usereName, String password,Integer active,
Calendar createdDate, Integer created_by, Calendar updatedDate, Integer updated_by) {
super();
this.id = id;
this.usereName = usereName;
this.password = password;
this.active = active;
this.createdDate = createdDate;
this.created_by = created_by;
this.updatedDate = updatedDate;
this.updated_by = updated_by;
}
public UserAccount() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UserAccount getUsereName() {
return usereName;
}
public void setUsereName(UserAccount usereName) {
this.usereName = usereName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Integer getCreated_by() {
return created_by;
}
public void setCreated_by(Integer created_by) {
this.created_by = created_by;
}
public Calendar getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Calendar updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getUpdated_by() {
return updated_by;
}
public void setUpdated_by(Integer updated_by) {
this.updated_by = updated_by;
}
}
Property file
# Application running port
server.port=8000
# Application running port
server.servlet.contextPath=/app
# Log files
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
#DB config
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
The problem seems to be in UserAccount class, where you defined usereName field as UserAccount type.
I think it should be a String.

Table Column Mapping error on Hibernate with spring boot

I have two table on MySql database. Item, ItemGroup which are related by Item.groupid -> ItemGroup.id I am also using hibernate-entitymanager and spring boot. Here are my entity classes for Item and ItemGroup.
Item.java
package com.thiha.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String createdDate;
private String modifiedDate;
private String itemCode;
private String description;
private int groupId;
private double quantity;
private double price;
private int recordStatus;
private ItemGroup itemGroup;
#ManyToOne
#JoinColumn(name = "groupid")
public ItemGroup getItemGroup() {
return itemGroup;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(int recordStatus) {
this.recordStatus = recordStatus;
}
}
ItemGroup.java
package com.thiha.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class ItemGroup {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String createdDate;
private String modifiedDate;
private String groupCode;
private String groupName;
private int recordStatus;
private List<Item> items;
#OneToMany(mappedBy = "itemGroup", cascade = CascadeType.ALL)
public List<Item> getItems(){
return items;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getGroupCode() {
return groupCode;
}
public void setGroupCode(String groupCode) {
this.groupCode = groupCode;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public int getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(int recordStatus) {
this.recordStatus = recordStatus;
}
}
I also create a foreign keys in Item table reference to ItemGroup table with foreign key groupid. But when I run the code with mvn spring-boot:run, I got some exception as following:
org.hibernate.MappingException: Could not determine type for: java.util.List, at table: item_group, for columns: [org.hibernate.mapping.Column(items)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398)
at org.hibernate.mapping.Property.isValid(Property.java:225)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
If I remove the relationships in both class, it is working properly but I cannot make INNER JOIN query. Please help me to solve this problem
You can't mix annotation conventions in Hibernate. Please try to move your #Id and #GeneratedValue annotations to getter, or #OneToMany and #ManyToOne to fields.
It says
Could not determine type for: java.util.List, at table: item_group, for columns: [org.hibernate.mapping.Column(items)]'
Because your mappedBy is incorrect.
When you put annotation on getter getCategory(), hibernate understands that it's category.
#ManyToOne
#JoinColumn(name = "groupid")
public ItemGroup getCategory() {
return itemGroup;
}
So, please use appropriate name in your class ItemGroup
#OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
public List<Item> getItems(){
return items;
}
dont worry there is do only one thing remove your annotation of #Id and #generatorValue annotation above on the id and put on the getter method of your id
the problem will be fix.....!

org.hibernate.QueryException: duplicate association path for #ManyToOne Criteria

I have two classes which has a relationship between them. These are
com.edfx.adb.persist.Activity:
package com.edfx.adb.persist.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.NaturalId;
#javax.persistence.Entity
#Table(name = "ACTIVITY")
public class Activity extends Entity {
#Transient
private static final long serialVersionUID = 4741665931936809028L;
private String activityId;
private String activityName;
private String activityDescription;
private Customer customer;
private ActivityType activityType;
private boolean active;
private Double mandays;
private Double price;
private String manager;
private List<Participation> participations;
public Activity() {
super();
}
#NaturalId
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
#Lob
#Column(name = "ACTIVITY_NAME", nullable = false)
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
#Lob
#Column(name = "ACTIVITY_DESCRIPTION", nullable = false)
public String getActivityDescription() {
return activityDescription;
}
public void setActivityDescription(String activityDescription) {
this.activityDescription = activityDescription;
}
#ManyToOne
#JoinColumn(name = "CUSTOMER_ID", nullable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#ManyToOne
#JoinColumn(name = "ACTIVITY_TYPE_ID", nullable = false)
public ActivityType getActivityType() {
return activityType;
}
public void setActivityType(ActivityType activityType) {
this.activityType = activityType;
}
#Column(name = "ACTIVE", nullable = false)
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "MANDAYS")
public Double getMandays() {
return mandays;
}
public void setMandays(Double mandays) {
this.mandays = mandays;
}
#Column(name = "PRICE")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Column(name = "CUSTOMER_SIDE_MANAGER")
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
#OneToMany(mappedBy = "activity", fetch = FetchType.LAZY)
#Cascade(CascadeType.SAVE_UPDATE)
public List<Participation> getParticipations() {
return participations;
}
public void setParticipations(List<Participation> participations) {
this.participations = participations;
}
}
com.edfx.adb.persist.ActivityType:
package com.edfx.adb.persist.entity;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Transient;
#javax.persistence.Entity
#Table(name = "ACTIVITY_TYPE")
public class ActivityType extends Entity {
#Transient
private static final long serialVersionUID = 2322745769010162801L;
private String parent;
private String name;
private String activityId;
public ActivityType() {
}
#Column(name = "PARENT", nullable = false)
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
}
Both of them extends com.edfx.adb.persist.entity.Entity:
package com.edfx.adb.persist.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.hibernate.proxy.HibernateProxyHelper;
#MappedSuperclass
public class Entity implements Serializable {
#Transient
private static final long serialVersionUID = 7470288121057059283L;
private Long id;
private Date createTimestamp;
private Date lastUpdateTimestamp;
private Long version;
public Entity() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", updatable = false, nullable = false, unique = true)
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATE_TIMESTAMP")
public Date getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Date createTimestamp) {
this.createTimestamp = createTimestamp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_UPDATE_TIMESTAMP")
public Date getLastUpdateTimestamp() {
return lastUpdateTimestamp;
}
public void setLastUpdateTimestamp(Date lastUpdateTimestamp) {
this.lastUpdateTimestamp = lastUpdateTimestamp;
}
#Version
#Column(name = "VERSION")
public Long getVersion() {
return version;
}
#SuppressWarnings("unused")
private void setVersion(Long version) {
this.version = version;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
return prime * result + ((getId() == null) ? super.hashCode() : getId().hashCode());
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(HibernateProxyHelper.getClassWithoutInitializingProxy(obj))) {
return false;
}
final Entity other = (Entity) obj;
if (getId() != other.getId()) {
if (getId() == null) {
return false;
}
if (!getId().equals(other.getId())) {
return false;
}
}
return true;
}
}
Now I am using Primefaces datatable to show a List<Activity> in which I have filtering on the field name of ActivityType. ActivityType is associated with Activity by #ManyToOne relationship.
For filtering the List<Activity> I am using:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType").add(Restrictions.like("name", value.toString(), MatchMode.START));
I am getting:
null: org.hibernate.QueryException: duplicate association path: activityType
at org.hibernate.loader.criteria.CriteriaQueryTranslator.createAssociationPathCriteriaMap(CriteriaQueryTranslator.java:172) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaQueryTranslator.<init>(CriteriaQueryTranslator.java:111) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:84) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1602) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at com.edfx.adb.dao.ActivityDao.loadActivities(ActivityDao.java:54) [classes:]
at com.edfx.adb.service.ActivityService.loadActivities(ActivityService.java:101) [classes:]
This error is not showing always and never after the first load. After filtering the table for 5-6 time, I am having this error.
I am worried that if the mapping and the criteria is right or not. Any suggestion would be very helpful.
I think you need to provide an alias, so you should change your code this way:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType", "at")
.add(
Restrictions.like("at.name", value.toString(), MatchMode.START));

Categories