Spring JPA repository query can't find ID property - spring

I need a spring repository method that lets me get a list of Scene entities using a list of id's. When I try to refer to the Scene Id I get an error, saying it can't find the property called IdScene. I am using a custom query to do this. Is there something wrong with my query?
My Entity is
public class Scene implements Serializable
{
private long id_scene;
private Media media;
private int sceneNumber;
private int version;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id_scene")
public long getIdScene() {
return id_scene;
}
public void setIdScene(long id_scene) {
this.id_scene = id_scene;
}
#ManyToOne
#JoinColumn(name = "id_media")
public Media getMedia() {
return this.media;
}
public void setMedia(Media media) {
this.media = media;
}
private List<Thumbnail> thumbnails = new ArrayList<Thumbnail>();
#OneToMany(mappedBy = "scene", cascade=CascadeType.ALL,
orphanRemoval=true)
#LazyCollection(LazyCollectionOption.FALSE)
public List<Thumbnail> getThumbnails() {
return this.thumbnails;
}
public void setThumbnails(List<Thumbnail> thumbnails) {
this.thumbnails = thumbnails;
}
public void addThumbnail(Thumbnail thumbnail) {
thumbnail.setScene(this);
this.thumbnails.add(thumbnail);
}
private Property property;
#OneToOne(mappedBy="scene", cascade=CascadeType.ALL,
orphanRemoval=true)
#LazyCollection(LazyCollectionOption.FALSE)
public Property getProperty() {
return property;
}
public void setProperty(Property property) {
this.property = property;
}
public void addProperty(Property property) {
property.setScene(this);
this.property = property;
}
#Column(name = "sceneNumber")
public int getSceneNumber() {
return sceneNumber;
}
public void setSceneNumber(int sceneNumber) {
this.sceneNumber = sceneNumber;
}
#Column(name = "version")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
My repository:
public interface SceneRepository extends JpaRepository<Scene, Long> {
public final static String FIND_BY_ID_LIST = "SELECT s"
+ " FROM Scene s WHERE s.IdScene IN (:id)";
#Query(FIND_BY_ID_LIST)
public List<Scene> findByIdScene(#Param("id") List<Long> id);//, Pageable page);
}

try:
"SELECT s FROM Scene s WHERE s.idScene IN (:id)"
note lower case 'i' in 'idScene'"
This is because of the Java Bean naming convention, a property defined as:
public String getWibble() { return wibble; }
public void setWibble(String value) { wibble = value; }
defines wibble and not Wibble

Related

Spring JPA hibernate how to persist children (remove, add, or update) from #OneToMany parent column?

I'm trying to solve this problem since a while and I haven't achieved a 100% solution.
First of all I have to describe my problem. I'm developping a restaurant application, and amoung the Entities, I have the Entity Ingredient and as you know Ingredient can consist of other Ingredient with a specific quantity. So I created an Entity SubIngredient with an Embedded Id.
And to persist subIngredients list I tried a combinations of Cascade and orphanRemoval, each combination worked for some operation but not for the others.
I started by using CascadeType.ALL and the new subIngredient persisted successfuly from the #OneToMany propertiy, But if I try to remove an subIngredient from the subIngredients list and save this error appear.
java.lang.StackOverflowError: null
at com.mysql.cj.NativeSession.execSQL(NativeSession.java:1109) ~[mysql-connector-java-8.0.23.jar:8.0.23]......
I loked in the net for a solution and I find the I have to use orphanremoval = true I tried it but it didn't work until I changed cascade from CascadeType.ALL to CascadeType.PERSIST. But this one make the persistance of new SubIngredient this error aprear
Caused by: javax.persistence.EntityNotFoundException: Unable to find com.example.Resto.domain.SubIngredient with id com.example.Resto.domain.SubIngredientKey#51b11186........
These are my Enities:
#Entity
public class Ingredient {
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY)
#Column(name="ID")
private long id;
#NotNull
#Column(unique=true)
private String name;
private String photoContentType;
#Lob
private byte[] photo;
#JsonIgnoreProperties({"photoContentType","photo"})
#ManyToOne
private IngredientType ingredientType;
#OneToMany(mappedBy = "embId.ingredientId", fetch = FetchType.EAGER,
cascade = CascadeType.ALL /*or orphanRemoval = true, cascade = CascadeType.PERSIST*/ )
private Set<SubIngredient> subIngredients = new HashSet<SubIngredient>();
getters and setters.....
And
#Entity
#AssociationOverrides({
#AssociationOverride(name = "embId.ingredientId",
joinColumns = #JoinColumn(name = "ING_ID")),
#AssociationOverride(name = "embId.subIngredientId",
joinColumns = #JoinColumn(name = "SUB_ING_ID")) })
public class SubIngredient {
#EmbeddedId
private SubIngredientKey embId = new SubIngredientKey();
private double quantity;
getters and setters....
And
#Embeddable
public class SubIngredientKey implements Serializable{
#ManyToOne(cascade = CascadeType.ALL)
private Ingredient ingredientId;
#ManyToOne(cascade = CascadeType.ALL)
private Ingredient subIngredientId;
getters and setters...
The stackoverflow happen because you use a Set<> with Hibernate. When Hibernate retrieves the entities from your DB, it will fill up the Set<> with each entities. In order to that, hashode/equals will be used to determine wether or not the entitie is already present in the Set<>. By default, when you call the hashcode of Ingredient, this happen:
hashcode Ingredient -> hashcode SubIngredient -> hashcode Ingredient
which will result in an infinite call of hashcode method. That's why you have a stackoverflow error.
The same thing will happen with equals/toString.
So to avoid such an issue, it's best to override hashcode, equals and toString.
I have solved the problem by making some changes to may Entities and override equals/hashcode methods thanks Pilpo.
#Embeddable
public class SubIngredientKey implements Serializable{
private Long ingredientId;
private Long subIngredientId;
/**
* #return the ingredientId
*/
#Override
public int hashCode() {
return Objects.hash(ingredientId, subIngredientId);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof SubIngredientKey)) {
return false;
}
SubIngredientKey other = (SubIngredientKey) obj;
return Objects.equals(ingredientId, other.ingredientId)
&& Objects.equals(subIngredientId, other.subIngredientId);
}
}
#Entity
public class SubIngredient {
#EmbeddedId
private SubIngredientKey embId = new SubIngredientKey();
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("ingredientId")
private Ingredient ingredient;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("subIngredientId")
private Ingredient subIngredient;
private double quantity;
#JsonIgnore
public SubIngredientKey getId() {
return embId;
}
public void setId(SubIngredientKey id) {
this.embId = id;
}
#JsonIgnoreProperties({"subIngredients","photo","photoContentType","ingredientType"})
public Ingredient getIngredient() {
return ingredient;
}
public void setIngredient(Ingredient ingredient) {
this.ingredient = ingredient;
}
#JsonIgnoreProperties({"subIngredients","photo","photoContentType","ingredientType"})
public Ingredient getSubIngredient() {
return subIngredient;
}
public void setSubIngredient(Ingredient subIngredient) {
this.subIngredient = subIngredient;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return "subIngredient= " + getSubIngredient().getName() + " , quantity= " + getQuantity();
}
#Override
public int hashCode() {
return Objects.hash(ingredient,subIngredient);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof SubIngredient)) {
return false;
}
SubIngredient other = (SubIngredient) obj;
return Objects.equals(ingredient, other.ingredient) && Objects.equals(subIngredient, other.subIngredient);
}
}
#Entity
public class Ingredient {
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY)
#Column(name="ID")
private long id;
#NotNull
#Column(unique=true)
private String name;
private String photoContentType;
#Lob
private byte[] photo;
#JsonIgnoreProperties({"photoContentType","photo"})
#ManyToOne
private IngredientType ingredientType;
#OneToMany(mappedBy = "embId.ingredientId", fetch = FetchType.EAGER, cascade =
CascadeType.ALL, orphanRemoval = true)
private Set<SubIngredient> subIngredients = new HashSet<SubIngredient>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPhotoContentType() {
return photoContentType;
}
public void setPhotoContentType(String photoContentType) {
this.photoContentType = photoContentType;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public IngredientType getIngredientType() {
return this.ingredientType;
}
public void setIngredientType(IngredientType ingredientType) {
this.ingredientType = ingredientType;
}
public Set<SubIngredient> getSubIngredients() {
return subIngredients;
}
public void setSubIngredients(Set<SubIngredient> subIngredients) {
this.subIngredients = subIngredients;
}
public void addSubIngredient(SubIngredient subIngredient) {
this.subIngredients.add(subIngredient);
}
#Override
public String toString() {
String subIngsText = "";
for(var subIngredient:this.subIngredients) {
subIngsText = subIngsText + ", " + subIngredient.toString();
}
return "{id= "+id+",name=" + name +", ingredients="+subIngsText+"}";
}
#Override
public int hashCode() {
return Objects.hash(name);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Ingredient)) {
return false;
}
Ingredient other = (Ingredient) obj;
return Objects.equals(name, other.name);
}
}

