LEFT JOIN table mapping in hibernate - java

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.websystique.springmvc.model.AssetMakeMaster#0]
I have two entities are as follows:
1. AssetMaster
2. AssetMakeMaster
Above entities are mapped with tables. I want to use left join for above two entities and get the all the data from AssetMaster. Inner query is working fine for above entities but i want get the non matched values also. I have tried but not getting solution yet. Please anyone will give the solution for my problem.
I have tried the below query in mysql it gives me proper result but i want to get result from hibernate entities. Please give me solution for below query:
SELECT * FROM fscassets.asset_master a left join
fscassets.asset_make_master b on a.make=b.id;
/* * To change this license header, choose License Headers in Project
Properties. * To change this template file, choose Tools | Templates
* and open the template in the editor. */ package > >
/** * * #author Amol */
#Entity #Table(name = "asset_master")
public class AssetMaster implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "make", nullable = false)
private int make;
#Column(name = "serialno", nullable = false)
private String serialno;
#Column(name = "specs", nullable = false)
private String specs;
#Column(name = "model", nullable = false)
private String model;
#Column(name = "quantity", nullable = false)
private int quantity;
#Column(name = "purchasedate", nullable = false)
private String purchasedate;
#Column(name = "created_on", nullable = false)
private String createdOnDate;
#Column(name = "remark", nullable = false)
private String remark;
#Column(name = "ipaddress", nullable = false)
private String ipAddress;
#ManyToOne(cascade = CascadeType.ALL)
#Fetch(FetchMode.SELECT)
#JoinColumn(name = "make", updatable = false, insertable = false)
private AssetMakeMaster assetMakeMasterdata;
public AssetMakeMaster getAssetMakeMasterdata() {
return assetMakeMasterdata;
}
public void setAssetMakeMasterdata(AssetMakeMaster assetMakeMasterdata) {
this.assetMakeMasterdata = assetMakeMasterdata;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedOnDate() {
return createdOnDate;
}
public void setCreatedOnDate(String createdOnDate) {
this.createdOnDate = createdOnDate;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public int getMake() {
return make;
}
public void setMake(int make) {
this.make = make;
}
public String getSerialno() {
return serialno;
}
public void setSerialno(String serialno) {
this.serialno = serialno;
}
public String getSpecs() {
return specs;
}
public void setSpecs(String specs) {
this.specs = specs;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getPurchasedate() {
return purchasedate;
}
public void setPurchasedate(String purchasedate) {
this.purchasedate = purchasedate;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
/* * To change this license header, choose License Headers in Project
Properties. * To change this template file, choose Tools | Templates
* and open the template in the editor. */ package > >
/** * * #author Amol */
#Entity
#Table(name = "asset_make_master")
public class AssetMakeMaster implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty
#Column(name = "asset_make_name", unique = true, nullable = false)
private String assetmakename;
#Column(name = "assetgroup", nullable = false)
private int groupid;
#Column(name = "created_on", nullable = false)
private String createdOnDate;
#Column(name = "ipaddress", nullable = false)
private String ipAddress;
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "assetMakeMasterdata")
private List<AssetMaster> assetMakeMasters = new ArrayList<AssetMaster>();
public List<AssetMaster> getAssetMakeMasters() {
return assetMakeMasters;
}
public void setAssetMakeMasters(List<AssetMaster> assetMakeMasters) {
this.assetMakeMasters = assetMakeMasters;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAssetmakename() {
return assetmakename;
}
public void setAssetmakename(String assetmakename) {
this.assetmakename = assetmakename;
}
public int getGroupid() {
return groupid;
}
public void setGroupid(int groupid) {
this.groupid = groupid;
}
public String getCreatedOnDate() {
return createdOnDate;
}
public void setCreatedOnDate(String createdOnDate) {
this.createdOnDate = createdOnDate;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
}

You can't use (*) in HQL query. If you want non matched values also then select that columns individually you will get values.

the problem is a that you are fetching a AssetMaster that has the AssetMakeMaster id setted, but the AssetMakeMaster with the setted id is not in database anymore.

Related

Execution Batch file in Spring Batch

i have project for school, in my project I want to do a run the automatic and periodic execution of tasks like Windows task scheduler, But I didn't find the correct code do that. I do this business class, but which step i do for schedule the job?
how can i run the batch file and schedule the jobs ?
Please who can help me.
#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 = "description", length = 100, nullable = false)
private String description;
#Column(name = "scriptFile", length = 100, nullable = false)
private String scriptFile;
#Column(name = "date_execution", length = 20,nullable = false)
private Date date_execution;
#Column(name = "temps_execution", length = 100, nullable = false)
private Date temps_execution;
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScriptFile() {
return script;
}
public void setScriptFile(String script) {
this.script = script;
}
public Date getDate_exécution() {
return date_execution;
}
public void setDate_exécution(Date date_execution) {
this.date_execution = date_execution;
}
public Date getTemps_exécution() {
return temps_execution;
}
public void setTemps_exécution(Date temps_execution) {
this.temps_execution = temps_execution;
}
public Task(Integer id, String nom_job, String description, String scriptFile, Date
date_execution, Date temps_execution ) {
super();
this.id=id;
this.nom_job = nom_job;
this.description = description;
this.scriptFile = scriptFile;
this.date_execution = date_execution;
this.temps_execution = temps_execution;
}
}

How to POST ArrayList to spring boot H2 DB

Im getting the following error:
{"timestamp":1535929757444,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.DataIntegrityViolationException","message":"could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.WT_TASK(TASK_ID)\"; SQL statement:\ninsert into wt_task (exercise_id, task_id) values (?, ?) [23505-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement","path":"/api/word-transformation/new"}
I was able to create a service to fetch JSON from the database but I cant manage to upload them.
This is my service:
public WordTransformationExercise save(WordTransformationExerciseRequest wtRequest) {
WordTransformationExercise wordTransformation = new WordTransformationExercise();
wordTransformation.setAuthorId(wtRequest.getAuthor_id());
List<WordTransformationTaskRequest> testP = wtRequest.getwt_task();
List<WordTransformation> thisIsIt = new ArrayList<WordTransformation>();
for(WordTransformationTaskRequest task : testP) {
WordTransformation send = new WordTransformation();
send.setBody(task.getBody());
send.setResult(task.getResult());
send.setWord(task.getWord());
send.setWordAtIndex(task.getWord_at_index());
thisIsIt.add(send);
}
wordTransformation.setwt_task(thisIsIt);
this.wtRepository.save(wordTransformation);
return wordTransformation;
}
This is my Entity:
#Entity
#Table(name = "wt_exercise")
public class WordTransformationExercise implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "author_id")
private Long authorId;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "wt_task",
joinColumns = #JoinColumn(name = "exercise_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "task_id", referencedColumnName = "task_id"))
private List<WordTransformation> wt_task;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public void setwt_task(List<WordTransformation> list) {
this.wt_task = list;
}
public Collection<?> getwt_task() {
return this.wt_task;
}
}
This is Task entity:
#Entity
#Table(name = "wt_task")
public class WordTransformation implements Serializable {
#Id
#Column(name = "task_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long task_id;
#Column(name = "body")
private String body;
#Column(name = "result")
private String result;
#Column(name = "word")
private String word;
#Column(name = "word_at_index")
private Integer wordAtIndex;
#Column(name = "exercise_id")
private Long exercise_id;
public void setExercise_id(Long exercise_id) {
this.exercise_id = exercise_id;
}
public Long getExercise_id() {
return exercise_id;
}
public void setId(Long task_id) {
this.task_id = task_id;
}
public Long getId() {
return task_id;
}
public void setBody(String body) {
this.body = body;
}
public String getBody() {
return body;
}
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
public void setWord(String word) {
this.word = word;
}
public String getWord() {
return word;
}
public void setWordAtIndex(Integer wordAtIndex) {
this.wordAtIndex = wordAtIndex;
}
public Integer getWordAtIndex() {
return wordAtIndex;
}
}
My API is returning 'id' and 'authorId' fine when I set wt_task to null
This is an example of my sql:
INSERT INTO wt_exercise (id, author_id) VALUES (2, 2);
INSERT INTO wt_task (body, result, word, word_at_index, exercise_id, task_id) VALUES ('please start ', 'running', 'run', 13, 2, 2);
It depends on what you are trying to do.
If you are trying to update an existing entity, you should retrieve it from your repository and set the values instead of creating a new object and trying to save it with an existing key.
If you are trying to create something new then don't set the key at all.

Hibernate mappedBy and ManyToMany

I'm starting from scratch a new project and i got this problem which i cannot solve. I have three entities, and they all have a manytomany relationship with each other. There is the Cluster:
#Entity
#Component
#Table(name = "clusterEntity")
public class Cluster {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
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;
}
#ManyToMany
#JoinTable(name="cluster_user",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_cluster;
#ManyToMany
#JoinTable(name="cluster_sito",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"))
private List<Sito> sitos;
#Override
public String toString() {
return "Cluster{" +
"id=" + id +
", name='" + name +
", users='" + users_cluster.toString() +
'}';
}
}
This is the User:
#Entity
#Component
#Table(name = "userEntity")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "password_hash", nullable = false)
private String passwordHash;
#Column(name = "role", nullable = false)
#Enumerated(EnumType.STRING)
private Role role;
#Column(name = "G1", nullable = true)
private String G1;
#Column(name = "G2", nullable = true)
private String G2;
#Column(name = "G3", nullable = true)
private String G3;
#Column(name = "G4", nullable = true)
private String G4;
#Column(name = "G5", nullable = true)
private String G5;
#Column(name = "G6", nullable = true)
private String G6;
#Column (name = "access_token", nullable = true)
private String access_token;
#Column (name = "refresh_token", nullable = true)
private String refresh_token;
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getG1() {
return G1;
}
public void setG1(String g1) {
G1 = g1;
}
public String getG2() {
return G2;
}
public void setG2(String g2) {
G2 = g2;
}
public String getG3() {
return G3;
}
public void setG3(String g3) {
G3 = g3;
}
public String getG4() {
return G4;
}
public void setG4(String g4) {
G4 = g4;
}
public String getG5() {
return G5;
}
public void setG5(String g5) {
G5 = g5;
}
public String getG6() {
return G6;
}
public void setG6(String g6) {
G6 = g6;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
#ManyToMany(mappedBy="users_cluster")
private List<User> users_cluster;
#ManyToMany(mappedBy="users_sito")
private List<User> users_sito;
public User(){}
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email.replaceFirst("#.*", "#***") +
", passwordHash='" + passwordHash.substring(0, 10) +
", role=" + role +
'}';
}
}
This is the Sito:
#Entity
#Component
#Table(name = "sitoEntity")
public class Sito {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
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;
}
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_sito;
#Override
public String toString() {
return "Sito{" +
"id=" + id +
", name='" + name+
", users='" + users_sito.toString()+
'}';
}
}
When i try compiling with maven i get the following error about mappedBY, as if it was written on both side of the relation, but in fact it is written only on one side:
Caused by: org.hibernate.AnnotationException: Illegal use of mappedBy on both sides of the relationship: User.users_cluster
Anyone has any ideaof what am i doing wrong?
Clustor
As far as I can see the Cluster entity is annotated correctly except some kine of naming convention. Instead of
private List<User> users_cluster;
I would recommend using
private List<User> users;
The list contains users so it should be named to reflect that; good naming is the best documentation, (imo).
User
This entity seems to be correctly annotated but the references are wrong as they are self referencing. So the entity should be modified as follows if you want to create a many-to-many relationship between the thre entities:
public class User {
// ...
#ManyToMany(mappedBy="users")
private List<Cluster> clusters;
#ManyToMany(mappedBy="users")
private List<Sito> sitos;
// getters + setters
}
Sito
Here too I made a small modification as follows:
public class Sito {
// ...
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users;
#ManyToMany(mappedBy = "sitos")
private List<Cluster> clusters;
// getters + setters
}
Now your three entities should be related to each other as you desired.

