getting error in JPA Entity relationship simple example - java

I'm doing simple JPA entity relationship many to ine in spring using annotation while i am getting error that "com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null";
Below is my pojos
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTDB")
public class Student {
#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;
}
}
And mapped class as given below.
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 Marks {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long sid;
private int subject1;
private int subject2;
private int subject3;
#ManyToOne(optional=false)
#JoinColumn(name="id",referencedColumnName="id")
private Student s;
public Student getS() {
return s;
}
public void setS(Student s) {
this.s = s;
}
public long getSid() {
return sid;
}
public void setSid(long sid) {
this.sid = sid;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
}
So what can be possible solution for this?

package com.example;
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 = "STUDENTDB")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable=false,updatable=false)
private long id;
private String name;
}

Please check the following:
The table named STUDENTDB is defined in the database such that the primary key column id has AUTO_INCREMENT attribute.
Without the above attribute #GeneratedValue(strategy = GenerationType.AUTO) is not going to work in the present scenario.

Related

Spring Boot JPA relationship mapping and join queries

Started learning Spring Boot, JPA. Finding difficult on understanding JPA relationship concepts, I tried joining two tables but could not achieve the expected result can anyone help me to get the expected result.
Below Requirement
Have two tables as below
product_master table
product_catagory table
ProductMasterModel
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product_master")
public class ProductMasterModel {
#Id
#GeneratedValue
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_category_id")
private int productCategoryId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "product_category_id", referencedColumnName = "product_catogory_id",insertable = false, updatable = false)
private ProductCatagoryMasterModel productCatagoryMasterModel;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public ProductMasterModel() {
super();
}
public ProductMasterModel(String productName, int productCategoryId) {
super();
this.productName = productName;
this.productCategoryId = productCategoryId;
}
}
ProductCatagoryMasterModel
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="product_catagory")
public class ProductCatagoryMasterModel {
#Id
#GeneratedValue
#Column(name="product_catogory_id")
private int productCategoryId;
#Column(name="product_type")
private String productType;
#OneToOne(mappedBy = "productCatagoryMasterModel")
private ProductMasterModel productMasterModel;
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public ProductCatagoryMasterModel() {
super();
}
public ProductCatagoryMasterModel(String productType) {
super();
this.productType = productType;
}
}
ProductMasterRepository
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lollipop.model.ProductMasterModel;
#Repository
public interface ProductMasterRepository extends CrudRepository<ProductMasterModel, Integer> {
#Query (value = "select * from product_master pm, product_catagory pc where pc.product_catogory_id = pm.product_category_id", nativeQuery = true)
public List $ProductMasterModel$ getProductCategoryDetail();
}
ProductService
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lollipop.model.ProductMasterModel;
import com.lollipop.repository.ProductMasterRepository;
#Service
#Transactional
public class ProductService {
#Autowired
private ProductMasterRepository productMasterRepository;
public void getProductCat() {
List $ProductMasterModel$ productMasterModel = productMasterRepository.getProductCategoryDetail();
System.out.println("productMasterModel value "+productMasterModel.toString());
}
}
When calling getProductCat() method getting result as
productMasterModel value [ProductMasterModel [productId=1011,
productName=Pencil, productCategoryId=10], ProductMasterModel
[productId=1012, productName= Mobile, productCategoryId=11]]
Since ProductMasterModel is not having productType variable it is not displaying productType
I need below result by joining two tables, please help me to acheive this
[[productName=Pencil,productType=Stationary],[productName=
Mobile,productType=Electronics]]
Yes, One to One Relationship should work.
Changes should be made in your POJO.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product_master")
public class ProductMasterModel {
#Id
#GeneratedValue
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_category_id")
private int productCategoryId;
#OneToOne(mappedBy= product_master, fetch = FetchType.LAZY)
public ProductCatagoryMasterModel productCatagory;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public ProductMasterModel() {
}
public ProductMasterModel(String productName, int productCategoryId) {
super();
this.productName = productName;
this.productCategoryId = productCategoryId;
}
}
Next Address your Category Model
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="product_catagory")
public class ProductCatagoryMasterModel {
#Id
#GeneratedValue
#Column(name="product_catogory_id")
private int productCategoryId;
#Column(name="product_type")
private String productType;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "product_master", referencedColumnName = "product_id")
private ProductMasterModel productMaster;
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public ProductCatagoryMasterModel() {
super();
}
public ProductCatagoryMasterModel(String productType) {
super();
this.productType = productType;
}
}
We also need DAO
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lollipop.model.ProductMasterModel;
#Repository
public interface ProductMasterRepository extends CrudRepository<ProductMasterModel, Integer> {
}
Product Service
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lollipop.model.ProductMasterModel;
import com.lollipop.repository.ProductMasterRepository;
#Service
#Transactional
public class ProductService {
#Autowired
private ProductMasterRepository productMasterRepository;
public List<ProductMasterModel > getAllProducts() {
return productMasterRepository.findAll();
}
public Optional<ProductMasterModel > getProductById(int productId) {
if (!productMasterRepository.existsById(productId)) {
throw new ResourceNotFoundException("Product with id " + productId+ " not found");
}
return productMasterRepository.findById(productId);
}
}
}
You need to establish ont-to-one relationship between those two tables.
Take a look at this:
Example

