Merge JPA is inserting instead of updating - spring

Hi everyone I have this issue with merge (jpa) , first of all I read all the answers about my problem but non of theme helped me to find out a solution.
well I have a table resultat that I want to merge in my managedbean(jsf) but when I do that , I get a another row inserted
package com.journaldev.jpa.data;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name="Resultat")
public class Resultat {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int resultatID;
#ManyToOne
#JoinColumn(name="personneID")
private Etudiant etudiant;
#ManyToOne
#JoinColumn(name="testID")
private Test test;
#Column
private boolean passer;
#Column
private int resultat;
#Temporal(TemporalType.DATE)
#Column
private Date date_passage;
public int getResultatID() {
return resultatID;
}
public void setResultatID(int resultatID) {
this.resultatID = resultatID;
}
public Etudiant getEtudiant() {
return etudiant;
}
public void setEtudiant(Etudiant etudiant) {
this.etudiant = etudiant;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public boolean isPasser() {
return passer;
}
public void setPasser(boolean passer) {
this.passer = passer;
}
public int getResultat() {
return resultat;
}
public void setResultat(int resultat) {
this.resultat = resultat;
}
public Date getDate_passage() {
return date_passage;
}
public void setDate_passage(Date date_passage) {
this.date_passage = date_passage;
}
}
And my service class is
public Resultat findRes(int id)
{
return this.em.find(Resultat.class,id);
}
#Transactional
public Resultat updateR(Resultat emp) {
// Save Personne
return this.em.merge(emp);
}
and this is how i use it in my managedbean
Resultat res = testService.findRes(1);
System.out.println("hahowa"+res.getResultatID());
res.setResultatID(score);
res.setPasser(true);
res= testService.updateR(res);

Related

Getting null value in h2 database when using spring boot

I am trying to insert data into the h2 database taking input from user.But primary key is getting inserted but the other is stored as null.
Here is my application.properties
spring.sql.init.platform==h2
spring.datasource.url=jdbc:h2:mem:preethi
spring.jpa.defer-datasource-initialization: true
spring.jpa.hibernate.ddl-auto=update
Here is Controller class AlienController.java
package com.preethi.springbootjpa.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.preethi.springbootjpa.model.Alien;
import com.preethi.springbootjpa.repo.AlienRepo;
#Controller
public class AlienController {
#Autowired
AlienRepo repo;
#RequestMapping("/")
public String home()
{
return "home.jsp";
}
#RequestMapping("/addAlien")
public String addAlien( Alien alien)
{
repo.save(alien);
return "home.jsp";
}
}
Here is Alien.java
package com.preethi.springbootjpa.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Alien {
#Id
private int aid;
private String aname;
public Alien()
{
}
public Alien(int aid, String aname) {
super();
this.aid = aid;
this.aname = aname;
}
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getName() {
return aname;
}
public void setName(String name) {
this.aname = name;
}
#Override
public String toString() {
return "Alien [aid=" + aid + ", name=" + aname + "]";
}
}
Here is AlienRepo.java
package com.preethi.springbootjpa.repo;
import org.springframework.data.repository.CrudRepository;
import com.preethi.springbootjpa.model.Alien;
public interface AlienRepo extends CrudRepository<Alien,Integer>{
}
Here is data.sql;
insert into alien values(101,'Preethi');
when I try to insert data from data.sql,it is getting inserted but when I try to insert data taking input from user, data is stored as null(except primary key).
Here is the table :
table
I got the same issue when i forgot to add the gettters and setters for an entity class.
Finally solved it, there is no problem with the code...It's just all the configuraton things that messed up.
Just did everything from scratch and took care of build path and configurations.
Solved..

Null values needs to be displayed in Mongo DB through POJO class

I have a Spring batch application written on top of spring boot framework, it is used to read data from oracle database(using JDBCcursorItemreader) and write to Mongo Database(MongoItemWriter).For each table i'm having a POJO class .Null value field not displaying in mongo collection.By default searilaization omitting the null value columns are omitting and displaying only the non null columns.
is there any other property to include the null fields in mongo DB?
ex: Oracle table
Mongo Collection:
{
"Name":"xyz",
"Number":"16"
}
Want below format:
{
"Name":"xyz",
"Number":"16",
"Date" : null
}
I want to display the date column in mongo DB.I have tried with jsoninclude properties.it is not working. Can anyone suggest on this?
My Code:
Batch File:
package com.sam.oracletomongo;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.job.flow.support.SimpleFlow;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.partition.PartitionHandler;
import org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler;
import org.springframework.batch.item.data.MongoItemWriter;
import org.springframework.batch.item.data.builder.MongoItemWriterBuilder;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.batch.item.database.support.ListPreparedStatementSetter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.mongodb.core.MongoTemplate;
#Configuration
#EnableBatchProcessing
#Import(AdditionalBatchConfiguration.class)
public class BABatchConfig {
#Autowired
public DataSource datasource;
#Autowired
public MongoTemplate mongotemplate;
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
#StepScope
public JdbcCursorItemReader<BA> itemReaderBA(#Value("#{jobParameters[deltadate]}") String deltadate,#Value("#{jobParameters[rundate]}") String rundate) {
ListPreparedStatementSetter listPreparedStatementSetter = new ListPreparedStatementSetter();
List<String> l1=new ArrayList<String>();
l1.add(deltadate);
l1.add(rundate);
listPreparedStatementSetter.setParameters(l1);
return new JdbcCursorItemReaderBuilder<BA>()
.dataSource(datasource) // change accordingly if you use another data source
.name("fooReader")
.sql("SELECT SA_NO,SA_NAME,DATE1,DATE2,DATE3,ACTIVE FROM SAMPLE WHERE DATE2 between TO_DATE(?,'YYYY-MM-DD') and TO_DATE(?, 'YYYY-MM-DD')")
.rowMapper(new BARowMapper())
.preparedStatementSetter(listPreparedStatementSetter)
.build();
}
#Bean
public MongoItemWriter<BA> writerBA(MongoTemplate mongoTemplate) {
return new MongoItemWriterBuilder<BA>().template(mongoTemplate).collection("BA")
.build();
}
#Bean
public Job BAJob() {
return jobBuilderFactory.get("BA")
.incrementer(new CustomParametersIncrementerImpl(datasource))
.start(BAstep())
.build();
}
#Bean
public Step BAstep() {
return stepBuilderFactory.get("BAStep1")
.<BA, BA> chunk(10)
.reader(itemReaderBA(null,null))
.writer(writerBA(mongotemplate))
.build();
}
}
Model Class:
package com.sam.oracletomongo;
public class BA {
private String _id;
private String saNo;
private String saName;
private String Date1;
private String Date2;
private String Date3;
private String active;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getsaNo() {
return saNo;
}
public void setBaNo(String saNo) {
this.saNo = saNo;
}
public String getsaName() {
return saName;
}
public void setBaName(String saName) {
this.saName = saName;
}
public String getDate1() {
return Date1;
}
public void setDate1(String Date1) {
this.Date1 = Date1;
}
public String getDate2() {
return Date2;
}
public void setDate2(String Date2) {
this.Date2 = Date2;
}
public String getDate3() {
return Date3;
}
public void setDate3(String Date3) {
this.Date3 = Date3;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
#Override
public String toString() {
return "BA [_id=" + _id + ", saNo=" + saNo + ", saName=" + saName + ", Date1=" + Date1 + ", Date2="
+ Date2 + ", Date3=" + Date3 + ", active=" + active + "]";
}
}
Mapper Class:
package com.sam.oracletomongo;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class BARowMapper implements RowMapper<BA> {
public BA mapRow(ResultSet rs, int rowNum) throws SQLException
{
BA ba = new BA();
String id=rs.getString("sA_NO");
ba.set_id(id);
ba.setsaNo(rs.getString("sA_NO"));
ba.setsaName(rs.getString("sA_NAME"));
ba.setDate1(rs.getString("DATE1"));
ba.setDate2(rs.getString("DATE2"));
ba.setDate3(rs.getString("DATE3"));
ba.setActive(rs.getString("ACTIVE"));
return ba;
}
}
This $project stage can help you:
{
"$project": {
_id: 0,
"name": 1,
"number": 1,
"Date": {
"$ifNull": [
"$Date", //If the Date field is not null
"null" //If the Date field is null write string 'null' to the field
]
}
}
}

form:select does not set the selected value

Basically I need a CRUD application for payments. Each payment is assigned to one account.
My jsp page shows the correct list of "account" objects but it does not set the selected account.
Question: How can I achieve a dropdown box with the assigned account pre-selected?
Question: The assignment (account to payment) works, but only with the below code in my PaymentDaoImpl.java (marked as workaround). Why is this the case?
PaymentDaoImpl.java
..
#Override
#Transactional
public int insertRow(Payment obj) {
// Session session = HibernateUtil.getSessionFactory().openSession();
Session session = sessionFactory.openSession();
// !!!! workaround?? If I don't do this, account won't be assigned
int accountId = obj.getAccount().getId();
Account account = (Account) session.get(Account.class, accountId);
obj.setAccount(account);
Transaction tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
Serializable id = session.getIdentifier(obj);
session.close();
return (Integer) id;
}
..
jsp:
<form:select path="account.id" >
<form:option value="-1" label="Select Account" />
<form:options items="${accountList}" itemValue="id" itemLabel="iban" />
</form:select>
Domain Account.java:
package com.beingjavaguys.domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.*;
import org.springframework.beans.factory.annotation.Autowired;
#Entity
public class Account {
#Id
#GeneratedValue
private int id;
private String iban;
private String bank;
private String beschreibung;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getBank() {
return bank;
}
public void setBank(String bank) {
this.bank = bank;
}
public String getBeschreibung() {
return beschreibung;
}
public void setBeschreibung(String beschreibung) {
this.beschreibung = beschreibung;
}
}
Domain Payment
package com.beingjavaguys.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.beans.factory.annotation.Autowired;
#Entity
public class Payment {
private int id;
private Account account;
private float amount;
private String text;
private String comment;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL, targetEntity = Account.class, fetch=FetchType.EAGER)
#JoinColumn(name="fk_account")
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
PaymentController.java
package com.beingjavaguys.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.beingjavaguys.domain.Payment;
import com.beingjavaguys.services.AccountService;
import com.beingjavaguys.services.PaymentService;
#Controller
#RequestMapping("/payment")
public class PaymentController {
#Autowired
PaymentService dataService;
#Autowired
AccountService accountService;
#RequestMapping("form")
public ModelAndView getForm(#ModelAttribute Payment obj) {
ModelAndView mav = new ModelAndView("payment/form");
mav.addObject("accountList", accountService.getList());
return mav;
}
#RequestMapping("insert")
public ModelAndView insert(#ModelAttribute Payment obj) {
dataService.insertRow(obj);
return new ModelAndView("redirect:list");
}
#RequestMapping("list")
public ModelAndView getList() {
List objList = dataService.getList();
return new ModelAndView("payment/list","objList",objList);
}
#RequestMapping("delete")
public ModelAndView deleteUser(#RequestParam int id) {
dataService.deleteRow(id);
return new ModelAndView("redirect:list");
}
#RequestMapping("edit")
public ModelAndView editUser(#RequestParam int id,#ModelAttribute Payment obj) {
ModelAndView mav = new ModelAndView("payment/form");
Payment paymentObj = dataService.getRowById(id);
mav.addObject("accountList", accountService.getList());
mav.addObject("paymentObj", paymentObj);
return mav;
}
#RequestMapping("update")
public ModelAndView updateUser(#ModelAttribute Payment obj) {
dataService.updateRow(obj);
return new ModelAndView("redirect:list");
}
}
Can you have a look on my implementation of the AccountEditor? I need the AccountService to lookup the account, or not? However, I don't get the service instantiated here..
public class AccountEditor extends PropertyEditorSupport {
#Autowired
AccountService dataService; // == null ??
#Override
public void setAsText(String text) {
Account account = lookupAccount(text); // lookup account by accountId
// text
setValue(account);
}
private Account lookupAccount(String text) {
int id = Integer.parseInt(text);
return dataService.getRowById(id);
}
}
What you need is a PropertyEditor implementation to convert from a String accountId to an Account object. Then in your jsp you use the path form:select path="account" instead of form:select path="account.id"
Implement a PropertyEditor as follows
public class AccountEditor extends PropertyEditorSupport{
#Override
public void setAsText(String text){
Account account = lookupAccount(text); //lookup account by accountId text
setValue(account);
}
}
Then register your AccountEditor in your controller
#InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Account.class , new AccountEditor());
}
With the above changes you wont need your workaround. Your solution is only setting the id property of the account and not the whole object

Relationship issue on neo4j.ogm using spring boot application

In my project i am using org.neo4j.ogm with spring boot. While i am trying to create a relationship using #RelationshipEntity means it will created successfully. But it does not support multiple to one relation.
Here i am creating relationship for Blueprint to ScTaxonomy at the relationship on RELATED_TO_ScTaxonomy. And i want to add relationship properties for catalogueBlueprint class.
I mean Blueprint-(RELATED_TO_ScTaxonomy)-ScTaxonomy with catalogueBlueprint class values was saved on RELATED_TO_ScTaxonomy.
once i restart the service then i'll create a new connection means already created relations are lost and only the newly created relations only saved.
I am using the query for
package nuclei.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.neo4j.ogm.annotation.Relationship;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Blueprint extends Entity {
private String blueprint;
private String onIaas;
private String script;
private String isDeleted;
#Relationship(type = "iaaSTemplate", direction = Relationship.INCOMING)
IaaSTemplate iaaSTemplate;
#Relationship(type = "iaasParameters")
List<IaasParameters> iaasParameters;
#Relationship(type = "tasks")
List<Tasks> tasks;
#Relationship(type = "RELATED_TO_ScTaxonomy")
#JsonIgnore
public List<CatalogueBlueprint> relations;
public Blueprint() {
iaaSTemplate = new IaaSTemplate();
iaasParameters = new ArrayList<IaasParameters>();
tasks = new ArrayList<Tasks>();
relations = new ArrayList<CatalogueBlueprint>();
}
public void addRelation(ScTaxonomy scTaxonomyRelation,CatalogueBlueprint catalogueBlueprint) {
catalogueBlueprint.blueprintRelation = this;
catalogueBlueprint.scTaxonomyRelation = scTaxonomyRelation;
relations.add(catalogueBlueprint);
/* relations.setCatalogueBlueprintId(catalogueBlueprint.getCatalogueBlueprintId());
relations.setOnIaas(catalogueBlueprint.getOnIaas());
relations.setScript(catalogueBlueprint.getScript());
relations.setX_axis(catalogueBlueprint.getX_axis());
relations.setY_axis(catalogueBlueprint.getY_axis());
relations.setStep(catalogueBlueprint.getStep());
relations.setIsDeleted(catalogueBlueprint.getIsDeleted());*/
scTaxonomyRelation.relations.add(catalogueBlueprint);
}
public Blueprint(String blueprint, String onIaas, String script,
String isDeleted) {
this.blueprint = blueprint;
this.onIaas = onIaas;
this.script = script;
this.isDeleted = isDeleted;
}
public String getBlueprint() {
return blueprint;
}
public void setBlueprint(String blueprint) {
this.blueprint = blueprint;
}
public String getOnIaas() {
return onIaas;
}
public void setOnIaas(String onIaas) {
this.onIaas = onIaas;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public List<IaasParameters> getIaasParameters() {
return iaasParameters;
}
public void setIaasParameters(List<IaasParameters> iaasParameters) {
this.iaasParameters = iaasParameters;
}
public List<Tasks> getTasks() {
return tasks;
}
public void setTasks(List<Tasks> tasks) {
this.tasks = tasks;
}
public IaaSTemplate getIaaSTemplate() {
return iaaSTemplate;
}
public void setIaaSTemplate(IaaSTemplate iaaSTemplate) {
this.iaaSTemplate = iaaSTemplate;
}
public List<CatalogueBlueprint> getRelations() {
return relations;
}
public void setRelations(List<CatalogueBlueprint> relations) {
this.relations = relations;
}
}
/**
*
*/
package nuclei.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.neo4j.ogm.annotation.Relationship;
/**
* #author Karthikeyan
*
*/
public class ScTaxonomy extends Entity {
private String taxName;
private String description;
private String isDeleted;
private String step;
private String serviceCatalogueStep;
private String x_axis;
private String y_axis;
#Relationship(type = "RELATED_TO_ScTaxonomy", direction = "INCOMING")
public List<CatalogueBlueprint> relations;
public ScTaxonomy() {
relations = new ArrayList<>();
}
public ScTaxonomy(String taxName, String description, String isDeleted,String step,String serviceCatalogueStep,
String x_axis,String y_axis) {
this.taxName=taxName;
this.description = description;
this.isDeleted = isDeleted;
this.step=step;
this.serviceCatalogueStep=serviceCatalogueStep;
this.x_axis=x_axis;
this.y_axis=y_axis;
}
public String getTaxName() {
return taxName;
}
public void setTaxName(String taxName) {
this.taxName = taxName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public String getStep() {
return step;
}
public void setStep(String step) {
this.step = step;
}
public String getServiceCatalogueStep() {
return serviceCatalogueStep;
}
public void setServiceCatalogueStep(String serviceCatalogueStep) {
this.serviceCatalogueStep = serviceCatalogueStep;
}
public String getX_axis() {
return x_axis;
}
public void setX_axis(String x_axis) {
this.x_axis = x_axis;
}
public String getY_axis() {
return y_axis;
}
public void setY_axis(String y_axis) {
this.y_axis = y_axis;
}
public List<CatalogueBlueprint> getRelations() {
return relations;
}
public void setRelations(List<CatalogueBlueprint> relations) {
this.relations = relations;
}
}
package nuclei.domain;
import java.util.List;
import org.neo4j.ogm.annotation.EndNode;
import org.neo4j.ogm.annotation.RelationshipEntity;
import org.neo4j.ogm.annotation.StartNode;
#RelationshipEntity(type="catalogueBlueprint")
public class CatalogueBlueprint extends Entity {
private long catalogueBlueprintId;
private String onIaas;
private String script;
private String x_axis;
private String y_axis;
private String step;
private String isDeleted;
#StartNode
public Blueprint blueprintRelation;
#EndNode
public ScTaxonomy scTaxonomyRelation;
public CatalogueBlueprint() {
}
public CatalogueBlueprint(ScTaxonomy to,Blueprint from, String onIaas, String script,long catalogueBlueprintId,
String isDeleted,String x_axis,String y_axis,String step) {
this.scTaxonomyRelation=to;
this.blueprintRelation=from;
this.onIaas = onIaas;
this.script = script;
this.isDeleted = isDeleted;
this.x_axis=x_axis;
this.y_axis=y_axis;
this.step=step;
this.catalogueBlueprintId=catalogueBlueprintId;
}
public long getCatalogueBlueprintId() {
return catalogueBlueprintId;
}
public void setCatalogueBlueprintId(long catalogueBlueprintId) {
this.catalogueBlueprintId = catalogueBlueprintId;
}
public String getOnIaas() {
return onIaas;
}
public void setOnIaas(String onIaas) {
this.onIaas = onIaas;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getX_axis() {
return x_axis;
}
public void setX_axis(String x_axis) {
this.x_axis = x_axis;
}
public String getY_axis() {
return y_axis;
}
public void setY_axis(String y_axis) {
this.y_axis = y_axis;
}
public String getStep() {
return step;
}
public void setStep(String step) {
this.step = step;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
public ScTaxonomy getScTaxonomyRelation() {
return scTaxonomyRelation;
}
public void setScTaxonomyRelation(ScTaxonomy scTaxonomyRelation) {
this.scTaxonomyRelation = scTaxonomyRelation;
}
public Blueprint getBlueprintRelation() {
return blueprintRelation;
}
public void setBlueprintRelation(Blueprint blueprintRelation) {
this.blueprintRelation = blueprintRelation;
}
}
/**
*
*/
package nuclei.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nuclei.domain.CatalogueBlueprint;
import nuclei.domain.IaaSTemplate;
import nuclei.domain.IaasParameters;
import nuclei.domain.ScTaxonomy;
import nuclei.domain.Tasks;
import nuclei.domain.Blueprint;
import nuclei.response.BlueprintMessage;
import nuclei.response.BlueprintsMessage;
import nuclei.response.CatalogueBlueprintMessage;
import nuclei.response.ResponseStatus;
import nuclei.response.ResponseStatusCode;
import nuclei.service.CatalogueBlueprintService;
import nuclei.service.MainService;
import nuclei.service.BlueprintService;
import nuclei.service.ScTaxonomyService;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sun.jersey.multipart.FormDataParam;
/**
* #author Karthikeyan
*
*/
// #RestController
#Controller
public class BlueprintController extends MainController<Blueprint> {
#Autowired
private CatalogueBlueprintService catalogueBlueprintService;
#Autowired
private ScTaxonomyService scTaxonomyService;
#Autowired
private BlueprintService blueprintService;
//create scTaxonomy relation
#RequestMapping(value = "/createScTaxonomyRelation", method = RequestMethod.POST)
public #ResponseBody BlueprintMessage relationTest(
#FormDataParam("ScTaxonomyId") String ScTaxonomyId,
#FormDataParam("blueprintId") String blueprintId,
#FormDataParam("catalogueBlueprintId") String catalogueBlueprintId,
#FormDataParam("onIaas") String onIaas,
#FormDataParam("script") String script,
#FormDataParam("step") String step,
#FormDataParam("x_axis") String x_axis,
#FormDataParam("y_axis") String y_axis,
final HttpServletResponse response) {
ResponseStatus status = null;
Long blueptId = Long.parseLong(blueprintId);
Long taxonomyId = Long.parseLong(ScTaxonomyId);
List<CatalogueBlueprint> catalogueBPList = new ArrayList<CatalogueBlueprint>();
CatalogueBlueprint catalogueBP=new CatalogueBlueprint();
Blueprint blueprint=null;
ScTaxonomy taxonomy = null;
try {
Long catalogueID=Long.parseLong(catalogueBlueprintId);
taxonomy = scTaxonomyService.find(taxonomyId);
blueprint=blueprintService.find(blueptId);
catalogueBP.setBlueprintRelation(blueprint);
catalogueBP.setScTaxonomyRelation(taxonomy);
catalogueBP.setOnIaas(onIaas);
catalogueBP.setCatalogueBlueprintId(catalogueID);
catalogueBP.setScript(script);
catalogueBP.setStep(step);
catalogueBP.setX_axis(x_axis);
catalogueBP.setY_axis(y_axis);
catalogueBP.setIsDeleted("0");
catalogueBPList.add(catalogueBP);
blueprint.addRelation(taxonomy, catalogueBP);
super.create(blueprint);
//super.update(blueptId, blueprint);
status = new ResponseStatus(ResponseStatusCode.STATUS_OK, "SUCCESS");
} catch (Exception e) {
e.printStackTrace();
}
return new BlueprintMessage(status, blueprint);
}
#Override
public MainService<Blueprint> getService() {
return blueprintService;
}
}
I am removed all the dependencies and add updated versions for all the dependency then the error was not showing and the application was running successfully.

Problem about controller and dao functions

i made some small project
there are just add, delete, showlist functions
add and delete functions good work but get list functions are didn't work.
(in my project memoservice.getAll() function didn't work well)
so i try to get lists like this,
List <Memo> mem = getAll();
but there are no return values;
what's the problem in my project. help me plz!
some codes are here.
MemoController.java
package springbook.sug.web;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import springbook.sug.domain.Memo;
import springbook.sug.service.MemoService;
import springbook.sug.web.security.LoginInfo;
#Controller
#RequestMapping("/memo")
public class MemoController {
#Autowired
private MemoService memoService;
private #Inject Provider<LoginInfo> loginInfoProvider;
#RequestMapping("/list")
public String list(ModelMap model) {
model.addAttribute(this.memoService.getAll());
return "memo/list";
}
#RequestMapping("/list/{userId}")
public String list(#PathVariable int userId, ModelMap model) {
model.addAttribute(this.memoService.get(userId));
return "memo/list";
}
#RequestMapping("/delete/{memoId}")
public String delete(#PathVariable int memoId) {
this.memoService.delete(memoId);
return "memo/deleted";
}
#RequestMapping("/add/")
public String showform(ModelMap model) {
Memo memo = new Memo();
model.addAttribute(memo);
return "memo/add";
}
#RequestMapping(method=RequestMethod.POST)
public String add(#ModelAttribute #Valid Memo memo, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
return "list";
}
else {
this.memoService.add(memo);
status.setComplete();
return "redirect:list";
}
}
}
MemoService.java
package springbook.sug.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springbook.sug.dao.MemoDao;
import springbook.sug.domain.Memo;
#Service
#Transactional
public class MemoServiceImpl implements MemoService{
private MemoDao memoDao;
#Autowired
public void setMemoDao(MemoDao memoDao) {
this.memoDao = memoDao;
}
public Memo add(Memo memo) {
memo.initDates();
return this.memoDao.add(memo);
}
public void delete(int memoId) {
this.memoDao.delete(memoId);
}
public Memo get(int userId) {
return this.memoDao.get(userId);
}
public Memo update(Memo memo) {
return this.memoDao.update(memo);
}
public List<Memo> getAll() {
return this.memoDao.getAll();
}
}
MemoDao.java
package springbook.sug.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;
import springbook.sug.domain.Memo;
#Repository
public class MemoDaoJdbc implements MemoDao {
private SimpleJdbcTemplate jdbcTemplate;
private SimpleJdbcInsert memoInsert;
private RowMapper<Memo> rowMapper =
new RowMapper<Memo>() {
public Memo mapRow(ResultSet rs, int rowNum) throws SQLException {
Memo memo = new Memo();
memo.setMemoId(rs.getInt("memoId"));
memo.setMemoContents(rs.getString("memoContents"));
memo.setMemoRegister(rs.getString("memoRegister"));
memo.setCreated(rs.getDate("created"));
return memo;
}
};
#Autowired
public void init(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.memoInsert = new SimpleJdbcInsert(dataSource)
.withTableName("memos")
.usingGeneratedKeyColumns("memoId");
}
public Memo add(Memo memo) {
int generatedId = this.memoInsert.executeAndReturnKey(
new BeanPropertySqlParameterSource(memo)).intValue();
memo.setMemoId(generatedId);
return memo;
}
public Memo update(Memo memo) {
int affected = jdbcTemplate.update(
"update memos set " +
"memoContents = :memoContents, " +
"memoRegister = :memoRegister, " +
"created = :created, " +
"where memoId = :memoId",
new BeanPropertySqlParameterSource(memo));
return memo;
}
public void delete(int memoId) {
this.jdbcTemplate.update("delete from memos where memoId = ?", memoId);
}
public int deleteAll() {
return this.jdbcTemplate.update("delete from memos");
}
public Memo get(int memoId) {
try {
return this.jdbcTemplate.queryForObject("select * from memos where memoId = ?",
this.rowMapper, memoId);
}
catch(EmptyResultDataAccessException e) {
return null;
}
}
public List<Memo> search(String memoRegister) {
return this.jdbcTemplate.query("select * from memos where memoRegister = ?",
this.rowMapper, "%" + memoRegister + "%");
}
public List<Memo> getAll() {
return this.jdbcTemplate.query("select * from memos order by memoId desc",
this.rowMapper);
}
public long count() {
return this.jdbcTemplate.queryForLong("select count(0) from memos");
}
}
Are you getting an exception when running the code? If so, stack trace is needed. If not, do you have data in your table to return? How are you injecting datasource into your dao implementation? Your application context might help.

Resources