form:select does not set the selected value - spring

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

Related

Java Spring Boot Entites not saving to JpaRepository

That's my first project with Spring Boot implemented. I tried going step by step with official Spring tutorial but I'm stuck with a problem that I can't find any answer about.
Whenever I try to call findAll() or find() method on my repository it returns empty array [].
Even with manual preloading enitites like done in tutorial and immediately trying to display database content I get the same result.
I can guess I'm missing something silly, but I can't figure it out for some hours now. What's the cause? Tomcat/jpa/spring version mismatch? Missing annotation somewhere?
Here's my AnimalRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AnimalRepository extends JpaRepository<Animal, Long> {
}
LoadDatabase.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;
#Configuration
class LoadDatabase {
private static final Logger log = LoggerFactory.getLogger(LoadDatabase.class);
#Bean
CommandLineRunner initDatabase(AnimalRepository repository) {
return args -> {
log.info("Preloading " + repository.save(new Lion("Bilbo")));
log.info("Preloading " + repository.save(new Lion("Frodo")));
log.info(repository.findAll().toString()); //try to log content to console
};
}
}
The logging above basically ends up with this console output:
logging result
Probably not as important, but AnimalController.java
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class AnimalController {
private final AnimalRepository repository;
AnimalController(AnimalRepository repository) {
this.repository = repository;
}
#GetMapping("/animals")
List<Animal> all() {
repository.save(new Lion("Bilbo")); //this doesn't work either
return repository.findAll();
}
#PostMapping("/animals")
Animal newAnimal(#RequestBody Animal newAnimal) {
return repository.save(newAnimal);
}
#GetMapping("/animals/{id}")
Animal one(#PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new AnimalNotFoundException(id));
}
#PutMapping("/animals/{id}")
Animal replaceAnimal(#RequestBody Animal newAnimal, #PathVariable Long id) {
return repository.findById(id)
.map(animal -> {
animal.setName(newAnimal.getName());
animal.setSpecies(newAnimal.getSpecies());
return repository.save(animal);
})
.orElseGet(() -> {
newAnimal.setId(id);
return repository.save(newAnimal);
});
}
#DeleteMapping("/animals/{id}")
void deleteAnimal(#PathVariable Long id) {
repository.deleteById(id);
}
}
And the finally Lion.java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Objects;
#Entity
public class Lion implements Animal {
private #Id
#GeneratedValue Long id;
private String name;
private String species;
private int requiredFood;
//private Zone zone;
public Lion(String name) {
this.name = name;
this.species = this.getClass().getSimpleName();
this.requiredFood = LION_REQUIRED_FOOD;
}
public Lion() {
}
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
#Override
public String getSpecies() {
return species;
}
#Override
public void setSpecies(String species) {
this.species = species;
}
#Override
public int getRequiredFood() {
return requiredFood;
}
#Override
public void setRequiredFood(int requiredFood) {
this.requiredFood = requiredFood;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Animal animal))
return false;
return Objects.equals(this.id, animal.getId()) && Objects.equals(this.name, animal.getName())
&& Objects.equals(this.species, animal.getSpecies());
}
#Override
public int hashCode() {
return Objects.hash(this.id, this.name, this.species);
}
#Override
public String toString() {
return "Animal{" + "id=" + this.id + ", name='" + this.name + '\'' + ", species='" + this.species + '\'' + '}';
}
}
I tried switching JpaRepository to CrudRepository, but that didn't work out.
I think the problem here is that your data haven't been saved to the database, because of the transaction. try to change your repository.save() to repository.saveAndFlush()

JPA - Converter class is not being invoked as expected

