I want to establish one to many relation between table vendor detail and product detail. like one vendor can have multiple products. but when i am inserting data into table its inserting all the four fields but not mapping vendorid into ProductDetail Table
and query generated is this.
Hibernate: insert into ProductInfo (productCategory, productDetails, productPrice, VendorId) values (?, ?, ?, ?) It shuld map vendor ID also but in table its empty.
VendorDetail.java
package com.cts.entity;
import javax.persistence.*;
#Entity
#Table(name = "VendorInfo")
public class VendorDetails {
#Id
#Column
private Long VendorId;
#OneToMany
private ProductDetails productdetail;
#Column
private String VendorName;
#Column
private String Password;
public String getVendorName() {
return VendorName;
}
public void setVendorName(String vendorName) {
VendorName = vendorName;
}
public Long getVendorId() {
return VendorId;
}
public void setVendorId(Long vendorId) {
VendorId = vendorId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
ProductDetails.java
package com.cts.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity#Table(name = "ProductInfo")
public class ProductDetails {
#ManyToOne(cascade = CascadeType.ALL)#JoinColumn(name = "VendorId")
private VendorDetails vendordetails;
public ProductDetails() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int productId;
#Column
private String productCategory;
#Column
private String productDetails;
#Column
private String productPrice;
public VendorDetails getVendordetails() {
return vendordetails;
}
public void setVendordetails(VendorDetails vendordetails) {
this.vendordetails = vendordetails;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDetails() {
return productDetails;
}
public void setProductDetails(String productDetails) {
this.productDetails = productDetails;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
}
DAO class ProductDetailDaoImpl.java
package com.cts.Dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.cts.entity.ProductDetails;
import com.cts.entity.to.ProductDetailsTo;
#Repository
public class ProductDetailDaoImpl implements ProductDetailDao {
#Autowired
SessionFactory sessionFactory;
#Transactional
public boolean saveProductInfo(ProductDetailsTo productTo) {
System.out.println("M in Registration DAO");
System.out.println(productTo.getProductCategory());
System.out.println(productTo.getProductDetails());
System.out.println(productTo.getProductId());
System.out.println(productTo.getProductPrice());
//getting productTo data to entity class
ProductDetails prodet = productTo.getEntity();
System.out.println("Value of product details is:" + prodet.getProductDetails());
sessionFactory.getCurrentSession().save(prodet);
return false;
}
}
VendorDetails has many ProductDetails so you need to make one to many annotation like this:-
#OneToMany(mappedBy="vendordetails") //mappedBy value will be what you declared //in ProductDetails class.
private Collection<ProductDetails> productdetail=new ArrayList<ProductDetails>;
and create the setter and getter of this.
Now in ProductDetails class you need to annotate many to one like this:-
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "VendorId")
private VendorDetails vendordetails;
Then a new column named 'VendorId' will be create in table 'ProductInfo' and since declare mappedBy value="vendordetails" so each vendor id would be insert.
I think you should replace the code
#OneToMany
private ProductDetails productdetail;
to
#OneToMany
private Set productdetailSet;
And create setter and getter for this.
You can visit the blog http://gaurav1216.blogspot.in/2014/01/hibernate-tutorial-day-5.html for one to many using annotation.
Related
My project based on spring boot,Thymeleaf,mysql,html and Jquery.I tried to make a #oneToMany Relation with unidirectional in maintable,but it produces only error like
2017-10-23 16:17:49.908 ERROR 18724 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: **Unable to map collection
com.vfraternity.process.entity.EntPropertyMaster.blockListPropSub** at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1702)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122)
~[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
com.vfraternity.VfSpringBootMain.main(VfSpringBootMain.java:12)
[classes/:na] Caused by: org.hibernate.AnnotationException: Unable to
map collection
com.vfraternity.process.entity.EntPropertyMaster.blockListPropSub at
org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1604)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:871)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:786)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:725)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1589)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:358)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:384)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:373)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods AbstractAutowireCapableBeanFactory.java:1761)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] ... 16 common frames omitted
Caused by: org.hibernate.cfg.RecoverableException: Unable to find
column with logical name: propertysubpk in
org.hibernate.mapping.Table(property_master) and its related
supertables and secondary tables at
org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:831)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:243)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1594)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] ... 31 common frames
omitted Caused by: org.hibernate.MappingException: Unable to find
column with logical name: propertysubpk in
org.hibernate.mapping.Table(property_master) and its related
supertables and secondary tables at
org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:826)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] ... 33 common frames
omitted
I tried to achive unidirectional using
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid", referencedColumnName="propertysubpk")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
But it produces only error...
Here is my complete codes..
**EntPropertyMaster**
package com.vfraternity.process.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
#Entity
#Table(name="Property_Master")
public class EntPropertyMaster implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6162594257264775391L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="propertyid")
private int property_id;
#NotNull
private String property_name;
#NotNull
private String address1;
#NotNull
#Column(columnDefinition="varchar(15) default'None'")
private String address2;
#NotNull
private String city;
#NotNull
private String state;
#NotNull
private String country;
#NotNull
private int zipcode;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid", referencedColumnName="propertysubpk")
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
#Version
private int version;
private Boolean is_active;
private String created_by;
private Date created_ts;
private String modified_by;
private Date modified_ts;
private String approved_by;
private Date approved_ts;
public EntPropertyMaster() {
}
//Getter Setter
public int getProperty_id() {
return property_id;
}
public void setProperty_id(int property_id) {
this.property_id = property_id;
}
public String getProperty_name() {
return property_name;
}
public void setProperty_name(String property_name) {
this.property_name = property_name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_ts() {
return created_ts;
}
public void setCreated_ts(Date created_ts) {
this.created_ts = created_ts;
}
public String getModified_by() {
return modified_by;
}
public void setModified_by(String modified_by) {
this.modified_by = modified_by;
}
public Date getModified_ts() {
return modified_ts;
}
public void setModified_ts(Date modified_ts) {
this.modified_ts = modified_ts;
}
public String getApproved_by() {
return approved_by;
}
public void setApproved_by(String approved_by) {
this.approved_by = approved_by;
}
public Date getApproved_ts() {
return approved_ts;
}
public void setApproved_ts(Date approved_ts) {
this.approved_ts = approved_ts;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public List<EntPropertySub> getBlockListPropSub() {
return blockListPropSub;
}
public void setBlockListPropSub(List<EntPropertySub> blockListPropSub) {
this.blockListPropSub = blockListPropSub;
}
}
/////////////////////////////////////////////////////////////
EntPropertySub
package com.vfraternity.process.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
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.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
#Entity
#Table(name="propertysub")
public class EntPropertySub implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 810618405796553525L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="propertysubpk")
private int propertySub_pk;
#NotNull
private String blockname;
#NotNull
private int floors;
#NotNull
private String flatstart;
private String flatend;
#Version
private int version;
private Boolean is_active;
private String created_by;
private Date created_ts;
private String modified_by;
private Date modified_ts;
private String approved_by;
private Date approved_ts;
public EntPropertySub() {
}
//Getter Setter
public int getPropertySub_pk() {
return propertySub_pk;
}
public void setPropertySub_pk(int propertySub_pk) {
this.propertySub_pk = propertySub_pk;
}
public String getBlockname() {
return blockname;
}
public void setBlockname(String blockname) {
this.blockname = blockname;
}
public int getFloors() {
return floors;
}
public void setFloors(int floors) {
this.floors = floors;
}
public String getFlatstart() {
return flatstart;
}
public void setFlatstart(String flatstart) {
this.flatstart = flatstart;
}
public String getFlatend() {
return flatend;
}
public void setFlatend(String flatend) {
this.flatend = flatend;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_ts() {
return created_ts;
}
public void setCreated_ts(Date created_ts) {
this.created_ts = created_ts;
}
public String getModified_by() {
return modified_by;
}
public void setModified_by(String modified_by) {
this.modified_by = modified_by;
}
public Date getModified_ts() {
return modified_ts;
}
public void setModified_ts(Date modified_ts) {
this.modified_ts = modified_ts;
}
public String getApproved_by() {
return approved_by;
}
public void setApproved_by(String approved_by) {
this.approved_by = approved_by;
}
public Date getApproved_ts() {
return approved_ts;
}
public void setApproved_ts(Date approved_ts) {
this.approved_ts = approved_ts;
}
}
Please help me to solve this..Thanks in advance
The cause of the error is:
Unable to find column with logical name: propertysubpk in org.hibernate.mapping.Table(property_master)
The reason is that you have the referencedColumnName attribute wrong. It is supposed to be:
JPA 2.1 11.1.25: The name of the column referenced
by this foreign key column. When
used with entity relationship mappings
other than the cases described below, the
referenced column is in the table of the target
entity. When used with a unidirectional
OneToMany foreign key mapping, the referenced
column is in the table of the
source entity. When used inside a Join-
Table annotation, the referenced key column
is in the entity table of the owning
entity, or inverse entity if the join is part of
the inverse join definition. When used in a
collection table mapping, the referenced
column is in the table of the entity containing
the collection.
To explain: a #JoinColumn creates a column in the many side of the relation (the EntPropertySub here) with the given name that references the PK of the parent entity, unless referencedColumnName is specified. In the latter case the FK in the "many" table references the column given in referencedColumnName. In your case you want to reference the PK of EntPropertyMaster, so referencedColumnName is redundant. Simply use:
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
Try this: make sure how the foreign key in the table EntPopertySub called
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertyid")
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
It's not possible to create a physical column on the master table because you have a OneToMany relation. OneToMany means that Master has many Sub Table references.
Let's explain the Problem:
If you would have a column in the master table you need to would add a list of references in one cell.
For Example
------------------
| sub-fk |
|1, 2, 3, 4| <-- and this is against the database normalization
But this is not necessary:
Hibernate will automatically select all the referenced sub-columns for you (intern hibernate joins to the columns)
If you use the entitymanager to select the master data, the sub-data is included in the List blockListPropSub attribute
When you use the #JoinColumn on a #OneToMany relationship, the name attribute will point to the relating tables column, that is EntPropertySub entity and the referencedColumnName should be pointing to the column of the entity in which the #OneToMany annotation is present, that is EntPropertyMaster.
So basically you have it other way round and it should be in my opinion:
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubpk", referencedColumnName="propertysubfkid")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
The error clearly shows mapping missing in your schema relation.
You need to map EntPropertyMaster in EntPropertySub.
#OneToMany(cascade=CascadeType.ALL, mappedBy="entPropertyMaster")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
Provide EntPropertyMaster mapping in relation entity too.i.e.
#ManyToOne
#JoinColumn(name="entPropertyMasterId",referencedColumnName="id")
private EntPropertyMaster entPropertyMaster;
Relationships in JPA are always unidirectional, unless you associate
the parent with the child in both directions. Cascading REMOVE
operations from the parent to the child will require a relation from
the parent to the child (not just the opposite).
Finnaly i got a answer..
i made a changes in master entity "EntPropertyMaster"
"#OneToMany(cascade=CascadeType.ALL)"
"#JoinColumn(name="propertyidfk")"
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
It will create column in child table,but i wrote this code in parent Entity...
Please Note we need to give unique name for column creation,Then only it creates a column in child table.... not a primarykey column name
of child /parent table..
I am trying to create a mapping in Hibernate on an Entity with ManyToOne relationship. I am trying this:
CampaignItemSlot class:
package models;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "campaign_item_slots")
public class CampaignItemSlot {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#JoinColumn(name = "advert_slot_id")
#ManyToOne
private AdvertSlot advertSlot;
private boolean active;
private Timestamp date_created;
private Timestamp date_updated;
public CampaignItemSlot() {
super();
// TODO Auto-generated constructor stub
}
}
However I get this in the log file:
Caused by: org.hibernate.HibernateException: Missing column: advertSlot_id in text_advertising.campaign_item_slots
This is my table SQL:
CREATE TABLE IF NOT EXISTS `text_advertising`.`campaign_item_slots` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`campaign_item_id` BIGINT NOT NULL,
`advert_slot_id` BIGINT NOT NULL,
`active` TINYINT(1) NOT NULL DEFAULT TRUE,
`date_created` DATETIME NOT NULL,
`date_updated` DATETIME NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_campaignitems_1_idx` (`campaign_item_id` ASC),
INDEX `fk_campaignitems_2_idx` (`advert_slot_id` ASC),
CONSTRAINT `fk_campaign_item_slots_1`
FOREIGN KEY (`campaign_item_id`)
REFERENCES `text_advertising`.`campaignitems` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_campaign_item_slots_2`
FOREIGN KEY (`advert_slot_id`)
REFERENCES `text_advertising`.`advert_slots` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
AdvertSlot class:
package models;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "advert_slots")
public class AdvertSlot {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#ManyToOne
private Publication publication;
private String name;
private String description;
private boolean active;
private Timestamp date_created;
private Timestamp date_updated;
public AdvertSlot() {
super();
// TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Publication getPublication() {
return publication;
}
public void setPublication(Publication publication) {
this.publication = publication;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Timestamp getDate_created() {
return date_created;
}
public void setDate_created(Timestamp date_created) {
this.date_created = date_created;
}
public Timestamp getDate_updated() {
return date_updated;
}
public void setDate_updated(Timestamp date_updated) {
this.date_updated = date_updated;
}
}
Somehow Hibernate is not seeing my advert_slot_id, help please?
The answer here is to create a custom naming strategy by extending org.hibernate.cfg.DefaultNamingStrategy and then referencing it via hibernate config: hibernate.ejb.naming_strategy
Here is an example:
#Override
public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName) {
String changed = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, propertyName) + "_id";
return changed;
}
It will work.Try this way:
First table:
#Table(name = "buyer_city")
public class BuyerCity{
//other fields
.....
#OneToMany(mappedBy="buyerCity", fetch = FetchType.LAZY)
#JsonManagedReference
private Set<BuyerCityMapping> buyerCityMapping = new HashSet<>();
}
Second table:
#Table(name = "buyer_city_mapping")
public class BuyerCityMapping{
//other fields
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonBackReference
#JoinColumn(name = "buyer_city_id")
private BuyerCity buyerCity;
}
These are my pojo class
Orderdetail.java
package online.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "orderdetail")
public class OrderDetail {
#Id
#Column(name="order_detail_id")
private int order_detail_id;
#Column(name="bill")
private float bill;
#ManyToOne
#JoinColumn(name = "p_id" )
private Product p_id;
#ManyToOne
#JoinColumn(name = "o_id" )
private Order o_id;
public int getOrder_detail_id() {
return order_detail_id;
}
public void setOrder_detail_id(int order_detail_id) {
this.order_detail_id = order_detail_id;
}
public float getBill() {
return bill;
}
public void setBill(float bill) {
this.bill = bill;
}
public Product getP_id() {
return p_id;
}
public void setP_id(Product p_id) {
this.p_id = p_id;
}
public Order getO_id() {
return o_id;
}
public void setO_id(Order o_id) {
this.o_id = o_id;
}
}
My Order.java
package online.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "ordertable")
public class Order {
#Id
#Column(name = "order_id")
private int order_id;
#OneToMany(mappedBy = "o_id",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<OrderDetail> orderdetail;
#ManyToOne
#JoinColumn(name = "u_id")
private UserDetail u_id;
public UserDetail getU_id() {
return u_id;
}
public void setU_id(UserDetail u_id) {
this.u_id = u_id;
}
#Column(name = "date")
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#Column(name = "totalbill")
private Float totalbill;
public Float getTotalbill() {
return totalbill;
}
public void setTotalbill(Float totalbill) {
this.totalbill = totalbill;
}
public List<OrderDetail> getOrderdetail() {
return orderdetail;
}
public void setOrderdetail(List<OrderDetail> orderdetail) {
this.orderdetail = orderdetail;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
When ever I am trying to save order class I want my orderdetail class also get saved but when I am trying to save the List in order,Is is not getting saved and there is not error provided by hibernate that can help...
Thanks for the help
when i am trying to to persist the order class
Hibernate: select orderdetai_.order_detail_id, orderdetai_.bill as bill7_, orderdetai_.o_id as o3_7_, orderdetai_.p_id as p4_7_ from orderdetail orderdetai_ where orderdetai_.order_detail_id=?
This what I am getting output.
This is my code which save the class
#Override
public boolean payment(String username, Integer ordernumber, Date date,
Float totalbill, List<Integer> list) {
Session session = sessionFactory.openSession();
Transaction tranction = session.beginTransaction();
try {
Query query = session
.createQuery("from UserDetail where user_username = :username");
query.setParameter("username", username);
List<UserDetail> userdetaillist = query.list();
UserDetail userdetail = userdetaillist.get(0);
query = session
.createQuery("from ProductDetail where product_detail_id in(:list)");
query.setParameterList("list", list);
List<ProductDetail> productdetail = query.list();
Order order = new Order();
order.setOrder_id(ordernumber);
order.setDate(date);
order.setU_id(userdetail);
order.setTotalbill(totalbill);
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = new OrderDetail();
for (ProductDetail pro : productdetail) {
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
System.out.print("totalbill" + totalbill);
System.out.println(orderdetail);
order.setOrderdetail(orderdetail);
session.save(order);
tranction.commit();
return true;
} catch (Exception e) {
tranction.rollback();
e.getStackTrace();
}
return false;
}
I think ordetail has to be created inside the for.. You are modifying the same object for each productdetail. Should be like this:
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = null;
for (ProductDetail pro : productdetail) {
ordetail = new OrderDetail();
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
Hey I have recheck my pojo class and I found out the mistake I have done. I have made change and it work properly now.
I was not setting the the id for Orderdetail table. It was auto increment in database.
So it was giving me error ""
So I have made change in orderdetail iD
"#GeneratedValue(strategy=GenerationType.AUTO)" So now It is working fine cause now hibernate know that the id will get value from database.
Thanks for the help and for your time
I have the following problem.
Here are my entities.
TestTeam.java
package utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TEST_TEAM")
public final class TestTeam implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7275223441128447981L;
#Id
#Column(name = "NAME")
private String name;
#OneToMany(mappedBy = "playerId", cascade = CascadeType.ALL)
private List<TestPlayer> test1List;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TestPlayer> getTest1List() {
return test1List;
}
public void setTest1List(List<TestPlayer> test1List) {
this.test1List = test1List;
}
public TestTeam() {
}
public TestTeam(final String name, final List<TestPlayer> test1List) {
this.name = name;
this.test1List = new ArrayList<>(test1List);
}
}
TestPlayer.java
package utils;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "TEST_PLAYER")
public class TestPlayer implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2792602076488917813L;
#Id
private long playerId;
#Column(name = "NAME", nullable = false)
private String playerName;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "TEAM_NAME")
private TestTeam team;
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "PREVIOUS_TEST_TEAM")
private Map<Integer, TestTeam> previousTests = Collections.emptyMap();
public TestPlayer() {
// TODO Auto-generated constructor stub
}
public TestPlayer(final long playerId) {
this.playerId = playerId;
}
public String getName() {
return playerName;
}
public void setName(String name) {
this.playerName = name;
}
/**
* #return the team
*/
public TestTeam getTeam() {
return team;
}
/**
* #param team the team to set
*/
public void setTeam(TestTeam team) {
this.team = team;
}
public Map<Integer, TestTeam> getPreviousTests() {
return previousTests;
}
public void setPreviousTests(Map<Integer, TestTeam> previousTests) {
this.previousTests = previousTests;
}
public TestPlayer(final String name,
final Map<Integer, TestTeam> previousTests) {
this.playerName = name;
this.previousTests = new HashMap<>(previousTests);
}
}
The following annotated collection.
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "PREVIOUS_TEST_TEAM")
private Map<Integer, TestTeam> previousTests = Collections.emptyMap();
produces by default a unique constraint for the foreign key from TestTeam entity.
create table PLAYERS_PREVIOUS_TEAMS (
Player_ID bigint not null,
previousTeamMap_NAME varchar(255) not null,
previousTeamMap_KEY integer,
primary key (Player_ID, previousTeamMap_KEY)
)
alter table PLAYERS_PREVIOUS_TEAMS
add constraint UK_f7nfahws0ttuhe5p7lpxt3vfv unique (previousTeamMap_NAME)
I do not need this constraint and I would like to switch off this behaviour so that Hibernate does not generate it. I have spent some time looking on the internet but I did not find anything. I do not want to introduce #OneToMany and many #ManyToOne by introducing another entity. Did anyone face a similar problem in the past?
I worked around my issue by changing #ElementCollection to #ManyToMany annotation.
#ManyToMany(fetch = FetchType.EAGER)
#CollectionTable(name = "PREVIOUS_TEST_TEAM")
private Map<Integer, TestTeam> previousTests = Collections.emptyMap();
This is my annotation class and i want userId and groupId column both as primary key.
I have found more questions (Question) about this, but didn't found relevant answer.
I have less reputation, so I am not able to comment on posts, So I am putting my question here.
This is my code..
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
#Entity
#Table(name="user_group")
public class user_group {
#Column(name="serviceProvider")
private String serviceProvider;
#Column(name="enterpriseId")
private String enterpriseId;
#Column(name="department")
private String department;
#Column(name="trunkGroupName")
private String trunkGroupName;
#Id
#Column(name="userId")
private String userId;
#Column(name="groupId")
private String group;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getServiceProvider() {
return serviceProvider;
}
public void setServiceProvider(String serviceProvider) {
this.serviceProvider = serviceProvider;
}
public String getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(String enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getTrunkGroupName() {
return trunkGroupName;
}
public void setTrunkGroupName(String trunkGroupName) {
this.trunkGroupName = trunkGroupName;
}
}
You should create a new #Embeddable class containing the PK fields:
#Embeddable
public class user_groupId implements Serializable {
#Column(name="userId")
private String userId;
#Column(name="groupId")
private String group;
}
And use it in the #Entity as an #EmbeddedId:
#Entity
public class user_group {
#EmbeddedId
user_groupId id;
...
}
You could also use the #IdClass annotation to that effect.
This excellent answer by Pascal Thivent elaborates on the details. You can also take a look at this other answer I posted to a almost identical question some time ago.
As a side note, if you've got control over the DB structure, you might also consider avoiding composite keys. There are some reasons to do so.
you can create a composite primary key in hibernate using #UniqueConstraint annotation.
#Table(name="user_group",uniqueConstraints=#UniqueConstraint(columnNames= {"userId","groupId"}))
public class user_group
{
#Column(name="userId")
private String userId;
#Column(name="groupId")
private String group;
}
above method is not feasible if we use spring because for creating composite primary key we have to create a class is not a good thing.
in hibernate and spring you only have to create POJO classes which are available as an entity on your system.