Many to One Relationship with #IdClass

Using Spring Data JPA & Hibernate, I am saving an object Company, that has 0 to Many AccountMapping. The AccountMappings Primary Key is a composite of a String accountNumber and the Company Primary Key. When I save a new company the COMP_NUM from the Company Object is not set into the AccountMapping object. When I use long companyNumber it is zero, and Long it is NUM. Hibernate is executing the insert statement first, but how to get it to set the primary key from company into child object ?
#Entity
#Table(name = "COMPANY")
public class Company implements Serializable {
#Id
#Column(name = "COMP_NUM")
#SequenceGenerator(name = "comp_num_seq", sequenceName = "comp_num_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "comp_num_seq")
private long number;
#OneToMany(mappedBy = "companyNumber", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<AccountMapping> accountMappings;
public Company() {
super();
}
public long getNumber() {
return this.number;
}
public void setNumber(long id) {
this.number = id;
}
public List<AccountMapping> getAccountMappings() {
return accountMappings;
}
public void setAccountMappings(List<AccountMapping> accountMappings) {
this.accountMappings = accountMappings;
}
}
#Entity
#IdClass(value = AccountMappingPK.class)
#Table(name = "ACCOUNT_MAPPING")
public class AccountMapping implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ACCNT_NUM")
private String accountNumber;
#Id
#Column(name = "COMP_NUM")
private Long companyNumber;
#Column(name = "IS_PRIMARY")
private Boolean isPrimary;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public Long getCompanyNumber() {
return companyNumber;
}
public void setCompanyNumber(Long companyNumber) {
this.companyNumber = companyNumber;
}
public Boolean getIsPrimary() {
return isPrimary;
}
public void setIsPrimary(Boolean isPrimary) {
this.isPrimary = isPrimary;
}
}
public class AccountMapping implements Serializable {
#Column(name = "EA_ACCNT_NUM", nullable = false)
private String accountNumber;
#Column(name = "COMP_NUM", nullable = false)
private Long companyNumber;
public AccountMapping() {
// default constructor
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNum(String accountNumber) {
this.accountNumber = accountNumber;
}
public Long getCompanyNumber() {
return companyNumber;
}
public void setCompanyNumber(Long companyNumber) {
this.companyNumber = companyNumber;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof AccountMappingPK) {
AccountMappingPK accntPk = (AccountMappingPK) obj;
if (!(accountNumber.equals(accntPk.getAccountNumber()))) {
return false;
}
if (!(accntPk.getCompanyNumber() == (companyNumber))) {
return false;
}
return true;
}
return false;
}
#Override
public int hashCode() {
int hash = (accountNumber == null ? 1 : accountNumber.hashCode());
return (int) (hash * companyNumber);
}
}
#Entity
#IdClass(value = AccountMappingPK.class)
#Table(name = "ACCOUNT_MAPPING")
public class AccountMapping implements Serializable {
#Id
#Column(name = "ACCNT_NUM")
private String accountNumber;
#Id
#ManyToOne
#JoinColumn(name = "COMP_NUM")
private Company company;
...
}
// No annotations in this class
public class AccountMappingPK implements Serializable {
private String accountNumber;
private Company company;
...
// All the getter/setter, constructors, and so on ...
}
The Hibernate ORM documentation has more details about mapping with #IdClass: See Example 134. IdClass with #ManyToOne

