EclipseLink ADD CONSTRAINT Exception - java

I would like to use create-or-extend-tables but eclipselink gives below error after tables were created. I am using Eclipselink 2.5.2 and db is MS Sql 2014
Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: com.microsoft.sqlserver.jdbc.SQLServerException:
'announcementCOMPANY_ID' object already exists. Error Code: 2714 Call:
ALTER TABLE announcement ADD CONSTRAINT announcementCOMPANY_ID FOREIGN
KEY (COMPANY_ID) REFERENCES company (ID) Query:
DataModifyQuery(sql="ALTER TABLE announcement ADD CONSTRAINT
announcementCOMPANY_ID FOREIGN KEY (COMPANY_ID) REFERENCES company
(ID)")
Persistance.java
persistenceMap.put("javax.persistence.jdbc.driver", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_DRIVER));
persistenceMap.put("javax.persistence.jdbc.user", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_USER));
persistenceMap.put("javax.persistence.jdbc.password", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_PASSWORD));
persistenceMap.put("javax.persistence.jdbc.url", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_URL));
persistenceMap.put("eclipselink.logging.logger",
Log4jSessionLog.class.getName());
// persistenceMap.put("eclipselink.logging.file",
// Log4jSessionLog.class.getName());
persistenceMap
.put("eclipselink.ddl-generation.output-mode", "database");
persistenceMap.put("eclipselink.weaving.internal", "false");
persistenceMap.put("eclipselink.logging.level", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_LOGGING_LEVEL));
persistenceMap.put("eclipselink.ddl-generation",
"create-or-extend-tables");
Announcement.java
#Entity
#Table(name="announcement")
public class Announcement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "annId")
private int id;
#Column(nullable =false, length = 250, name="annName")
private String name;
#Column(length = 250)
private String mainTitle;
#Column(nullable=false, length = 250)
private String subTitle;
#Lob
private String content;
#Column(nullable = false)
private Date startDate;
#Transient
private java.util.Date startDateUtil;
#Column(nullable = false)
private Date endDate;
#Transient
private java.util.Date endDateUtil;
#Lob
private String imgUrl;
#Column(nullable = false)
private boolean isActive;
#Column(nullable = false)
private boolean isDeleted;
#Transient
private BtcResponse status;
private Type type;
#ManyToMany
#JoinTable(name="announcementLogs")
private List<Log> logAList = new ArrayList<Log>();
private Company company;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMainTitle() {
return mainTitle;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public java.util.Date getStartDateUtil() {
return startDateUtil;
}
public void setStartDateUtil(java.util.Date startDateUtil) {
this.startDateUtil = startDateUtil;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public java.util.Date getEndDateUtil() {
return endDateUtil;
}
public void setEndDateUtil(java.util.Date endDateUtil) {
this.endDateUtil = endDateUtil;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public List<Log> getLogAList() {
return logAList;
}
public void setLogAList(List<Log> logAList) {
this.logAList = logAList;
}
#ManyToOne
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Announcement() {
super();
}
public Announcement(BtcResponse status) {
super();
this.status = status;
}
public Announcement(java.util.Date startDateUtil,
java.util.Date endDateUtil, String imgUrl, boolean isActive) {
super();
this.startDateUtil = startDateUtil;
this.endDateUtil = endDateUtil;
this.imgUrl = imgUrl;
this.isActive = isActive;
}
#ManyToOne
#JoinColumn(name = "id")
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
Company.java
#Entity
#Table(name="company")
public class Company {
#Id
#Column(nullable = false)
private int id;
#Column(length = 100, nullable = false, name="companyName")
private String name;
private List<Banner> bannerList = new ArrayList<Banner>();
private List<Announcement> announcementList = new ArrayList<Announcement>();
private List<PriceList> priceList = new ArrayList<PriceList>();
#OneToMany(mappedBy="company")
public List<Announcement> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(List<Announcement> announcementList) {
this.announcementList = announcementList;
}
#Transient
private BtcResponse status;
public int getId() {
return id;
}
public Company(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy="company")
public List<Banner> getBannerList() {
return bannerList;
}
public void setBannerList(List<Banner> bannerList) {
this.bannerList = bannerList;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public Company() {
super();
}
public Company(BtcResponse status) {
super();
this.status = status;
}
#OneToMany(mappedBy="company")
public List<PriceList> getPriceList() {
return priceList;
}
public void setPriceList(List<PriceList> priceList) {
this.priceList = priceList;
}
}

Related

Foreign key always Null in DB

I got this error in Spring: enter image description here When I try to join two table entities.
And the foreign key is always Null in DB, Why?
My Entity Classes - Task, ListeExecJob.
Please, help me
Task :
#SuppressWarnings("serial")
#Entity
#Table(name ="task")
public class Task implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "nom_job", length = 20,nullable = false)
private String nom_job;
#Column(name = "type_commande", length = 20,nullable = false)
private String type_commande;
#Column(name = "description", length = 100, nullable = false)
private String description;
#Column(name = "script", length = 100, nullable = false)
private String script;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "date_execution")
private Date date_execution;
#Column(name = "active")
private boolean active;
#ManyToOne
#JoinColumn(name="id_liste")
private ListeExecJob liste;
public ListeExecJob getListe() {
return liste;
}
public void setListe(ListeExecJob liste) {
this.liste = liste;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNom_job() {
return nom_job;
}
public void setNom_job(String nom_job) {
this.nom_job = nom_job;
}
public String getType_commande() {
return type_commande;
}
public void setType_commande(String type_commande) {
this.type_commande = type_commande;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public boolean getActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Task() {
}
public Task(Integer id, String nom_job, String type_commande, String description, String script,
Date date_execution, boolean active) {
super();
this.id=id;
this.nom_job = nom_job;
this.type_commande = type_commande;
this.description = description;
this.script = script;
this.date_execution = date_execution;
this.active=active ;
}
}
ListeExecJob.java
____________________________________________________
#SuppressWarnings("serial")
#Entity
#Table(name ="liste")
#JsonIgnoreProperties(
value = {"dateCreation"},
allowGetters = true
)
public class ListeExecJob implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idListe")
private int idListe;
#Column(name = "status")
private String status;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "date_creation")
#CreatedDate
private Date date_creation;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#JoinColumn(name = "date_execution")
private Date date_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "fin_execution")
private Date fin_execution;
#JsonFormat(pattern="yyyy-MM-dd'T'HH:mm")
#Column(name = "next_execution")
private Date next_execution;
#OneToMany(mappedBy="liste",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JsonIgnore
private List<Task> task;
public int getIdListe() {
return idListe;
}
public void setIdListe(int idListe) {
this.idListe = idListe;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_execution() {
return date_execution;
}
public void setDate_execution(Date date_execution) {
this.date_execution = date_execution;
}
public Date getFin_execution() {
return fin_execution;
}
public void setFin_execution(Date fin_execution) {
this.fin_execution = fin_execution;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonIgnore
public List<Task> getTask() {
if (task == null) {
task = new ArrayList<>();
}
return this.task;
}
public void addTask(Task task) {
getTask().add((Task) task);
((Task) task).setListe(this);
}
public void removeTask(Task task) {
getTask().remove(task);
task.setListe(null);
}
#JsonSetter
public void setTask(List<Task> task) {
this.task = task;
}
public ListeExecJob() {
}
public ListeExecJob(int idListe, String status, Date date_creation, Date date_execution, Date b
fin_execution,
Date next_execution) {
super();
this.idListe = idListe;
this.status = status;
this.date_creation = date_creation;
this.date_execution = date_execution;
this.fin_execution = fin_execution;
this.next_execution = next_execution;
}
}
Task service
#Service
#Transactional(propagation= Propagation.SUPPORTS)
#Primary
public class TaskService {
#Autowired
private TaskRepository repository;
#Autowired
private ListeExecJobService service;
#Autowired
public TaskService(TaskRepository repository) {
super();
this.repository = repository;
}
public List<Task> listAllTask(){
return repository.findAll();
}
public Task addTask(Task task){
ListeExecJob ab = service.getByreferenece(task.getListe().getIdListe());
ab.addTask(task);
return repository.save(task);
/* task.setListe(ab);
System.out.println(task.getListe().getIdListe());
ab.addTask(task);*/
}
public Task updateTask(Integer id , Task task){
Task job1 = new Task();
job1 = task;
job1.setId(id);
return addTask(job1);
}
public void deleteTask(Integer id){
repository.deleteById(id);
}
public Task getByreferenece(Integer id){
return repository.findById(id).isPresent()? repository.findById(id).get():null;
}
}
ListeExecJobService
#Service
#Transactional
#Primary
public class ListeExecJobService {
#Autowired
private ListeExecJobRepository SJIRepos;
#Autowired
public ListeExecJobService(ListeExecJobRepository SJIRepos) {
super();
this.SJIRepos = SJIRepos;
}
public List<ListeExecJob> listAllListeExecJob(){
return SJIRepos.findAll();
}
public ListeExecJob addListeExecJob(ListeExecJob SJI){
return SJIRepos.save(SJI);
}
public ListeExecJob getByreferenece(Integer idListe){
return SJIRepos.findById(idListe).isPresent()? SJIRepos.findById(idListe).get():null;
}
public void deleteListeExecJob(Integer idListe){
SJIRepos.deleteById(idListe);
}
public ListeExecJob updateListeExecJob(Integer idListe , ListeExecJob sji){
ListeExecJob sji01 = new ListeExecJob();
sji01 = sji;
sji01.setIdListe(idListe);
return addListeExecJob(sji01);
}
public void deleteById(Integer idListe) {
SJIRepos.deleteById(idListe);
}
}
try #JoinColumn(name="id_liste",referencedColumnName = "idListe") in the task class, you have a problem in the join column

How to write hibernate insert query if entity name is saved in a variable

In my application I came to a situation where i need to save some data to an entity but the entity name is unknown, and is saved in a variable and entity field and its value are in a list.So i need to pick the entity name from variable and its field and data from list.
Variable is xEntity.
public void saveData(String xEntity,List<Attribute> attributeList) {
// hibernate insert query
}
Some of the entity class are shown below which may come as the xEntity,and attributeList in function saveData().
#Entity
#Table(name = "person")
public class Person implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "name")
private String name;
#Column(name="dob")
private Date dob;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public Person() {
}
public Person(Integer id, String empId, String name, Date dob, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.name = name;
this.dob = dob;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
#Entity
#Table(name = "person_address")
public class PersonAddress implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "house_name")
private String houseName;
#Column(name="post_office")
private String postOffice;
#Column(name="district")
private String district;
#Column(name="state")
private String state;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public PersonAddress() {
}
public PersonAddress(Integer id, String empId, String houseName, String postOffice, String district, String state, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.houseName = houseName;
this.postOffice = postOffice;
this.district = district;
this.state = state;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public String getPostOffice() {
return postOffice;
}
public void setPostOffice(String postOffice) {
this.postOffice = postOffice;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setState(String state) {
this.state = state;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
#Entity
#Table(name = "person_qualification")
public class PersonQualification implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "degree")
private String degree;
#Column(name="grade")
private String grade;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public PersonQualification() {
}
public PersonQualification(Integer id, String empId, String degree, String grade, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.degree = degree;
this.grade = grade;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
Below are some of the values that may come to attributeList each time.
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"name","value":"Basil"},{"fieldName":"dob","value":"26-11-90"}]
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"houseName","value":"Ellikkal"},{"fieldName":"postOffice","value":"Chengara"},{"fieldName":"district","value":"Alappy"},{"fieldName":"state","value":"Kerala"}]
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"degree","value":"B.Tech"},{"fieldName":"grade","value":"First class"}]
Date value come as string date which should be formatted to type Date.Below is the Attribute class.
public class Attribute implements Serializable {
private String fieldName;
private String value;
public Attribute() {
super();
// TODO Auto-generated constructor stub
}
public Attribute(String fieldName, String value) {
this.fieldName = fieldName;
this.value = value;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Now can i use hibernate query to save data to each entity?If anyone know please help me.
Though I don't know why you want to do this but if you have no other choice then you have to use reflection here.
First create instance using your class name. It should be full class name. Also your classes should have default constructor.
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
Now use reflection to set the values of fields. Lets assume your field name is stored in fieldName and value is stored in fieldValue
declaredField = object.getClass().getDeclaredField(fieldName);
declaredField.setAccessible(true);
declaredField.set(object, fieldValue);
For the cases where you need to convert the type from String to Date etc. You have to get field type and convert accordingly. Field type can be found out by:
declaredField.getFieldType();
Now save this object using hibernate.
sessionFactory.getCurrentSession().save(object);
I'm afraid HQL doesn't support inserting per query but you can use reflection to build your entities or create a native query.

Error in One to many mapping in hibernate-spring integration

I need to map two pojo class using one to many, but getting the below error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'testCaseStepsform' at row 1
When I saw the table created by hibernate, I found that a column with data type blob is created
I am adding the code below.
#Entity
#Table(name="TEST_CASE_DESC")
public class TestCaseForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 10001234L;
#Id
#Column(name="TEST_CASE_ID")
private String testCaseId;
#Column(name="PROJECT_NAME")
private String projectName;
#Column(name="PROJECT_ID")
private String projectId;
#Column(name="RELEASE_NAME")
private String releaseName;
#Column(name="RELEASE_ID")
private String releaseId;
#Column(name="ITERATION")
private String iteration;
#Column(name="TITLE")
private String title;
#Column(name="CREATED_BY")
private String createdBy;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="DESCRIPTION")
private String description;
#Column(name="PRE_CONDITION")
private String preCondition;
#Column(name="POST_CONDITION")
private String postCondition;
#Column(name="TYPE")
private String type;
#Column(name="IMPORTANCE")
private String importance;
private ArrayList<TestCaseStepsForm> testCaseStepsform = new ArrayList<TestCaseStepsForm>();
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPreCondition() {
return preCondition;
}
public void setPreCondition(String preCondition) {
this.preCondition = preCondition;
}
public String getPostCondition() {
return postCondition;
}
public void setPostCondition(String postCondition) {
this.postCondition = postCondition;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getRelease() {
return releaseName;
}
public void setReleaseName(String releaseName) {
this.releaseName = releaseName;
}
public String getReleaseId() {
return releaseId;
}
public void setReleaseId(String releaseId) {
this.releaseId = releaseId;
}
public String getIteration() {
return iteration;
}
public void setIteration(String iteration) {
this.iteration = iteration;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getReleaseName() {
return releaseName;
}
public String getImportance() {
return importance;
}
public void setImportance(String importance) {
this.importance = importance;
}
#OneToMany(mappedBy = "TEST_CASE_DESC", cascade = CascadeType.ALL)
public ArrayList<TestCaseStepsForm> getTestCaseStepsform() {
return testCaseStepsform;
}
public void setTestCaseStepsform(ArrayList<TestCaseStepsForm> testCaseStepsform) {
this.testCaseStepsform = testCaseStepsform;
}
public String getTestCaseId() {
return testCaseId;
}
public void setTestCaseId(String testCaseId) {
this.testCaseId = testCaseId;
}
}
#Entity
#Table(name="TEST_CASE_STEP")
public class TestCaseStepsForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 123456788091L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="SERIAL_NUMBER")
private String serialNumber;
#Column(name="TEST_CASE_ID")
private String testCaseId;
#Column(name="INPUT")
private String input;
#Column(name="EXPCETED_OUTPUT")
private String expectedOutput;
#Column(name="STATUS")
private String status;
private TestCaseForm testCaseForm;
public String getTestCaseId() {
return testCaseId;
}
public void setTestCaseId(String testCaseId) {
this.testCaseId = testCaseId;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getExpectedOutput() {
return expectedOutput;
}
public void setExpectedOutput(String expectedOutput) {
this.expectedOutput = expectedOutput;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#ManyToOne( fetch = FetchType.LAZY)
#JoinColumn(name = "TEST_CASE_ID", nullable = false)
public TestCaseForm getTestCaseForm() {
return testCaseForm;
}
public void setTestCaseForm(TestCaseForm testCaseForm) {
this.testCaseForm = testCaseForm;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
}
#Configuration
public class TestCaseConfig {
#Bean(name="testCaseForm1")
public TestCaseForm testCaseForm1(){
TestCaseForm tst = new TestCaseForm();
tst.setTestCaseId("1122233");
tst.setProjectId("1234");
tst.setReleaseName("June");
tst.setReleaseId("1707");
tst.setIteration("2");
tst.setProjectName("ExpressPay");
tst.setTitle("ExpressPay");
tst.setCreatedBy("Anirban Deb");
tst.setCreationDate(new Date());
tst.setDescription("ExpressPay Login");
tst.setPreCondition("Active account");
tst.setPostCondition("success");
TestCaseStepsForm str1 = new TestCaseStepsForm();
str1.setTestCaseId("1122233");
str1.setInput("Hello World");
str1.setExpectedOutput("Bye Bye world");
str1.setStatus("Run");
str1.setTestCaseForm(tst);
TestCaseStepsForm str2 = new TestCaseStepsForm();
str2.setTestCaseId("1122233");
str2.setInput("Hello World");
str2.setExpectedOutput("Bye Bye world");
str2.setStatus("Run");
str1.setTestCaseForm(tst);
tst.getTestCaseStepsform().add(str1);
tst.getTestCaseStepsform().add(str2);
return tst;
}
}
public class Main {
public static void main(String[] args) throws MessagingException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("core-bean.xml");
TestCaseForm test1 = context.getBean("testCaseForm1",TestCaseForm.class);
ITestCaseService testCase = context.getBean("testCaseServiceImp", ITestCaseService.class);
testCase.inserTestCase(test1);
[enter image description here][1]
stopWatch.stop();
System.out.println("Time taken in execution : "+stopWatch.getTotalTimeSeconds());
}
}
You should choose to annotate object properties or getters. Don't use it simultaneously.
Apart, #xl0e answer
You need to correct mapping
#OneToMany(mappedBy = "testCaseForm", cascade = CascadeType.ALL)
public ArrayList<TestCaseStepsForm> getTestCaseStepsform() {
return testCaseStepsform;
}

hibernate many to one annotations - mapping exception

I have to tables book and borrow and I want to have in my Borrow class method to get Book. I have something like this:
#Entity
#Table(name="borrow")
public class Borrow {
#Id
#Column(name="ID")
#GeneratedValue
private Long id;
#Column(name="book_id")
private long bookId;
#Column(name="user_id")
private long userId;
#Column(name="borrow_date")
private Date borrowDate;
#Column(name="return_date")
private Date returnDate;
private Book book;
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
#ForeignKey(name = "id")
public Book getBook() {
return this.book;
}
public void setBook(Book book) {
this.book = book;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Date getBorrowDate() {
return borrowDate;
}
public void setBorrowDate(Date borrowDate) {
this.borrowDate = borrowDate;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
}
In table book I have id field and I want to join by it. Like book.id = borrow.book_id. I get execption:
Could not determine type for: Book, at table: borrow, for columns: [org.hibernate.mapping.Column(book)]
Book class:
#Entity
#Table(name="book")
public class Book {
#Id
#Column(name="ID")
#GeneratedValue
private Long id;
#Column(name="title")
private String title;
#Column(name="author")
private String author;
#Column(name="isbn")
private String isbn;
#Column(name="year")
private String year;
#Column(name="publisher")
private String publisher;
#Column(name="book_url")
private String bookUrl;
#Column(name="review_url")
private String reviewUrl;
#Column(name="status_id")
private int status;
#Column(name="accepted")
private boolean accepted;
#Column(name="in_library")
private boolean inLibrary;
#Column(name="user_id")
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isAccepted() {
return accepted;
}
public void setAccepted(boolean accepted) {
this.accepted = accepted;
}
public boolean isInLibrary() {
return inLibrary;
}
public void setInLibrary(boolean inLibrary) {
this.inLibrary = inLibrary;
}
public Book(long l, String string) {
this.title = string;
this.id = l;
}
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getBookUrl() {
return bookUrl;
}
public void setBookUrl(String bookUrl) {
this.bookUrl = bookUrl;
}
public String getReviewUrl() {
return reviewUrl;
}
public void setReviewUrl(String reviewUrl) {
this.reviewUrl = reviewUrl;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
The issue is that you're mixing field and property access. Your #Id annotation is on a field, so that's where hibernate is looking for book's annotation. From 2.2.2.2. Access type:
The placement of annotations within a class hierarchy has to be
consistent (either field or on property) to be able to determine the
default access type. It is recommended to stick to one single
annotation placement strategy throughout your whole application.
So either keep your annotations consistent (recommended), or use the methods described in the rest of that section to override the access type for book (e.g. by using the #Access annotation)

hibernate gives two rows the same instead of two distinct rows

I have a user dao
#Entity
#Table(name="EBIGUSERTIM")
public class EbigUser {
private String id;
private Integer source;
private String entryscheme;
private String fullName;
private String email;
private Long flags;
private String status;
private String createdBy;
private Date createdStamp;
private String modifiedBy;
private Date modifiedStamp;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
public void setSource(Integer source) {
this.source = source;
}
#Column(name="ENTRYSCHEME")
public String getEntryscheme() {
return entryscheme;
}
public void setEntryscheme(String entryscheme) {
this.entryscheme = entryscheme;
}
#Column(name="FULLNAME")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="FLAGS")
public Long getFlags() {
return flags;
}
public void setFlags(Long flags) {
this.flags = flags;
}
#Column(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="CREATEDBY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name="CREATEDSTAMP")
public Date getCreatedStamp() {
return createdStamp;
}
public void setCreatedStamp(Date createdStamp) {
this.createdStamp = createdStamp;
}
#Column(name="MODIFIEDBY")
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
#Column(name="MODIFIEDSTAMP")
public Date getModifiedStamp() {
return modifiedStamp;
}
public void setModifiedStamp(Date modifiedStamp) {
this.modifiedStamp = modifiedStamp;
}
i am selecting 2 rows out of the db. The sql works
select * from ebigusertim where id='blah'
It returns 2 distinct rows. When i query the data using hibernate, it appears that the object memory is not being allocated for each entry in the list. Thus, i get 2 entries in the list with the same object.
Criteria userCriteria = session.createCriteria(EbigUser.class);
userCriteria.add(Restrictions.eq("id", id));
userlist = userCriteria.list();
Why are you defining two id columns(both id and source are mapped with annotation #Id)?
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
Please remove one if it is by mistake. If both together make composite key, map them accordingly e.g.
#Embeddable
public class UserPK implements Serializable {
#Column(name = "ID", nullable = false)
private String id;
#Column(name = "SOURCE", nullable = false)
private Integer source;
.....
.....
}
Use this new class in you original class as Id as below:
#EmbeddedId
private UserPK userPK;
Hope this helps.

Categories