i have two entity classes named Qa.java and Answeres.java
my Qa entity consists of lists of answers.
Qa.Java
#Entity
#Table(name = "qa")
public class Qa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private String question;
private String type;
private String description;
private String param;
private int maxlength;
#OneToMany(mappedBy = "qa", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Answers> answersList = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
}
Answers.java
#Entity
#Table(name = "answers")
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ans_label;
private int ans_value;
private int ans_weightage;
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "question_id", referencedColumnName = "id",nullable = false)
private Qa qa;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Qa getQa() {
return qa;
}
public void setQa(Qa qa) {
this.qa = qa;
}
}
My controller from where i am trying to insert data.
TableDataController.java
#Controller
public class TabletDataController {
#Autowired
QaRepository qaRepository;
#RequestMapping(value = "/saveApiData", method = RequestMethod.GET)
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
Answers answers1 = new Answers();
answers1.setAns_label("english");
answers1.setAns_value(2);
answers1.setAns_weightage(2);
answers1.setIs_default(2);
Answers answers2 = new Answers();
answers2.setAns_label("japense");
answers2.setAns_value(3);
answers2.setAns_weightage(3);
answers2.setIs_default(3);
answersArrayList.add(answers);
answersArrayList.add(answers1);
answersArrayList.add(answers2);
qa.setAnswersList(answersArrayList);
answers.setQa(qa);
qaRepository.save(qa);
}
}
my qaRepository extends JpaRepository. so whenever i call this api only first object i.e
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
is saved. how can i saved all the given list?
You have to set the qa object to answers1 and answers2 objects as well and not just for the answers object.
Related
I am trying to fetch list of train entities using source and destination properties of route entity which has one to many relationship with each other. The train table having route id as foreign key. The table names are route and train respectively. Please help me as the query is throwing java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.infyrail.app.repository.RouteRepository.findBySourceDestination(java.lang.String,java.lang.String)!
RouteRepository:
public interface RouteRepository extends JpaRepository<RouteEntity, Integer> {
#Query("SELECT t FROM train t JOIN route r WHERE r.source=?1 AND r.destination=?2")
public List<TrainEntity> findBySourceDestination(String source,String destination);
}
RouteEntity:
#Entity
#Table(name="route")
public class RouteEntity {
#Id
#GenericGenerator(name="route_id",
strategy="com.infyrail.app.generator.RouteIdGenerator")
#GeneratedValue(generator = "route_id")
#Min(value = 100)
#Max(value = 999)
Integer id;
String source;
String destination;
#OneToMany(mappedBy = "route",
cascade=CascadeType.ALL,orphanRemoval = true)
private List<TrainEntity> trainList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public List<TrainEntity> getTrainList() {
return trainList;
}
public void setTrainList(List<TrainEntity> trainList) {
this.trainList = trainList;
}
}
TrainEntity:
#Entity
#Table(name="train")
public class TrainEntity {
//#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#GenericGenerator(name="train_id",
strategy="com.infyrail.app.generator.TrainIdGenerator")
#GeneratedValue(generator = "train_id")
#Min(value = 100)
#Max(value = 999)
Integer id;
String trainName;
String arrivalTime;
String departureTime;
Double fare;
#ManyToOne(fetch = FetchType.LAZY)
#Autowired
RouteEntity route;
public RouteEntity getRoute() {
return route;
}
public void setRoute(RouteEntity route) {
this.route = route;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Double getFare() {
return fare;
}
public void setFare(Double fare) {
this.fare = fare;
}
}
Here is the problem. Your query should define the table bean name instead of the actual table name.
In your case you should use TrainEntity instead of train and RouteEntity instead of route.
public interface RouteRepository extends JpaRepository<RouteEntity, Integer> {
#Query("SELECT t FROM TrainEntity t JOIN RouteEntity r WHERE r.source=?1 AND r.destination=?2")
public List<TrainEntity> findBySourceDestination(String source,String destination);
}
I'm working on a web app and one of the task i have to complete is to add an excel import feature that will read an xlsx file and convert it to a list of abstract class.
Converting it to a class is easy and there are many tutorials on how to do it, but there are none on an abstract class.
The abstract class is called AbstractQuestion which represents a questions, and there are multiple type of questions like single choice question, multiple choice question and text question.
Basically, each row of the excel file can be a different type of question and i need to return a list of AbstractQuestion at the end. Moreover, a multiple and single choice question can have up to 10 options.
AbstractQuestion:
#SuppressWarnings("serial")
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "question_type", discriminatorType =
DiscriminatorType.STRING)
public abstract class AbstractQuestion implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="code", nullable=false)
private String code;
#Column(name="question", nullable=false)
private String question;
#Version
private long version;
private #OneToMany(mappedBy="question")
List<AbstractAnswer> answers = new ArrayList<AbstractAnswer>();
public AbstractAnswer currentUserAnswer;
public AbstractQuestion() {
super();
// TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public List<AbstractAnswer> getAnswers() {
return answers;
}
public void setAnswers(List<AbstractAnswer> answers) {
this.answers = answers;
}
public void putCurrentUserAnswer(AbstractAnswer answer) {
this.currentUserAnswer = answer;
}
public abstract void accept(QuestionVisitor q);
public abstract AbstractAnswer createAnswer(User user);
}
Text Question:
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING)
#DiscriminatorValue("Text")
public class TextQuestion extends AbstractQuestion {
public TextQuestion() {
super();
}
#Override
public void accept(QuestionVisitor q) {
q.process(this);
}
public String getType() {
return QuestionUtility.TEXT_QUESTION;
}
#Override
public AbstractAnswer createAnswer(User user) {
TextAnswer answer = new TextAnswer();
answer.setAnswerer(user);
answer.setQuestion(this);
answer.setId(0);
answer.setVersion(0);
answer.setAnswered(false);
return answer;
}
}
Single Choice Question:
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING)
#DiscriminatorValue("SingleChoice")
public class SingleChoiceQuestion extends AbstractQuestion {
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
#JoinTable(name = "singlechoice_options", joinColumns = {
#JoinColumn(name= "parent" )
},inverseJoinColumns = {
#JoinColumn(name = "child")
}
)
private List<Option> options = new ArrayList<Option>();
public SingleChoiceQuestion() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void accept(QuestionVisitor q) {
q.process(this);
}
public String getType() {
return QuestionUtility.SINGLE_CHOICE_QUESTION;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
#Override
public AbstractAnswer createAnswer(User user) {
SingleChoiceAnswer answer = new SingleChoiceAnswer();
answer.setAnswerer(user);
answer.setQuestion(this);
answer.setId(0);
answer.setVersion(0);
answer.setAnswered(false);
return answer;
}
}
Multiple Choice Question:
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING)
#DiscriminatorValue("MultipleChoice")
public class MultipleChoiceQuestion extends AbstractQuestion {
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
#JoinTable(name = "multiplechoice_options", joinColumns = {
#JoinColumn(name= "parent" )
},inverseJoinColumns = {
#JoinColumn(name = "child")
}
)
private List<Option> options = new ArrayList<Option>();
public MultipleChoiceQuestion() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void accept(QuestionVisitor q) {
q.process(this);
}
public String getType() {
return QuestionUtility.MULTIPLE_CHOICE_QUESTION;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
#Override
public AbstractAnswer createAnswer(User user) {
MultipleChoiceAnswer answer = new MultipleChoiceAnswer();
answer.setAnswerer(user);
answer.setQuestion(this);
answer.setId(0);
answer.setVersion(0);
answer.setAnswered(false);
return answer;
}
}
Option:
#SuppressWarnings("serial")
#Entity
#Table(name = "option")
public class Option implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "option", nullable=false)
private String option;
#Column(name = "weight", nullable=false)
private int weight;
#Version
private int version;
public Option() {
super();
// TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
And then let's imagine this excel file:
xlsx file
The goal is to return a list of AbstractQuestion. Is it possible to do it ? If so, how can i do it ? Any possible solution would be appreciated.
Thanks you.
I have three tables which called SLSNotification,SLSWorkflow and Importer These tables are not any relationships... I want to get three tables for jasper report.. So I create a native query for it.. It works fine on MySQL... But when i add it to the SLSWorkflowRepository retrieve only workflow class only.. I want to get other classes also from this repository... I think it retrieves only because i write this like this
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
can i get other classes for SLSIWorkflow getForPrint() methord...
If i wrong please give some onother way...
This is my models
SLSNotification Model
#Entity
#Table(name = "slsnotification")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 16)
private Long snumber;
#Column(length = 100)
private String serialCord;
private String date;
// #JsonFormat(pattern = "yyyy-MM-dd")
// private Date appPostdate = new Date();
#Column(nullable = false)
private String appPostdate;
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20, nullable = false)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
public Long getSnumber() {
return snumber;
}
public void setSnumber(Long snumber) {
this.snumber = snumber;
}
public String getSerialCord() {
return serialCord;
}
public void setSerialCord(String serialCord) {
this.serialCord = serialCord;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCusOffice() {
return cusOffice;
}
public void setCusOffice(String cusOffice) {
this.cusOffice = cusOffice;
}
public String getCusSerial() {
return cusSerial;
}
public void setCusSerial(String cusSerial) {
this.cusSerial = cusSerial;
}
public String getCusDecNo() {
return cusDecNo;
}
public void setCusDecNo(String cusDecNo) {
this.cusDecNo = cusDecNo;
}
public Date getCusDate() {
return cusDate;
}
public void setCusDate(Date cusDate) {
this.cusDate = cusDate;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getExporterAddress() {
return exporterAddress;
}
public void setExporterAddress(String exporterAddress) {
this.exporterAddress = exporterAddress;
}
public String getImporterVAT() {
return importerVAT;
}
public void setImporterVAT(String importerVAT) {
this.importerVAT = importerVAT;
}
public String getDeclarantVAT() {
return declarantVAT;
}
public void setDeclarantVAT(String declarantVAT) {
this.declarantVAT = declarantVAT;
}
public String getVessel() {
return vessel;
}
public void setVessel(String vessel) {
this.vessel = vessel;
}
public String getBlNo() {
return blNo;
}
public void setBlNo(String blNo) {
this.blNo = blNo;
}
public String getLoadingPort() {
return loadingPort;
}
public void setLoadingPort(String loadingPort) {
this.loadingPort = loadingPort;
}
public String getTradingCountry() {
return tradingCountry;
}
public void setTradingCountry(String tradingCountry) {
this.tradingCountry = tradingCountry;
}
public String getCountryOrigin() {
return countryOrigin;
}
public void setCountryOrigin(String countryOrigin) {
this.countryOrigin = countryOrigin;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
public Date getInvoiceDate() {
return invoiceDate;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Double getInvoiceValue() {
return invoiceValue;
}
public void setInvoiceValue(Double invoiceValue) {
this.invoiceValue = invoiceValue;
}
SLSWorkflow Model
#Entity
#Table(name = "sls_wrkflw")
public class SLSIWorkflow {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long SNumber;
private String qc;
private String inv;
private String manuTr;
private String packList;
private String blAttached;
private String otherDoc;
private String otherDocName;
private String ad;
private String MAUsername;
private String appMan;
private String accptdQc;
private String accptTR;
private String manufacturer;
private String validMark;
private String otherDocBoolean;
private String cnfrmtyTest;
private String dtSampling;
private String otherDocDet;
private String adUsername;
private String recom;
private String reaRec;
private String tests;
private String wfStatus;
public Long getSNumber() {
return SNumber;
}
public void setSNumber(Long SNumber) {
this.SNumber = SNumber;
}
public String getQc() {
return qc;
}
public void setQc(String qc) {
this.qc = qc;
}
public String getInv() {
return inv;
}
public void setInv(String inv) {
this.inv = inv;
}
public String getManuTr() {
return manuTr;
}
public void setManuTr(String manuTr) {
this.manuTr = manuTr;
}
public String getPackList() {
return packList;
}
public void setPackList(String packList) {
this.packList = packList;
}
public String getBlAttached() {
return blAttached;
}
public void setBlAttached(String blAttached) {
this.blAttached = blAttached;
}
public String getMaattachUser() {
return maattachUser;
}
public void setMaattachUser(String maattachUser) {
this.maattachUser = maattachUser;
}
public String getMauser() {
return mauser;
}
public void setMauser(String mauser) {
this.mauser = mauser;
}
public String getMareattachUser() {
return mareattachUser;
}
public void setMareattachUser(String mareattachUser) {
this.mareattachUser = mareattachUser;
}
public String getOtherDoc() {
return otherDoc;
}
public void setOtherDoc(String otherDoc) {
this.otherDoc = otherDoc;
}
public String getOtherDocName() {
return otherDocName;
}
public void setOtherDocName(String otherDocName) {
this.otherDocName = otherDocName;
}
}
Importer Model
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
private String importerBrc;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerVatNumber;
#Column(nullable = false)
private String category;
private String importerSVatNumber;
#NotEmpty
private String importerName;
private String importerAddress1;
#NotEmpty
private String officePhoneNumber;
#NotEmpty
private String mobilePhoneNumber;
#Email
#NotEmpty
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
#NotEmpty
private String userIDandTime;
#NotEmpty
private String recentUpdateBy;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {
#JoinColumn(name = "importerId")},
inverseJoinColumns = {
#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getImporterSVatNumber() {
return importerSVatNumber;
}
public void setImporterSVatNumber(String importerSVatNumber) {
this.importerSVatNumber = importerSVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
}
SLSIWorkflowRepository
public interface SLSIWorkflowRepository extends CrudRepository<SLSIWorkflow,Long> {
#Override
SLSIWorkflow save(SLSIWorkflow slsiWorkflow);
#Override
SLSIWorkflow findOne(Long Long);
#Override
boolean exists(Long Long);
#Override
Iterable<SLSIWorkflow> findAll();
#Override
long count();
#Override
void delete(SLSIWorkflow entity);
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
WorkflowServices
public class WorkflowServices {
private static final Logger serviceLogger = LogManager.getLogger(WorkflowServices.class);
private static final String INIT_WORKFLOW_STATUS = "INIT";
#Autowired
private SLSIWorkflowRepository workflowRepository;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private SLSNotificationRepository slsNotificationRepository;
public void initWorkflow(Long slsNumber) {
SLSIWorkflow workflow = new SLSIWorkflow();
workflow.setSNumber(slsNumber);
workflow.setWfStatus(INIT_WORKFLOW_STATUS);
workflowRepository.save(workflow);
}
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
}
Workflow Controller //this is large and i gives my cord only
#RequestMapping(path = "/viewTAXInvoice/{snumber}/{importerVatNumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber, #PathVariable("importerVatNumber") String importerVatNumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(workflowServices.getApplicationForPrint(Long.parseLong(snumber), importerVatNumber)));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println("Dt Source1 "+dataSource);
return new ModelAndView("pdfReportforVAT", parameterMap);
}
How to connect three tables... Please help me someone...
You are getting a SLSIWorkflow only because you are returning that Entity only in the following code in WorkflowServices.
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
If you return an Object it will have all the fields from tables slsnotification, sls_wrkflw, importers as a Object[].
Plus using a Plain JOIN it will result in an INNER JOIN by default. This will not return anything if one joined table doesn't satisfy the ON criteria. It is good if you use LEFT JOIN so that the null will be returned.
I am having alot of issues trying to delete child records using JPA. Consider the mappings below. I am trying to delete all the state data in the jobs table. When it is removed it will cascade all deletes down the chain. Here is the chain:
Job -> State -> TaskState -> Step
When I try to remove state from job table it is set to NULL. However it is not cascaded down the chain. How would I go about achieving this?
Here is how I am deleting the data:
#Transactional
public void runJob(Long id) throws IOException, JAXBException {
Job job = jobRepository.findOne(id);
if(job.getState() != null){
State stateObj = stateRepository.findOne(job.getState().getId());
stateObj.setTasks(null);
stateRepository.delete(stateObj);
}
job.setState(null);
jobRepository.save(job);
}
Jobs:
#Entity
#Table(name = "jobs")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#OneToOne
private Image image;
#OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private State state;
#OneToMany
private List<Task> tasks;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private JobStatusEnum status;
#ManyToMany
private List<Device> devices;
#OneToMany
private List<JobRun> runs;
#OneToMany
private List<Container> containers;
public Job() {
this.image = new Image();
this.status = JobStatusEnum.New;
this.devices = new ArrayList<>();
this.runs = new ArrayList<>();
this.containers = new ArrayList<>();
}
public Job(String name, String description, Date date, Image image, State state, List<Task> tasks, JobStatusEnum status, List<Device> devices, List<JobRun> runs, List<Container> containers) {
this.name = name;
this.description = description;
this.date = date;
this.image = image;
this.state = state;
this.tasks = tasks;
this.status = status;
this.devices = devices;
this.runs = runs;
this.containers = containers;
}
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;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public JobStatusEnum getStatus() {
return status;
}
public void setStatus(JobStatusEnum status) {
this.status = status;
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
public List<JobRun> getRuns() {
return runs;
}
public void setRuns(List<JobRun> runs) {
this.runs = runs;
}
public List<Container> getContainers() {
return containers;
}
public void setContainers(List<Container> containers) {
this.containers = containers;
}
}
State:
#Entity
#Table(name = "state")
public class State implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="name")
private String name;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<TaskState> tasks;
public State() {
tasks = new ArrayList<>();
}
public State(Long id, String name, List<TaskState> tasks) {
this.id = id;
this.name = name;
this.tasks = tasks;
}
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;
}
public List<TaskState> getTasks() {
return tasks;
}
public void setTasks(List<TaskState> tasks) {
this.tasks = tasks;
}
}
TaskState:
#Entity
#Table(name = "task_state")
public class TaskState implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "parent")
private Long parent;
#Column(name = "referenceid")
private Long referenceId;
#Column(name = "name")
private String name;
#Column(name = "status")
private TaskStatusEnum status;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Step> steps;
#Column(name = "maxAttempts")
private Integer maxAttempts;
#ManyToOne
#JsonIgnore
private State state;
public TaskState() {
status = TaskStatusEnum.New;
steps = new ArrayList<>();
maxAttempts = 5;
}
public TaskState(Long id, Long parent, Long referenceId, String name, TaskStatusEnum status, List<Step> steps, Integer maxAttempts) {
this();
this.id = id;
this.parent = parent;
this.referenceId = referenceId;
this.name = name;
this.status = status;
this.steps = steps;
this.maxAttempts = maxAttempts;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TaskStatusEnum getStatus() {
return status;
}
public void setStatus(TaskStatusEnum status) {
this.status = status;
}
public List<Step> getSteps() {
return steps;
}
public void setSteps(List<Step> steps) {
this.steps = steps;
}
public Long getReferenceId() {
return referenceId;
}
public void setReferenceId(Long referenceId) {
this.referenceId = referenceId;
}
public Integer getMaxAttempts() {
return maxAttempts;
}
public void setMaxAttempts(Integer maxAttempts) {
this.maxAttempts = maxAttempts;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
Step:
#Entity
#Table(name = "step")
public class Step implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "groupname")
private String group;
#Column(name = "route")
private String route;
#Column(name = "celerytask")
private String celeryTask;
#Column(name = "postbackqueuename")
private String postBackQueueName;
#Column(name = "postbackerrorqueuename")
private String postBackErrorQueueName;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private TaskStatusEnum status;
#ElementCollection
private List<String> arguements;
#Column(name="runningTaskId")
private Long runningTaskId;
#Column(name="result")
private String result;
#Column(name="attempt")
private Integer attempt;
#JsonIgnore
#ManyToOne
private TaskState task;
public Step() {
arguements = new ArrayList<>();
status = TaskStatusEnum.New;
attempt = 0;
}
public Step(String name, String group, String route, String celeryTask, String postBackQueueName, String postBackErrorQueueName, TaskStatusEnum status, List<String> arguements, Long runningTaskId) {
this();
this.name = name;
this.group = group;
this.route = route;
this.celeryTask = celeryTask;
this.postBackQueueName = postBackQueueName;
this.postBackErrorQueueName = postBackErrorQueueName;
this.status = status;
this.arguements = arguements;
this.runningTaskId = runningTaskId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public String getCeleryTask() {
return celeryTask;
}
public void setCeleryTask(String celeryTask) {
this.celeryTask = celeryTask;
}
public String getPostBackQueueName() {
return postBackQueueName;
}
public void setPostBackQueueName(String postBackQueueName) {
this.postBackQueueName = postBackQueueName;
}
public String getPostBackErrorQueueName() {
return postBackErrorQueueName;
}
public void setPostBackErrorQueueName(String postBackErrorQueueName) {
this.postBackErrorQueueName = postBackErrorQueueName;
}
public List<String> getArguements() {
return arguements;
}
public void setArguements(List<String> arguements) {
this.arguements = arguements;
}
public TaskStatusEnum getStatus() {
return status;
}
public void setStatus(TaskStatusEnum status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Integer getAttempt() {
return attempt;
}
public void setAttempt(Integer attempt) {
this.attempt = attempt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRunningTaskId() {
return runningTaskId;
}
public void setRunningTaskId(Long runningTaskId) {
this.runningTaskId = runningTaskId;
}
public TaskState getTask() {
return task;
}
public void setTask(TaskState task) {
this.task = task;
}
}
It's not cascading because of stateObj.setTasks(null);.
You're breaking the link between the State and its Tasks so when you're deleting the State, the delete doesn't cascade on anything.
I am trying to attach image files to an entity called product. I can create a product along with the image pretty well but when i try to delete an image i get the following error.
HTTP 500 - Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.IJM.model.Product
Product Class
#Entity
#Table(name = "Product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id")
private Long id;
#NotNull
#Size(min = 3, max = 10)
#Column(name = "Code", nullable = false)
private String code;
#NotNull
#Size(min = 3, max = 50)
#Column(name = "Name", nullable = false)
private String name;
#Size( max = 50)
#Column(name = "Description", nullable = false)
private String description;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "Id_Category")
private Category category;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "Id_Unit")
private Unit unit;
#OneToMany(cascade = CascadeType.ALL,
fetch= FetchType.EAGER,
orphanRemoval = true,
mappedBy="product")
private Set<Image> images;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
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;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
if(this.category==null||!this.category.equals(category))
{
this.category=category;
}
return;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
if(this.unit==null||!this.unit.equals(unit))
{
this.unit=unit;
}
return;
}
public Set<Image> getImages() {
return images;
}
public void setImages(Set<Image> images) {
this.images = images;
}
}
Image Class
#Entity
#Table(name = "product_Image")
public class Image {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", nullable = false)
private long id;
#Lob
#Column(name = "File", nullable = false)
private byte[] file;
#Column(name = "Checksum",nullable = false)
private String checksum;
#Column(name = "Extension",nullable = false)
private String extension;
#Column(name = "File_Name",nullable = false)
private String file_name;
#Column(name = "Size",nullable = false)
private int size;
#Column(name = "Last_Updated",nullable = false)
private Timestamp last_Updated;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="Id_Product")
private Product product;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name="Id_Directory")
private Directory directory;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getChecksum() {
return checksum;
}
public void setChecksum(String checksum) {
this.checksum = checksum;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFile_name() {
return file_name;
}
public void setFile_name(String file_name) {
this.file_name = file_name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Timestamp getLast_Updated() {
return last_Updated;
}
public void setLast_Updated(Timestamp last_Updated) {
this.last_Updated = last_Updated;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
And this is the code for the controller calling the deleting method
#RestController
#RequestMapping("/image")
public class ImageController {
#Autowired
ProductService productService;
#Autowired
ImageService imageService;
private static final String productImagePath="C:\\IJM\\Images\\Product\\";
#RequestMapping(value = "/product/{code}", method = RequestMethod.DELETE)
public ResponseEntity<Image> deleteProductImage(#PathVariable("code") String code) {
System.out.println("Fetching & Deleting Image for product " + code);
code = code.toUpperCase();
if (!productService.isProductExist(code)) {
System.out.println("Product with code " + code + " not found");
return new ResponseEntity<Image>(HttpStatus.NOT_FOUND);
}
else
{
Product product = productService.findProductByCode(code);
if(product.getImages()!=null)
{
for(Image image:product.getImages())
{
product.getImages().remove(image);
image.setProduct(null);
imageService.deleteImage(image.getId());
}
productService.saveProduct(product);
try{
File file = new File(productImagePath+code);
if(FileDeleter.removeDirectory(file)){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
return new ResponseEntity<Image>(HttpStatus.NO_CONTENT);
}
}
In case someone else is wondering.. the service just calls the DAO
#Override
public void deleteImage(long id) {
Image image = imageDao.findById(id);
imageDao.delete(image);
}
This is the Dao Class
#Repository("imageDao")
public class ImageDaoImpl extends AbstractDao<Long,Image> implements ImageDao{
#Override
public void delete(Image image) {
super.delete(image);
}
}
This is the code in my abstract DAO class
public void delete(T entity) {
getSession().delete(entity);
}
It seems these line are not in proper order.
product.getImages().remove(image);
image.setProduct(null);
imageService.deleteImage(image.getId());
Also not sure what imageService.deleteImage(image.getId()); is doing. It is not required.
Please try like below.
for(Image image:product.getImages())
{
image.setProduct(null);
product.getImages().remove(image);
}
productService.saveProduct(product);
This should be enough. I know it doesn't make any sense to change the order but It had worked for me.