Problem with proxy when using #IdClass in Hibernate

For legacy reasons I have composite keys in my database, I use #IdClass to map them (before I used #Embeddedid but it had it's own bugs). However I have problem whenever I'm trying to save composite key entity that contains proxy as id field.
I made very simple example to isolate this problem (example uses Spring Data, but I think its irrelevant).
p.s. I know that calling .save is not necessary, but it should not cause exception.
#Entity
public class Image {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String fileName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String 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;
}
}
#Entity
#IdClass(ProductImage.ProductImageId.class)
public class ProductImage {
public static class ProductImageId implements Serializable {
private static final long serialVersionUID = 8542391285589067304L;
private Long product;
private Long image;
public ProductImageId() {
}
public Long getProduct() {
return product;
}
public void setProduct(Long product) {
this.product = product;
}
public Long getImage() {
return image;
}
public void setImage(Long image) {
this.image = image;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductImageId that = (ProductImageId) o;
return Objects.equals(product, that.product) &&
Objects.equals(image, that.image);
}
#Override
public int hashCode() {
return Objects.hash(product, image);
}
}
#ManyToOne(fetch = FetchType.LAZY)
#Id
private Product product;
#ManyToOne(fetch = FetchType.LAZY)
#Id
private Image image;
private Integer number;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
List<ProductImage> productImages = productImageRepository.findAll();
productImages.get(0).setNumber(456);
productImageRepository.save(productImages.get(0));
Caused by: java.lang.IllegalArgumentException: Cannot convert value of type 'com.example.springbootnewplayground.Product$HibernateProxy$AJ38NiN6' to required type 'java.lang.Long' for property 'product': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'com.example.springbootnewplayground.Product$HibernateProxy$AJ38NiN6'
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:258) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
... 69 common frames omitted