Problems with #ManyToMany Annotation Hibernate - Foreign key has the wrong number of column (should be 3)

I want to add the following database-structure to my Jpa:
CREATE TABLE USER (
id int PRIMARY KEY AUTO_INCREMENT,
firstname varchar(255),
lastname varchar(255)
);
CREATE TABLE PROJECT (
PNUM varchar(255) PRIMARY KEY,
PNAME varchar(255) NOT NULL
);
CREATE TABLE ROLE (
id int PRIMARY KEY AUTO_INCREMENT,
description varchar(255) NOT NULL
);
CREATE TABLE ASSIGNMENT (
user_id int,
project_num varchar(255),
role_id int,
foreign key (user_id) REFERENCES USER(ID),
FOREIGN KEY (project_num) REFERENCES PROJECT(PNUM),
FOREIGN KEY (role_id) REFERENCES ROLE(id),
PRIMARY KEY (user_id, project_num, role_id)
);
So I started off making the three Entities User, Project and Role (See end of this post for full classes). Then I created the Assignment-class for the connection including an #EmbeddedId:
The Assigment class:
package com.demo.example.entity;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
#Entity
public class Assignment {
#EmbeddedId
private AssignmentId id;
public Assignment() {
// TODO Auto-generated constructor stub
}
public AssignmentId getId() {
return this.id;
}
public void setId(AssignmentId id) {
this.id = id;
}
}
The AssignmentId-class
package com.demo.example.entity;
import java.io.Serializable;
import javax.persistence.Embeddable;
#Embeddable
public class AssignmentId implements Serializable {
private Role role;
private Project project;
private User user;
public AssignmentId(Project project, Role role, User user) {
this.project = project;
this.role = role;
this.user = user;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Finally I declared the repository for the Assignment:
package com.demo.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.demo.example.entity.Assignment;
import com.demo.example.entity.AssignmentId;
#Repository
public interface AssignmentRepository extends JpaRepository<Assignment, AssignmentId> {
}
Now upon running a JUnit-Test I run into the following error:
Caused by: org.hibernate.AnnotationException: A Foreign key refering com.demo.example.entity.Assignment from com.demo.example.entity.User has the wrong number of column. should be 3
I have seen quite a few suggestions on what to do but none of them worked (also, most of the time the "should be"-value is 2. Is this even working out with 3?). But I cannot make out why my User-Entity has a wrong number of columns? It provided three in the #JoinTable-Annotation (one join and two inverseJoin-Columns). What did I do wrong?
The classes:
User.java:
package com.demo.example.entity;
import java.util.HashSet;
import java.util.Set;
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.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class User {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="user_id")
private int user_id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="ASSIGNMENT",
joinColumns = {#JoinColumn(name="user_id")},
inverseJoinColumns = { #JoinColumn(name="pnum"),
#JoinColumn(name="role_id")}
)
private Set<Assignment> assignments = new HashSet<Assignment>();
public Set<Assignment> getAssignments() {
return this.assignments;
}
public User() {
}
public User(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public void setId(int id) {
this.user_id = id;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getId() {
return user_id;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
Project.java:
package com.demo.example.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="PROJECT")
public class Project {
#Id
#Column(name="PNUM")
private String pnum;
#Column(name = "PNAME", nullable = false)
private String pname;
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="ASSIGNMENT",
joinColumns = {#JoinColumn(name="pnum")},
inverseJoinColumns = { #JoinColumn(name="user_id"),
#JoinColumn(name="role_id")}
)
private Set<Assignment> assignments = new HashSet<Assignment>();
public Set<Assignment> getAssignments() {
return this.assignments;
}
public Project() {
// TODO Auto-generated constructor stub
}
public Project(String PNUM, String PNAME) {
this.pnum = PNUM;
this.pname = PNAME;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
Role.java:
package com.demo.example.entity;
import java.util.HashSet;
import java.util.Set;
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.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="ROLE")
public class Role {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="role_id")
private int role_id;
#Column(name = "NAME", nullable = false)
private String name;
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="ASSIGNMENT",
joinColumns = {#JoinColumn(name="role_id")},
inverseJoinColumns = { #JoinColumn(name="user_id"),
#JoinColumn(name="project_id")}
)
private Set<Assignment> assignments = new HashSet<Assignment>();
public Set<Assignment> getAssignments() {
return this.assignments;
}
public Role(String name) {
this.name = name;
}
public int getId() {
return this.role_id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

Another pojo class is not creating table in database in hibernate

TrainingDays.java
package com.hibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingDays")
public class TrainingDays {
#Id
#GeneratedValue
private int TD_Id;
private String T_Days;
public int getTD_Id() {
return TD_Id;
}
public void setTD_Id(int tD_Id) {
TD_Id = tD_Id;
}
public String getT_Days() {
return T_Days;
}
public void setT_Days(String t_Days) {
T_Days = t_Days;
}
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="TD_Id")
private Set<TrainingTime> trainingTime;
public Set<TrainingTime> getTrainingTime() {
return trainingTime;
}
public void setTrainingTime(Set<TrainingTime> trainingTime) {
this.trainingTime = trainingTime;
}
}
TrainingTime.java
package com.hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingTime")
public class TrainingTime {
#Id
#GeneratedValue
private int TT_Id;
#ManyToOne
#JoinColumn(name = "TD_Id")
private TrainingDays trainingDays;
private String time;
private String desc;
public int getTT_Id() {
return TT_Id;
}
public void setTT_Id(int tT_Id) {
TT_Id = tT_Id;
}
public TrainingDays getTrainingDays() {
return trainingDays;
}
public void setTrainingDays(TrainingDays trainingDays) {
this.trainingDays = trainingDays;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Hibernate.cfg.xml
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="connection.username">blueHeaven</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.hibernate.Rodie" />
<mapping class="com.hibernate.TrainingTime" />
<mapping class="com.hibernate.TrainingDays" />
</session-factory>
In the database TraningDays table is created but traningTime table is not created.
Can any one help?
Please correct your code as given:
class TrainingDays
#Entity
#Table(name = "TrainingDays")
public class TrainingDays {
#OneToMany(cascade={CascadeType.ALL},mappedBy = "trainingDays")
private Set<TrainingTime> trainingTime;
}
class TrainingTime
#Entity
#Table(name = "TrainingTime")
public class TrainingTime {
#ManyToOne
#JoinColumn(name = "TD_Id")
private TrainingDays trainingDays;
}
You need to specify "mappedBy" when you are creating bidirectional
relationship.
As the mapping is bidirectional. Please try like this.
TrainingDays.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingDays")
public class TrainingDays implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TD_Id")
private int TD_Id;
#Column(name="T_Days")
private String T_Days;
#OneToMany(mappedBy="trainingDays")
private Set<TrainingTime> trainingTime;
public int getTD_Id() {
return TD_Id;
}
public void setTD_Id(int tD_Id) {
TD_Id = tD_Id;
}
public String getT_Days() {
return T_Days;
}
public void setT_Days(String t_Days) {
T_Days = t_Days;
}
public Set<TrainingTime> getTrainingTime() {
return trainingTime;
}
public void setTrainingTime(Set<TrainingTime> trainingTime) {
this.trainingTime = trainingTime;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
TrainingTime.java
import java.io.Serializable;
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.Table;
#Entity
#Table(name = "TrainingTime")
public class TrainingTime implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TT_Id")
private int TT_Id;
#Column(name="time")
private String time;
#Column(name="desc")
private String desc;
#ManyToOne
#JoinColumn(name="TD_Id")
private TrainingDays trainingDays;
public int getTT_Id() {
return TT_Id;
}
public void setTT_Id(int tT_Id) {
TT_Id = tT_Id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public TrainingDays getTrainingDays() {
return trainingDays;
}
public void setTrainingDays(TrainingDays trainingDays) {
this.trainingDays = trainingDays;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
Always try to apply mappings after declaring all the columns.
I got the Solution of this issue,
in TrainingTime Pojo class i have created one variable named "Desc", and i found that this keyword is already reserved, so can name any variable like this.

On delete CASCADE is not working in manyToMany mapping in hibernate

I have many to many mapping in hibernate with join table and have 3 different classes. OperationEntity and EndPointEntity has manyToMany mapping. I have tried using #Cascade(org.hibernate.annotations.CascadeType.ALL) and #ManyToOne(cascade=CascadeType.ALL) annotations. But when checked in Database, on delete and on update are RESTRICT. Below is the code:
OperationEntity.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="t_operation", schema="test")
public class OperationEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="op_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int opId;
#Column(name="op_name")
private String opName;
#Column(name="op_desc")
private String opDesc;
#OneToMany(mappedBy="operationsEntity")
private List<OpEndPointEntity> listOfOperationsEndpoints;
public int getOpId() {
return opId;
}
public void setOpId(int opId) {
this.opId = opId;
}
public String getOpName() {
return opName;
}
public void setOpName(String opName) {
this.opName = opName;
}
public String getOpDesc() {
return opDesc;
}
public void setOpDesc(String opDesc) {
this.opDesc = opDesc;
}
public List<OpEndPointEntity> getListOfOperationsEndpoints() {
return listOfOperationsEndpoints;
}
public void setListOfOperationsEndpoints(
List<OpEndPointEntity> listOfOperationsEndpoints) {
this.listOfOperationsEndpoints = listOfOperationsEndpoints;
}
}
EndPointEntity.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="t_endPoint", schema="test")
public class EndPointEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="end_point_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int endPointId;
#Column(name="end_point")
private String endPoint;
#Column(name="end_point_desc")
private String endPointDesc;
#OneToMany(mappedBy="endPointEntity")
private List<OpEndPointEntity> listOpEndPoint;
public int getEndPointId() {
return endPointId;
}
public void setEndPointId(int endPointId) {
this.endPointId = endPointId;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endPoint) {
this.endPoint = endPoint;
}
public String getEndPointDesc() {
return endPointDesc;
}
public void setEndPointDesc(String endPointDesc) {
this.endPointDesc = endPointDesc;
}
public List<OpEndPointEntity> getListOpEndPoint() {
return listOpEndPoint;
}
public void setListOpEndPoint(List<OpEndPointEntity> listOpEndPoint) {
this.listOpEndPoint = listOpEndPoint;
}
}
Mapping class : OpEndPointEntity.java
import java.io.Serializable;
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.Table;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name="t_op_endpoint_map", schema="test")
public class OpEndPointEntity implements Serializable {
private static final long serialVersionUID = 71L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="OP_ENDPOINT_ID")
private Integer operationEndpointId;
#ManyToOne(cascade=CascadeType.ALL)
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name="end_point_id")
private EndPointEntity endPointEntity;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name="op_id")
private OperationEntity operationsEntity;
public Integer getOperationEndpointId() {
return operationEndpointId;
}
public void setOperationEndpointId(Integer operationEndpointId) {
this.operationEndpointId = operationEndpointId;
}
public EndPointEntity getEndPointEntity() {
return endPointEntity;
}
public void setEndPointEntity(EndPointEntity endPointEntity) {
this.endPointEntity = endPointEntity;
}
public OperationEntity getOperationsEntity() {
return operationsEntity;
}
public void setOperationsEntity(OperationEntity operationsEntity) {
this.operationsEntity = operationsEntity;
}
}
Please provide a way to make on delete and on update CASCADE. Can it be jar issue?
Did you delete it from Java code or using terminal? If you delete it from terminal, it won't work. Once you backup with mysqldump, you will see there's no ON DELETE SET NULL or ON DELETE CASCADE in that sql file. That means it works only with Java Code. Try deleting it from Java Code. I'm not sure how you delete it. And I need to see both classes to see the code.

hibernate4: A Foreign key refering has the wrong number of column. should be 2

I am trying to use Hibernate annotations for writing a model class for my database tables.
I have two tables each having a primary key User and ChartDetails.
package com.winnow.springservice.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//User Entity class mapped with hibernate
#Entity
#Table(name="User")
#SuppressWarnings(value = { "all" })
public class User implements Serializable
{
#Id
#Column(name="user_id")
public String user_Id;
#Column(name="user_name")
public String userName;
public String password;
#Column(name="last_login")
public String last_Login;
#Column(name="role_id")
public int role_Id;
public int status;
public String getUser_Id() {
return user_Id;
}
public void setUser_Id(String user_Id) {
this.user_Id = user_Id;
}
public String getLast_Login() {
return last_Login;
}
public void setLast_Login(String last_Login) {
this.last_Login = last_Login;
}
public int getRole_Id() {
return role_Id;
}
public void setRole_Id(int role_Id) {
this.role_Id = role_Id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
System.out.println("username"+userName);
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password)
{
System.out.println("password "+password);
this.password = password;
}
}
Chart details
package com.winnow.springservice.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Chart_Details")
#SuppressWarnings(value = { "all" })
public class ChartDetails implements Serializable
{
#Id
#Column(name="chart_id")
public int chartId;
#Id
#Column(name="chart_type_id")
public int chartTypeId;
#Column(name="chart_name")
public String chartName;
#Column(name="x_axis")
public String x_axis;
#Column(name="y_axis")
public String y_axis;
#Column(name="z_axis")
public int z_axis;
#Column(name="chart_filter_id")
public int chartFilterId;
#Column(name="is_data_table")
public boolean isDataTable;
#Column(name="dataset_id")
public int datasetId;
#Column(name="user_id")
public int userId;
#Column(name="project_id")
public int projectId;
}
And I have one more table – ChartsStarredBy – which has userId and chart_id as foreign keys from the above two tables.
But I am unable to find how I can reference these constraints in the ChartsStarredBy table.
package com.winnow.springservice.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
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.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="Chart_Starred_By")
#SuppressWarnings(value = { "all" })
public class ChartsStarredBy implements Serializable
{
#Id
public int id;
#Temporal(TemporalType.DATE)
public Date starred_date;
#ManyToOne
#JoinColumn(name = "FK_chart_id4")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "FK_user_id4")
private User user;
public Date getStarred_date()
{
return starred_date;
}
public void setStarred_date(Date starred_date)
{
this.starred_date = starred_date;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public ChartDetails getChart_details() {
return chart_details;
}
public void setChart_details(ChartDetails chart_details) {
this.chart_details = chart_details;
}
}
Please help me achieve this? Thanks in advance.
First of all you should create an integer id for User table which is primary key. Here in your code you creating it as String type.
You are doing wrong here
#ManyToOne
#JoinColumn(name = "FK_chart_id4")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "FK_user_id4")
private User user;
You have IDs in User table & ChartDetails table as
#Id
#Column(name="user_id")
public String user_Id;
AND
#Id
#Column(name="chart_id")
public int chartId;
So when you refer to id of another class you should give name of that id in #JoinColumn. Just like this
#ManyToOne
#JoinColumn(name = "chartId")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "user_Id")
private User user;
You can also use #ForeignKey(name = "user_Id") annotation from Hibernate like this
#ManyToOne
#ForeignKey(name = "user_Id")
private User user;
Example tutorial :- Hibernate One To Many Annotation Tutorial

Categories