Use join and subquery with criteria in hibernate

I searched lot. But can't find solution for my case. i want create hibernate criteria for following query.
SELECT * FROM patient as p1 LEFT OUTER JOIN (SELECT * FROM patient_caller_admin_map WHERE caller_admin_id='1') as pca ON p1.patient_id=pca.patient_id;
i went through the DetachedCriteria , Criteria and created the following things. But don't know how to use LEFT_JOIN by joining both.
DetachedCriteria inner=DetachedCriteria.forClass(PatientCallerAdminMap.class, "patientCallerAdmin");
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
PatientCallerAdminMap Entity:
/**
* PatientCallerAdminMap generated by hbm2java
*/
#Entity
#Table(name = "patient_caller_admin_map", catalog = "test")
public class PatientCallerAdminMap implements java.io.Serializable {
private PatientCallerAdminMapId id;
private CallerAdmin callerAdmin;
private Caller caller;
private Patient patient;
private String notes;
private Integer isArchived;
private Integer patientStatus;
private Set<CallLog> callLogs = new HashSet<CallLog>(0);
private Set<CallLog> callLogs_1 = new HashSet<CallLog>(0);
public PatientCallerAdminMap() {
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Patient patient) {
this.id = id;
this.callerAdmin = callerAdmin;
this.patient = patient;
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Caller caller, Patient patient,
String notes, Integer isArchived, Integer patientStatus,
Set<CallLog> callLogs, Set<CallLog> callLogs_1) {
this.id = id;
this.callerAdmin = callerAdmin;
this.caller = caller;
this.patient = patient;
this.notes = notes;
this.isArchived = isArchived;
this.patientStatus = patientStatus;
this.callLogs = callLogs;
this.callLogs_1 = callLogs_1;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "patientId", column = #Column(name = "patient_id", nullable = false)),
#AttributeOverride(name = "callerAdminId", column = #Column(name = "caller_admin_id", nullable = false)) })
public PatientCallerAdminMapId getId() {
return this.id;
}
public void setId(PatientCallerAdminMapId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_admin_id", nullable = false, insertable = false, updatable = false)
public CallerAdmin getCallerAdmin() {
return this.callerAdmin;
}
public void setCallerAdmin(CallerAdmin callerAdmin) {
this.callerAdmin = callerAdmin;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_id")
public Caller getCaller() {
return this.caller;
}
public void setCaller(Caller caller) {
this.caller = caller;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id", nullable = false, insertable = false, updatable = false)
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
#Column(name = "notes", length = 600)
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Column(name = "is_archived")
public Integer getIsArchived() {
return this.isArchived;
}
public void setIsArchived(Integer isArchived) {
this.isArchived = isArchived;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs() {
return this.callLogs;
}
public void setCallLogs(Set<CallLog> callLogs) {
this.callLogs = callLogs;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs_1() {
return this.callLogs_1;
}
public void setCallLogs_1(Set<CallLog> callLogs_1) {
this.callLogs_1 = callLogs_1;
}
}
Patient Entity Class:
#Entity
#Table(name = "patient", catalog = "test")
public class Patient implements java.io.Serializable {
private String patientId;
private String addedDate;
private String name;
private String dateOfBirth;
private String gender;
private String address;
private String phoneNumber;
private Integer tier;
private Integer patientStatus;
private Integer status;
private Set<PatientCallerAdminMap> patientCallerAdminMaps = new HashSet<PatientCallerAdminMap>(
0);
public Patient() {
}
public Patient(String patientId) {
this.patientId = patientId;
}
public Patient(String patientId,String addedDate, String timeOfCrash,
String name, String dateOfBirth, String gender,
String address,
String phoneNumber,Integer tier, Integer patientStatus,
Integer status,
Set<PatientCallerAdminMap> patientCallerAdminMaps,
) {
this.patientId = patientId;
this.addedDate = addedDate;
this.name = name;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.address = address;
this.phoneNumber = phoneNumber;
this.tier=tier;
this.patientStatus = patientStatus;
this.status = status;
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
#Id
#Column(name = "patient_id", unique = true, nullable = false)
public String getPatientId() {
return this.patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
#Column(name = "added_date", length = 45)
public String getAddedDate() {
return addedDate;
}
public void setAddedDate(String addedDate) {
this.addedDate = addedDate;
}
#Column(name = "name", length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "date_of_birth", length = 45)
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Column(name = "gender", length = 5)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name = "address", length = 200)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "phone_number", length = 20)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "tier")
public Integer getTier() {
return this.tier;
}
public void setTier(Integer tier) {
this.tier = tier;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#Column(name = "status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patient")
public Set<PatientCallerAdminMap> getPatientCallerAdminMaps() {
return this.patientCallerAdminMaps;
}
public void setPatientCallerAdminMaps(
Set<PatientCallerAdminMap> patientCallerAdminMaps) {
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
}
Please help to solve this.
Maybe you can achieve this without using subquery so the query become simpler :
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
cr2=cr1.createCriteria("patientCallerAdminMaps ",CriteriaSpecification.LEFT_JOIN);
cr3= cr2.createCriteria("callerAdmin",CriteriaSpecification.LEFT_JOIN);
cr3.add(Restrictions.eq("id", "1"));
For the "select *" you can't do it with criteria. This criteria will return a list of Patient entity.
If really want * you will have to add alias on subcriteria and use Projection to select explicitly the fields that you want

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()

I got the above error though i have set the ID manually, Im not using auto generated key here.
when i set the key and pass the object to
entityManager.persist(obj);
it gives the above error.
any help... plz
thanks
This is the InstallationInfo class, and I got the above error when persisting the installationInfo object. The complete error is
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): se.cambio.cimonitor.jpa.table.ModuleInfo
so I have attached the ModuleInfo class as well
package se.cambio.cimonitor.jpa.table;
#Entity
#Table(name = "InstallationInfo", catalog="CI_Monitor", schema="dbo")
public class InstallationInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String installationId;
private String timestamp;
private Module moduleByParentId;
private Environment environmentByEnvironmentClientId;
private Environment environmentByEnvironmentServerId;
private Module moduleByBaseLineId;
private String machineName;
private String status;
private String teamName;
private Set<ModuleInfo> moduleInfos = new HashSet<ModuleInfo>(0);
public InstallationInfo() {
}
public InstallationInfo(String installationId) {
this.installationId = installationId;
}
public InstallationInfo(String installationId,
Module moduleByParentId,
Environment environmentByEnvironmentClientId,
Environment environmentByEnvironmentServerId,
Module moduleByBaseLineId, String machineName,
String status, String teamName,
Set<ModuleInfo> moduleInfos) {
this.installationId = installationId;
this.moduleByParentId = moduleByParentId;
this.environmentByEnvironmentClientId = environmentByEnvironmentClientId;
this.environmentByEnvironmentServerId = environmentByEnvironmentServerId;
this.moduleByBaseLineId = moduleByBaseLineId;
this.machineName = machineName;
this.status = status;
this.teamName = teamName;
this.moduleInfos = moduleInfos;
}
/*#TableGenerator(name="InstlIds", table="InstlPkTb", pkColumnName="InstlId", pkColumnValue="InstlIdVal", allocationSize=1, catalog="CI_Monitor", schema="dbo")
#GeneratedValue(strategy=GenerationType.TABLE, generator="InstlIds")*/
#Id
#Column(name = "InstallationId", unique = true, nullable = false, insertable = true, updatable = true)
public String getInstallationId() {
return this.installationId;
}
public void setInstallationId(String installationId) {
this.installationId = installationId;
}
//#Version This is a bug
#Column(name = "Timestamp")
public String getTimestamp() {
return this.timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ParentId")
public Module getModuleByParentId() {
return this.moduleByParentId;
}
public void setModuleByParentId(Module moduleByParentId) {
this.moduleByParentId = moduleByParentId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EnvironmentClientId")
public Environment getEnvironmentByEnvironmentClientId() {
return this.environmentByEnvironmentClientId;
}
public void setEnvironmentByEnvironmentClientId(
Environment environmentByEnvironmentClientId) {
this.environmentByEnvironmentClientId = environmentByEnvironmentClientId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EnvironmentServerId")
public Environment getEnvironmentByEnvironmentServerId() {
return this.environmentByEnvironmentServerId;
}
public void setEnvironmentByEnvironmentServerId(
Environment environmentByEnvironmentServerId) {
this.environmentByEnvironmentServerId = environmentByEnvironmentServerId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BaseLineId")
public Module getModuleByBaseLineId() {
return this.moduleByBaseLineId;
}
public void setModuleByBaseLineId(Module moduleByBaseLineId) {
this.moduleByBaseLineId = moduleByBaseLineId;
}
#Column(name = "MachineName")
public String getMachineName() {
return this.machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
#Column(name = "Status")
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name = "TeamName")
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "installationInfo", targetEntity=ModuleInfo.class, cascade={CascadeType.ALL}) //targerEntity is added by Isuru
public Set<ModuleInfo> getModuleInfos() {
return this.moduleInfos;
}
public void setModuleInfos(Set<ModuleInfo> moduleInfos) {
this.moduleInfos = moduleInfos;
}
}
package se.cambio.cimonitor.jpa.table;
#Entity
#Table(name = "ModuleInfo", catalog="CI_Monitor", schema="dbo")
public class ModuleInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private ModuleInfoId id;
private InstallationInfo installationInfo;
private Module moduleByModuleId;
private Module moduleByParentId;
private Module moduleByBaseLineId;
private String buildNo;
private String svnRevision;
public ModuleInfo() {
}
public ModuleInfo(ModuleInfoId id, InstallationInfo installationInfo,
Module moduleByModuleId) {
this.id = id;
this.installationInfo = installationInfo;
this.moduleByModuleId = moduleByModuleId;
}
public ModuleInfo(ModuleInfoId id, InstallationInfo installationInfo,
Module moduleByModuleId, Module moduleByParentId,
Module moduleByBaseLineId, String buildNo,
String svnRevision) {
this.id = id;
this.installationInfo = installationInfo;
this.moduleByModuleId = moduleByModuleId;
this.moduleByParentId = moduleByParentId;
this.moduleByBaseLineId = moduleByBaseLineId;
this.buildNo = buildNo;
this.svnRevision = svnRevision;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "moduleId", column = #Column(name = "ModuleId", nullable = false)),
#AttributeOverride(name = "installationId", column = #Column(name = "InstallationId", nullable = false)) })
public ModuleInfoId getId() {
return this.id;
}
public void setId(ModuleInfoId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "InstallationId", nullable = false, insertable = false, updatable = false, unique = true)
public InstallationInfo getInstallationInfo() {
return this.installationInfo;
}
public void setInstallationInfo(InstallationInfo installationInfo) {
this.installationInfo = installationInfo;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ModuleId", nullable = false, insertable = false, updatable = false)
public Module getModuleByModuleId() {
return this.moduleByModuleId;
}
public void setModuleByModuleId(Module moduleByModuleId) {
this.moduleByModuleId = moduleByModuleId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ParentId")
public Module getModuleByParentId() {
return this.moduleByParentId;
}
public void setModuleByParentId(Module moduleByParentId) {
this.moduleByParentId = moduleByParentId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BaseLineId")
public Module getModuleByBaseLineId() {
return this.moduleByBaseLineId;
}
public void setModuleByBaseLineId(Module moduleByBaseLineId) {
this.moduleByBaseLineId = moduleByBaseLineId;
}
#Column(name = "BuildNo")
public String getBuildNo() {
return this.buildNo;
}
public void setBuildNo(String buildNo) {
this.buildNo = buildNo;
}
#Column(name = "SvnRevision")
public String getSvnRevision() {
return this.svnRevision;
}
public void setSvnRevision(String svnRevision) {
this.svnRevision = svnRevision;
}
}
You have a cascade all on ModuleInfos collection, so when you save InstallationInfo it will try to save all the associated ModuleInfos. You need to make sure that the ids of the ModuleInfos are set before saving the InstallationInfo object.
#OneToMany(fetch = FetchType.EAGER, mappedBy = "installationInfo",
targetEntity=ModuleInfo.class, cascade={CascadeType.ALL}) //targerEntity is added by Isuru
public Set<ModuleInfo> getModuleInfos() {
return this.moduleInfos;
}

Categories