Stop hibernate from firing update query on #ManyToOne entities

I have two entities ProductCartItem and Product. A product in my scenario is more of a master record that is never gonna change. Below is the mapping.
#Entity
#DiscriminatorValue(value = "PRODUCT")
public class ProductCartItem extends CartItem {
#ManyToOne(optional = false)
#JoinColumn(name = "product_id", referencedColumnName = "id")
private Product product;
#OneToMany(cascade = CascadeType.REMOVE, mappedBy = "parentProductCartItem",orphanRemoval = true)
#JsonManagedReference
Set<AccessoryCartItem> associatedAccessories = new HashSet<>();
#Column(name="property")
#Type(type = "ProductItemPropertyUserType")
private ProductItemProperty productItemProperty;
#OneToOne
#JoinColumn(name="project_id",referencedColumnName = "id")
private Project project;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Set<AccessoryCartItem> getAssociatedAccessories() {
return associatedAccessories;
}
public void setAssociatedAccessories(Set<AccessoryCartItem> associatedAccessories) {
this.associatedAccessories = associatedAccessories;
}
public void addAccessory(AccessoryCartItem accessoryCartItem) {
this.getAssociatedAccessories().add(accessoryCartItem);
}
public void removeAccessory(AccessoryCartItem accessoryCartItem) {
this.getAssociatedAccessories().remove(accessoryCartItem);
}
public ProductItemProperty getProductItemProperty() {
return productItemProperty;
}
public void setProductItemProperty(ProductItemProperty productItemProperty) {
this.productItemProperty = productItemProperty;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
And here is the Product entity.
#Entity
public class Product extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "subtitle")
private String subtitle;
#Column(name = "description")
private String description;
#Column(name = "type_name")
private String typeName;
#Column(name = "price")
private Float price;
#Column(name = "image_list")
#Type(type = "MyImageListUserType")
private MyImageList imageList;
#Column(name = "pricing_property")
#Type(type = "PricingProperty")
private Map<String,SizePriceDTO> pricingProperty;
#JoinColumn(name = "product_type")
#ManyToOne
private ProductType productType;
private String orientation;
private Short groupId;
#Column(name = "display_order")
private Short displayOrder;
#Column(name = "base_quantity")
private int baseQuantity;
#Transient
private List<AccessoryDTO> configuredAccessoryDTOList;
public Product(){
}
public int getBaseQuantity() {
return baseQuantity;
}
public void setBaseQuantity(int baseQuantity) {
this.baseQuantity = baseQuantity;
}
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;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public MyImageList getImageList() {
return imageList;
}
public void setImageList(MyImageList imageList) {
this.imageList = imageList;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public String getOrientation() {
return orientation;
}
public void setOrientation(String orientation) {
this.orientation = orientation;
}
public Short getGroupId() {
return groupId;
}
public void setGroupId(Short groupId) {
this.groupId = groupId;
}
public Short getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Short displayOrder) {
this.displayOrder = displayOrder;
}
public List<AccessoryDTO> getConfiguredAccessoryDTOList() {
return configuredAccessoryDTOList;
}
public void setConfiguredAccessoryDTOList(List<AccessoryDTO> configuredAccessoryDTOList) {
this.configuredAccessoryDTOList = configuredAccessoryDTOList;
}
public Map<String, SizePriceDTO> getPricingProperty() {
return pricingProperty;
}
public void setPricingProperty(Map<String,SizePriceDTO> pricingProperty) {
this.pricingProperty = pricingProperty;
}
}
Now when I create a new ProductCartItem I associate an already existing Product with it. When I save the productcartitem hibernate for some reasons is firing an update query on the product table too. I have already tried setting the relationship as updatable= false but to no avail. Below is the code for the service.
private ShoppingCart addProductToCartHelper(ProductCartItemDTO productCartItemDTO) throws ShoppingException{
ShoppingCart shoppingCart;
ProductCartItem productCartItem;
Product product = productService.getProductById(productCartItemDTO.getProductDTO().getId().intValue());
if (null == product) {
throw new ShoppingException();
}
Customer currentCustomer = CanveraWebUtil.getCurrentCustomer();
GuestUser guestUser = guestUserService.loadGuestUserByUUID(CanveraWebUtil.getCurrentGuestUserIdentifier());
shoppingCart = fetchShoppingCartForCustomerOrGuestUser();
if (null == shoppingCart) {
if (null != currentCustomer) {
shoppingCart = new ShoppingCart(currentCustomer);
} else {
shoppingCart = new ShoppingCart(guestUser);
}
shoppingCart.setShoppingBagStatus(ShoppingBagStatus.DRAFT);
}
Long productCartItemDTOId = productCartItemDTO.getId();
// we will not update the associated accessories as in our case these never comes from our UI.
if (null == productCartItemDTOId) {
modifyNumberOfPages(productCartItemDTO,product);
productCartItem = new ProductCartItem();
productCartItem.setProductItemProperty(productCartItemDTO.getProductItemProperty());
productCartItem.setQuantity(productCartItemDTO.getQuantity());
productCartItem.setProduct(product);
productCartItem.setPrice(productCartItemDTO.getPrice());
productCartItem.setGiftWrap(shoppingCart.getIsGiftWrap());
//associating project
productCartItem.setProject(productCartItemDTO.getProject());
shoppingCart.addCartItem(productCartItem);
productCartItem.setShoppingCart(shoppingCart);
} else {
for (CartItem cartItem : shoppingCart.getCartItems()) {
if (null != cartItem.getId() && cartItem.getId().equals(productCartItemDTOId)) {
productCartItem = (ProductCartItem) cartItem;
productCartItem.setProductItemProperty(productCartItemDTO.getProductItemProperty());
productCartItem.setPrice(productCartItemDTO.getPrice());
productCartItem.setQuantity(productCartItemDTO.getQuantity());
}
}
}
shoppingCart = shoppingCartRepository.save(shoppingCart);
return shoppingCart;
}
Can anybody point me in the right direction ? At any point of time I do not alter any property of the product object.