I cannot figure out why my converter class is not being called. I have the following Entity class:
import org.springframework.validation.annotation.Validated;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.List;
#Entity
#Validated
#Table(name = "c_mark", schema="common")
public class CMark {
#Id
#Column(name = "c_mark_id")
private String id;
#Column(name = "cl_fk")
private String cFk;
#Column(name = "s_con")
#Convert(converter = StringListConverterCommaDelim.class)
private List<String> sCon;
#Override
public String toString() {
return "ClassificationMarking{" +
"id='" + id + '\'' +
", cFk='" + cFk + '\'' +
", s_con='" + s_con + '\'' +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCFk() {
return cFk;
}
public void setCFk(String cFk) {
this.cFk = cFk;
}
public List<String> getSCon() {
return sCon;
}
public void setSCon(List<String> sCon) {
this.sCon = sCon;
}
}
Here is the converter class:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.emptyList;
#Converter
public class StringListConverterCommaDelim implements AttributeConverter<List<String>, String>
{
private static final String SPLIT_CHAR = ",";
#Override
public String convertToDatabaseColumn(List<String> stringList) {
return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
}
#Override
public List<String> convertToEntityAttribute(String string) {
return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
}
}
Here is the repo interface that defines the insert method:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface CMarkRepository extends JpaRepository <ClassificationMarking, String> {
#Transactional
#Modifying
#Query(value = "INSERT INTO c_mark(c_fk, s_con) " +
"values(:c_fk, :s_con)", nativeQuery = true)
int insertCMark(#Param("c_fk") String c_fk, #Param("s_con") String s_con);
}
, and finally the method that invokes the insert:
public int postCMark(CMark cMark) {
CMark cm = null;
int status = 0;
try {
status = cMarkingRepository.insertCMark(cMark.getCFk(), cMark.getSCon());
} catch ( Exception e) {
e.printStackTrace();
}
return status;
}
My expectation is that the conversion takes place from the insertCMark() call? I am not sure. In any event, the converter is never called. I would be grateful for any ideas. Thanks!
You're not inserting the whole Entity. So I guess from Spring perspective you just give normal String parameters and Spring probably doesn't know the parameter should somehow be converted.
Despite that shouldn't you even get a compile error because you try to call insertCMark(String, String) as insertCMark(String, List<String>)?
Right now I would say that there is no need for some fancy Spring magic.
You can just tweak the getSCon() method to return a String and convert it in there. Or when you need it for something else to create a second method getSConString():
public String getSCon() {
return this.sCon != null ? String.join(SPLIT_CHAR, this.sCon) : "";
}
Another way is to use your current Converter by hand when calling insertCMark:
public int postCMark(CMark cMark) {
CMark cm = null;
int status = 0;
AttributeConverter<List<String>, String> converter = new StringListConverterCommaDelim();
String sCon = converter.convertToDatabaseColumn(cMark.getSCon());
try {
status = cMarkingRepository.insertCMark(cMark.getCFk(), sCon);
} catch ( Exception e) {
e.printStackTrace();
}
return status;
}

#OneToOne(cascade = {CascadeType.ALL}) problem

I have a problem with my code. I do a little CarRent webservice and when i try to assign Errand to the car, errand which i want to assign is add to list of errands...
this is controller of errand
package com.RentCar.Rent_A_car.domain.Controllers;
import com.RentCar.Rent_A_car.domain.Car;
import com.RentCar.Rent_A_car.domain.Errand;
import com.RentCar.Rent_A_car.domain.Services.CarService;
import com.RentCar.Rent_A_car.domain.Services.ErrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
public class ErrandController {
#Autowired
CarService carService;
#Autowired
ErrandService errandService;
#RequestMapping("/assignErrand")
public String assignQuest(#RequestParam("plate") String plate, Model model){
Car car = carService.getCar(plate);
List<Errand> errandList = errandService.getAllCurrentErrands();
model.addAttribute("car",car);
model.addAttribute("errands",errandList);;
return "assignErrand";
}
#RequestMapping(value = "/assignErrand", method = RequestMethod.POST)
public String assignQuest(Car car){
carService.updateCar(car);
System.out.println("assignquest");
return "redirect:/cars";
}
These are my repositories
#Repository
public class CarsRepository {
// class to do CRUD operation on cars and errands
Map<String, Car> CarList = new HashMap<>();
#PersistenceContext
private EntityManager em;
#Transactional
public void AddCar (String mark, String plate, int mileage){
Car newCar = new Car(mark, plate, mileage);
em.persist(newCar);
}
//pobiera aktualne id i dodaje do mapy
#Transactional
public void AddCar(Car car) {
em.persist(car);
}
// dla każdego "powyzej" usuniętego trzeba zmniejszyć id o 1 ; pętla o dlugosci pozostałych aut id--; KONIECZNE FINALNIE, do budowy nie
#Transactional
public void DellateCar(String plate){
Car c = em.find(Car.class, plate);
em.remove(c);
}
public Car getCar(String plate){
Car car = em.createQuery("from Car c where c.plate=:plate", Car.class)
.setParameter("plate", plate).getSingleResult();
return car;
}
public Collection<Car> getAllCars() {
return em.createQuery("from Car",Car.class).getResultList();
}
#Transactional
public void updateCar(Car car) {
em.merge(car);
}
// public String getPlate() {
// if (CarList.isEmpty()) {
// return "Car list is empty";
// } else {
// return (String)CarList.keySet();
// }
// }
// #PostConstruct
// public void build() {
// AddCar("BMW","DW",100000);
// AddCar("Opel","DTR",100043);
// AddCar("Toyota","WB",1012300);
// AddCar("Audi","DST",102340);
//
// }
#Override
public String toString() {
return "CarsRepository{" +
"CarList=" +
'}' + "\n";
}
}
Nr
#Repository
public class ErrandRepository {
#PersistenceContext
private EntityManager ee;
List<Errand> ErrandList = new ArrayList<>();
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
public void createErrand(Errand errand){ErrandList.add(errand);}
public List<Errand> getAll () {
return ee.createQuery("from Errand", Errand.class).getResultList();
}
public void delateErrand(Errand errand) {
ee.remove(errand);
}
#Transactional
public void delateErrand(int x) {
ErrandList.remove(x);
}
public Errand getErrandId(Integer x){
return ee.find(Errand.class, x );
}
#PostConstruct
#Transactional
public void init(){
Errand e1 = new Errand("zlecenie na wrocław");
Errand e2 = new Errand("zlecenie na wasdw");
Errand e3 = new Errand("zlecenie na wfgasfdław");
}
#Override
public String toString() {
return "ErrandRepository{" +
"ErrandList=" + ErrandList +
'}';
}
}
this is a part of CarService
public void updateCar(Car car) {
carsRepository.updateCar(car);
System.out.println("tu sie wywołuje updatecar");
}
i don't know what is a problem... can you help me ?
edit, i add car and errand class
package com.RentCar.Rent_A_car.domain;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Car {
// #Id
// #GeneratedValue(strategy = GenerationType.AUTO)
// public int id;
String mark;
#Id
String plate;
int mileage;
#OneToOne(cascade = CascadeType.ALL)
public Errand errand;
public Car() { }
public Car(String mark, String plate, int mileage) {
this.mark = mark;
this.plate = plate;
this.mileage = mileage;
}
public void setErrand(Errand errand) {
this.errand = errand;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public Errand getErrand() {
return errand;
}enter code here
And errand class
package com.RentCar.Rent_A_car.domain;
import net.bytebuddy.dynamic.loading.InjectionClassLoader;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Errand {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int Id;
public String description;
public Errand() {
}
public Errand(String description) {
this.description = description;
}
#Override
public String toString() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I'm not quite sure about what is the actual problem. But anyway, I can make you some recommendations:
use plural nouns for REST uris, like:
#GetMapping("cars")
#GetMapping("errands")
and so on. Not verbs, like: assignErrand
If you split Repositories and Services, do not put login in repos, like
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
In the repos you should do just the persistence job. Leave the logic to the service
To add errands, I would go with something like this:
#PostMapping("/cars/{carId}/errands")
public Car addErranr(#PathVariable int carId, #RequestBody Errand errand){
Car car = this.carService.findById(carId);
car.getErrands().add(errand);
return this.carService.save(car);
}

Nullpointer Exception unknown resource springmicriservice

cnv any one help me I dont knoe where make mistake,when i run my
application in chrome in browser when type
http://localhost:8100/currency-converter-feign/from/USD/to/INR/quantity/1000
i got this type of erro
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Fri Jul 17 21:38:29 IST 2020 There was an unexpected error
(type=Internal Server Error, status=500). No message available
java.lang.NullPointerException at
java.math.BigDecimal.multiply(Unknown Source) at
com.main.conteoller.CurrencyconversionController.convertCurencyFfeign(CurrencyconversionController.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at
currencyconvertercontroller.java
package com.main.conteoller;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.main.Bean.ConversionBean;
import com.main.serviceproxy.CurrencyexchangeserviceProxy;
#RestController
public class CurrencyconversionController {
#Autowired
private CurrencyexchangeserviceProxy proxy;
#GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
public ConversionBean convertCurency(#PathVariable String from,
#PathVariable String to,
#PathVariable BigDecimal quantity) {
Map<String, String>uriVariables= new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);
ResponseEntity<ConversionBean>resp = new RestTemplate()
.getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
ConversionBean.class,
uriVariables);
ConversionBean cbresp=resp.getBody();
return new ConversionBean(cbresp.getId(),from,to,cbresp.getConvermultiple(),
quantity,quantity.multiply(cbresp.getConvermultiple()),cbresp.getPort());
}
#GetMapping("/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}")
public ConversionBean convertCurencyFfeign(#PathVariable String from,
#PathVariable String to,
#PathVariable BigDecimal quantity) {
ConversionBean cbresp=proxy.retrivefromexchange(from, to);
return new ConversionBean(cbresp.getId(),from,to,cbresp.getConvermultiple(),
quantity,quantity.multiply(cbresp.getConvermultiple()),cbresp.getPort());
}
}
currencybean.java
package com.main.Bean;
import java.math.BigDecimal;
public class ConversionBean {
private int id;
private String from;
private String to;
private BigDecimal convermultiple;
private BigDecimal quantity;
private BigDecimal totalCalamount;
private int port;
public ConversionBean() {}
public ConversionBean(int id, String from, String to, BigDecimal convermultiple, BigDecimal quantity,
BigDecimal totalCalamount, int port) {
super();
this.id = id;
this.from = from;
this.to = to;
this.convermultiple = convermultiple;
this.quantity = quantity;
this.totalCalamount = totalCalamount;
this.port = port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public BigDecimal getConvermultiple() {
return convermultiple;
}
public void setConvermultiple(BigDecimal convermultiple) {
this.convermultiple = convermultiple;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getTotalCalamount() {
return totalCalamount;
}
public void setTotalCalamount(BigDecimal totalCalamount) {
this.totalCalamount = totalCalamount;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
currencyexchangeproxy.java
package com.main.serviceproxy;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.main.Bean.ConversionBean;
#FeignClient(name="currency-exchange",url="localhost:8000")
public interface CurrencyexchangeserviceProxy {
#GetMapping("/currency-exchange/from/{from}/to/{to}")
public ConversionBean retrivefromexchange(#PathVariable ("from") String from,
#PathVariable ("to") String to);
}
It is occurs due to mismatch of comumn name in your db table and in
your entity class. Because I use micriservices,I call some exchange
rates from another project by provideing its url in my repository, in
that project i privide same name in my entity class and in my db table
,but i declared diffrent name in my exchange service project. there i
declare conversationmultople and here declare convermultiple
.make sure both name same in db and your bean class
#EnableFeignClient service in your springboot main method
for example
package com.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
#SpringBootApplication
#EnableFeignClients("com.main.serviceproxy")
public class CurrencyConversionServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CurrencyConversionServiceApplication.class, args);
}
}

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.

Resources