Repeated column in mapping for entity: Shipper column: SHIPPER_ID (should be mapped with insert="false"

I have been going around in circles with this error and not sure why I am getting this.
Here is the mapping of Shipper class
#Entity
#Table(schema="SALONBOOKS",name="SHIPPER")
#AttributeOverride(name="id", column=#Column(name="SHIPPER_ID"))
public class Shipper extends SalonObject {
private static final long serialVersionUID = 1L;
private ShipperType name;//ShipperType.WALKIN;
#Column(name="SHIPPER_NAME")
#Enumerated(EnumType.STRING)
public ShipperType getName() {
return name;
}
public void setName(ShipperType name) {
this.name = name;
}
#Override
public Long getId(){
return id;
}
}
Here is Order class which references Shipper
#Entity
#Table(schema="SALONBOOKS",name="ORDER")
#AttributeOverride(name="id", column=#Column(name="ORDER_ID"))
public class Order extends SalonObject {
private static final long serialVersionUID = 1L;
private BigDecimal total= new BigDecimal(0.0);
private int numOfItems=0;
private BigDecimal tax= new BigDecimal(0.0);;
private String currency="USD";
private BigDecimal subTotal= new BigDecimal(0.0);
private PaymentMethod paymentMethod;
private Shipper shipper;
private OrderStatusType status;
private Appointment appointment ;
private Person person;
#Column(name="TOTAL")
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
#Column(name="NUM_OF_ITEMS")
public int getNumOfItems() {
return numOfItems;
}
public void setNumOfItems(int numOfItems) {
this.numOfItems = numOfItems;
}
#Column(name="TAX")
public BigDecimal getTax() {
return tax;
}
public void setTax(BigDecimal tax) {
this.tax = tax;
}
#Column(name="CURRENCY")
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#Column(name="SUBTOTAL")
public BigDecimal getSubTotal() {
return subTotal;
}
public void setSubTotal(BigDecimal subTotal) {
this.subTotal = subTotal;
}
#ManyToOne
#JoinColumn(name="PAYMENT_METHOD_ID", insertable=false,updatable=false)
public PaymentMethod getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
#ManyToOne
#JoinColumn(name="SHIPPER_ID", insertable=false,updatable=false)
public Shipper getShipper() {
return shipper;
}
public void setShipper(Shipper shipVia) {
this.shipper = shipVia;
}
#Column(name="STATUS")
#Enumerated(EnumType.STRING)
public OrderStatusType getStatus() {
return status;
}
public void setStatus(OrderStatusType status) {
this.status = status;
}
#ManyToOne
#JoinColumn(name="APPOINTMENT_ID", insertable=false,updatable=false)
public Appointment getAppointment() {
return appointment;
}
public void setAppointment(Appointment appointment) {
this.appointment = appointment;
}
#ManyToOne
#JoinColumn(name="PERSON_ID", insertable=false,updatable=false)
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
#Override
public Long getId(){
return id;
}
}
each of these extends:
#MappedSuperclass
public abstract class SalonObject implements Entity, Serializable {
private static final long serialVersionUID = 1L;
protected Long id;
protected DateTime createDate;
protected DateTime updateDate;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof SalonObject
&& obj !=null){
return ObjectUtils.equals(this.id, ((SalonObject) obj).getId()) ;
}
return false;
}
#Column(name="CREATE_DATE")
public DateTime getCreateDate() {
return createDate;
}
public void setCreateDate(DateTime dateTime) {
this.createDate = dateTime;
}
#Column(name="UPDATE_DATE")
public DateTime getUpdateDate() {
return updateDate;
}
public void setUpdateDate(DateTime updateDate) {
this.updateDate = updateDate;
}
}
The stackTrace is ::
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: salonbooks.model.Shipper column: SHIPPER_ID (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:709)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:731)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:753)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:506)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343)
at salonbooks.core.HibernateConfiguration.sessionFactory(HibernateConfiguration.java:109)
removing the following method from Shipper and from Order worked to resolve this error
#Override
public Long getId(){
return id;
}
Because you are using property access, by overriding the base method (containing the mapping configuration) you will replace your base method mapping configuration with no config at all.
Using field access wouldn't have caused this issue, but the override would have been useless anyway. The id field should have private access too, so this method wouldn't compile if you change the access modifier.

Resources