Field value in a Class does not get updated with Spring Boot MVC Controller - spring

I have a Parcel Entity, and I am populating the fields through #PostMapping. The value Volume should be gotten from a method taking in values from the agruments in the constructor.
Controller Class:
#Controller
public class Controller {
#Value("#{${listOfBases}}")
private List<String> listOfBases;
#Value("#{${listOfDestinations}}")
private List<String> listOfDestinations;
#Autowired
ParcelRepository parcelRepository;
#GetMapping("/register_parcel")
public String showParcelRegistrationForm(Model model) {
Parcel parcel = new Parcel();
model.addAttribute("parcel", parcel);
model.addAttribute("listOfBases", listOfBases);
model.addAttribute("listOfDestinations", listOfDestinations);
return "parcel/register_form_parcel";
}
#PostMapping("register_parcel")
public String registerParcel(#ModelAttribute("parcel") Parcel parcel) {
System.out.println(parcel);
parcelRepository.save(parcel);
return "user/user_registration_success_form";
}
}
Parcel Class:
#Entity
public class Parcel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
String length;
String width;
String height;
String weight;
String base;
String destination;
String creationDate;
String volume;
No args constructor:
public Parcel() {
creationDate = getCreationDateAndTime();
}
public Parcel(int id, String length, String width, String height, String weight, String base, String destination) {
this.id = id;
this.length = length;
this.width = width;
this.height = height;
this.weight = weight;
this.base = base;
this.destination = destination;
creationDate = getCreationDateAndTime();
volume = String.valueOf(calculateVolume(width, height, length));
}
Getters and Setters:
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLength() {
return length;
}
public void setLength(String length) {
this.length = length;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
private String getCreationDateAndTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
return dtf.format(now);
}
CalculateVolume method that is the root of the problem:
private int calculateVolume(String width, String height, String length) {
int w = Integer.parseInt(width);
int h = Integer.parseInt(height);
int l = Integer.parseInt(length);
return w * h * l;
}
But the value volume is null in my database. Even System.out.println(); in calculateVolume does not print anything on the console, but when I run create an instance in main, all runs fine and dandy.
Any ideas on how I should proceed, or is my question too vague?
Thank you
#Override
public String toString() {
return "Parcel{" +
"id=" + id +
", length='" + length + '\'' +
", width='" + width + '\'' +
", height='" + height + '\'' +
", weight='" + weight + '\'' +
", base='" + base + '\'' +
", destination='" + destination + '\'' +
", creationDate='" + creationDate + '\'' +
", volume='" + volume + '\'' +
'}';
}
}

Change Post method in your controller
from
public String registerParcel(#ModelAttribute("parcel") Parcel parcel)
to
public String registerParcel(#RequestBody Parcel parcel)

Related

How to change form data body feign client interceptor

I have some api with content-type: form-data.
Every request have some common field in the body
Here is my code
package com.example.demo.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
public class CreateNhanhProductRequest {
private String nuctk;
private Long storeId;
private String name;
private Integer typeId;
private String parentIdName;
private Long parentId;
private String code;
private String barcode;
private BigDecimal importPrice;
private BigDecimal vat;
private BigDecimal price;
private BigDecimal wholesalePrice;
private BigDecimal oldPrice;
private Integer status;
private Object multiUnitItems;
private Object comboItems;
private Long categoryId;
private Long internalCategoryId;
private Long brandId;
private Double shippingWeight;
private String unit;
private Integer length;
private Integer width;
private Integer height;
private Long countryId;
private Long warrantyAddress;
private String warrantyPhone;
private Long warranty;
private String warrantyContent;
private Integer firstRemain;
private Integer importType;
private Long depotId;
private String supplierName;
private Long supplierId;
private Integer checkcopyImg;
private Integer attributeCombinated;
private String metaTitle;
private String metaDescription;
private Object metaKeywords;
private Object tags;
#JsonProperty("tag-suggest")
private Object tagSuggest;
public String getNuctk() {
return nuctk;
}
public void setNuctk(String nuctk) {
this.nuctk = nuctk;
}
public Long getStoreId() {
return storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public String getParentIdName() {
return parentIdName;
}
public void setParentIdName(String parentIdName) {
this.parentIdName = parentIdName;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public BigDecimal getImportPrice() {
return importPrice;
}
public void setImportPrice(BigDecimal importPrice) {
this.importPrice = importPrice;
}
public BigDecimal getVat() {
return vat;
}
public void setVat(BigDecimal vat) {
this.vat = vat;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getWholesalePrice() {
return wholesalePrice;
}
public void setWholesalePrice(BigDecimal wholesalePrice) {
this.wholesalePrice = wholesalePrice;
}
public BigDecimal getOldPrice() {
return oldPrice;
}
public void setOldPrice(BigDecimal oldPrice) {
this.oldPrice = oldPrice;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Object getMultiUnitItems() {
return multiUnitItems;
}
public void setMultiUnitItems(Object multiUnitItems) {
this.multiUnitItems = multiUnitItems;
}
public Object getComboItems() {
return comboItems;
}
public void setComboItems(Object comboItems) {
this.comboItems = comboItems;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public Long getInternalCategoryId() {
return internalCategoryId;
}
public void setInternalCategoryId(Long internalCategoryId) {
this.internalCategoryId = internalCategoryId;
}
public Long getBrandId() {
return brandId;
}
public void setBrandId(Long brandId) {
this.brandId = brandId;
}
public Double getShippingWeight() {
return shippingWeight;
}
public void setShippingWeight(Double shippingWeight) {
this.shippingWeight = shippingWeight;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Long getCountryId() {
return countryId;
}
public void setCountryId(Long countryId) {
this.countryId = countryId;
}
public Long getWarrantyAddress() {
return warrantyAddress;
}
public void setWarrantyAddress(Long warrantyAddress) {
this.warrantyAddress = warrantyAddress;
}
public String getWarrantyPhone() {
return warrantyPhone;
}
public void setWarrantyPhone(String warrantyPhone) {
this.warrantyPhone = warrantyPhone;
}
public Long getWarranty() {
return warranty;
}
public void setWarranty(Long warranty) {
this.warranty = warranty;
}
public String getWarrantyContent() {
return warrantyContent;
}
public void setWarrantyContent(String warrantyContent) {
this.warrantyContent = warrantyContent;
}
public Integer getFirstRemain() {
return firstRemain;
}
public void setFirstRemain(Integer firstRemain) {
this.firstRemain = firstRemain;
}
public Integer getImportType() {
return importType;
}
public void setImportType(Integer importType) {
this.importType = importType;
}
public Long getDepotId() {
return depotId;
}
public void setDepotId(Long depotId) {
this.depotId = depotId;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public Long getSupplierId() {
return supplierId;
}
public void setSupplierId(Long supplierId) {
this.supplierId = supplierId;
}
public Integer getCheckcopyImg() {
return checkcopyImg;
}
public void setCheckcopyImg(Integer checkcopyImg) {
this.checkcopyImg = checkcopyImg;
}
public Integer getAttributeCombinated() {
return attributeCombinated;
}
public void setAttributeCombinated(Integer attributeCombinated) {
this.attributeCombinated = attributeCombinated;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public Object getMetaKeywords() {
return metaKeywords;
}
public void setMetaKeywords(Object metaKeywords) {
this.metaKeywords = metaKeywords;
}
public Object getTags() {
return tags;
}
public void setTags(Object tags) {
this.tags = tags;
}
public Object getTagSuggest() {
return tagSuggest;
}
public void setTagSuggest(Object tagSuggest) {
this.tagSuggest = tagSuggest;
}
#Override
public String toString() {
return "CreateNhanhProductRequest{" +
"nuctk='" + nuctk + '\'' +
", storeId=" + storeId +
", name='" + name + '\'' +
", typeId=" + typeId +
", parentIdName='" + parentIdName + '\'' +
", parentId=" + parentId +
", code='" + code + '\'' +
", barcode='" + barcode + '\'' +
", importPrice=" + importPrice +
", vat=" + vat +
", price=" + price +
", wholesalePrice=" + wholesalePrice +
", oldPrice=" + oldPrice +
", status=" + status +
", multiUnitItems=" + multiUnitItems +
", comboItems=" + comboItems +
", categoryId=" + categoryId +
", internalCategoryId=" + internalCategoryId +
", brandId=" + brandId +
", shippingWeight=" + shippingWeight +
", unit='" + unit + '\'' +
", length=" + length +
", width=" + width +
", height=" + height +
", countryId=" + countryId +
", warrantyAddress=" + warrantyAddress +
", warrantyPhone='" + warrantyPhone + '\'' +
", warranty=" + warranty +
", warrantyContent='" + warrantyContent + '\'' +
", firstRemain=" + firstRemain +
", importType=" + importType +
", depotId=" + depotId +
", supplierName='" + supplierName + '\'' +
", supplierId=" + supplierId +
", checkcopyImg=" + checkcopyImg +
", attributeCombinated=" + attributeCombinated +
", metaTitle='" + metaTitle + '\'' +
", metaDescription='" + metaDescription + '\'' +
", metaKeywords=" + metaKeywords +
", tags=" + tags +
", tagSuggest=" + tagSuggest +
'}';
}
// private Multi imageUpload;
}
I want to Add same nuctk in every request in the body.
But request use the formData i can't convert this to object in interceptor.
My client
package com.example.demo.client;
import com.example.demo.config.NhanhPageFeignClientInterceptor;
import com.example.demo.request.CreateNhanhProductRequest;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
#FeignClient(
value = "nhanhPage",
url = "https://nhanh.vn/product",
configuration = NhanhPageFeignClientInterceptor.class
)
public interface NhanhProductV1Client {
#PostMapping(value = "/item/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String createProduct(#RequestBody CreateNhanhProductRequest request);
}
This is my interceptor
package com.example.demo.config;
import com.example.demo.request.CreateNhanhProductRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.form.FormData;
import feign.form.FormEncoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.io.IOException;
public class NhanhPageFeignClientInterceptor {
#Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
String bodyTemplate = requestTemplate.bodyTemplate();
byte[] body = requestTemplate.body();
FormData formData = new FormData(MediaType.MULTIPART_FORM_DATA_VALUE, "data" , body);
requestTemplate.header(HttpHeaders.COOKIE, "Some cookie");
};
}
}
How to change the body in feign client interceptor.
Thank!

Java 8 groupingby with returning multiple field

In Java 8 group by how to groupby on a single field which returns more than one field. In the below code by I am passing name and the field to be summed which is 'total' in this scenario. however I would like to return sum of 'total' and 'balance' field for every 'name' in the Customer list (can be a map with key and value as array).
Can it be done by using a single groupingBy with the return values?
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class Sample {
public static void main(String str[]){
Customer custa = new Customer("A",1000,1500);
Customer custa1 = new Customer("A",2000,2500);
Customer custb = new Customer("B",3000,3500);
Customer custc = new Customer("C",4000,4500);
Customer custa2 = new Customer("A",1500,2500);
List<Customer> listCust = new ArrayList<>();
listCust.add(custa);
listCust.add(custa1);
listCust.add(custb);
listCust.add(custc);
listCust.add(custa2);
Map<String, Double> retObj =
listCust.stream().collect(Collectors.groupingBy(Customer::getName,Collectors.summingDouble(Customer::getTotal)));
System.out.println(retObj);
}
private static class Customer {
private String name;
private double total;
private double balance;
public Customer(String name, double total, double balance) {
super();
this.name = name;
this.total = total;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
#Override
public String toString() {
return "Customer [name=" + name + ", total=" + total + ", balance=" + balance + "]";
}
}
}
Expected Output -
{
A = [4500,6500],
B = [3000,3500] ,
C = [4000,4500]
}
You can write your own collector to sum total and balance
Collector<Customer, List<Double>, List<Double>> collector = Collector.of(
() -> Arrays.asList(0.0, 0.0),
(a, t) -> {
a.set(0, a.get(0) + t.getTotal());
a.set(1, a.get(1) + t.getBalance());
},
(a, b) -> {
a.set(0, a.get(0) + b.get(0));
a.set(1, a.get(1) + b.get(1));
return a;
}
);
Map<String, List<Double>> retObj = listCust
.stream()
.collect(Collectors.groupingBy(Customer::getName, collector));
System.out.println(retObj);
result
{A=[4500.0, 6500.0], B=[3000.0, 3500.0], C=[4000.0, 4500.0]}
You can also use the toMap collector to accomplish the task at hand.
Map<String, List<Double>> retObj =
listCust.stream()
.collect(Collectors.toMap(Customer::getName,
c -> new ArrayList<>(Arrays.asList(c.getTotal(), c.getBalance())),
(l, l1) -> {
l.set(0, l.get(0) + l1.get(0));
l.set(1, l.get(1) + l1.get(1));
return l;
}));

How to update/refresh list items of list view in oracle maf?

I have list of tasks. When I delete my one of the task my list still shows that task in the list but on server side i have updated list I am not able to refresh my list. I am getting new task array from server but not able to show it. When I launched my app again then it is showing the updated list. How can I get updated list without killing the app? Both the times I have updated array but not able to show it on the view.
public class ModelClass {
private String message;
private String statusCode;
private Response[] res = null;
protected transient PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
public ModelClass() {
super();
clickEvent(new ActionEvent());
}
public static String taskId;
public void setTaskId(String taskId) {
System.out.print(taskId);
this.taskId = taskId;
}
public String getTaskId() {
return taskId;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return _propertyChangeSupport;
}
public void setMessage(String message) {
String oldMessage = this.message;
this.message = message;
_propertyChangeSupport.firePropertyChange("message", oldMessage, message);
}
public String getMessage() {
return message;
}
public void setStatusCode(String statusCode) {
String oldStatusCode = this.statusCode;
this.statusCode = statusCode;
_propertyChangeSupport.firePropertyChange("statusCode", oldStatusCode, statusCode);
}
public String getStatusCode() {
return statusCode;
}
public void setRes(Response[] res) {
Response[] oldRes = this.res;
this.res = res;
System.out.println(res);
_propertyChangeSupport.firePropertyChange("res", oldRes, res);
System.out.println("refreshing here ");
}
public Response[] getRes() {
return res;
}
#Override
public String toString() {
return "ClassPojo [response = " + res + ", message = " + message + ", statusCode = " + statusCode + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
public class Response {
private String taskId;
private String taskType;
private Integer taskTime;
private String taskName;
private PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this);
Response(String taskId, String taskType, String taskName) {
super();
this.taskId = taskId;
this.taskType = taskType;
this.taskName = taskName;
}
public void setTaskId(String taskId) {
String oldTaskId = this.taskId;
this.taskId = taskId;
_propertyChangeSupport.firePropertyChange("taskId", oldTaskId, taskId);
}
public String getTaskId() {
return taskId;
}
public void setTaskType(String taskType) {
String oldTaskType = this.taskType;
this.taskType = taskType;
_propertyChangeSupport.firePropertyChange("taskType", oldTaskType, taskType);
}
public String getTaskType() {
return taskType;
}
public void setTaskTime(Integer taskTime) {
Integer oldTaskTime = this.taskTime;
this.taskTime = taskTime;
_propertyChangeSupport.firePropertyChange("taskTime", oldTaskTime, taskTime);
}
public Integer getTaskTime() {
return taskTime;
}
public void setTaskName(String taskName) {
String oldTaskName = this.taskName;
this.taskName = taskName;
_propertyChangeSupport.firePropertyChange("taskName", oldTaskName, taskName);
}
public String getTaskName() {
return taskName;
}
#Override
public String toString() {
return "ClassPojo [taskId = " + taskId + ", taskType = " + taskType + ", taskTime = " + taskTime +
", taskName = " + taskName + "]";
}
public void addPropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
_propertyChangeSupport.removePropertyChangeListener(l);
}
}
protected transient ProviderChangeSupport providerChangeSupport = new ProviderChangeSupport(this);
public void addProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.addProviderChangeListener(l);
}
public void removeProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.removeProviderChangeListener(l);
}
public void clickEvent(ActionEvent actionEvent) {
try {
JSONObject paramsMap = new JSONObject();
paramsMap.put("userId", "1");
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/#########");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(120000);
httpURLConnection.setConnectTimeout(120000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
os.write(paramsMap.toString().getBytes());
bufferedWriter.flush();
bufferedWriter.close();
os.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line + "\n");
line = bufferedReader.readLine();
}
is.close();
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println(builder.toString());
JSONObject json = new JSONObject(builder.toString());
String status = json.optString("statusCode");
String message = json.optString("message");
String response = json.optString("response");
System.out.println(status);
System.out.println(message);
// System.out.println(response);
JSONArray objarr = json.optJSONArray("response");
Response[] temp_res = new Response[objarr.length()];
for (int i = 0; i < objarr.length(); i++) {
System.out.println(objarr.getJSONObject(i));
JSONObject obj = objarr.getJSONObject(i);
String task = obj.optString("taskName");
taskId = obj.optString("taskId");
String taskType = obj.optString("taskType");
System.out.println(task);
System.out.println(taskId);
System.out.println(taskType);
temp_res[i] = new Response(taskId, taskType, task);
}
setRes(temp_res);
} else {
if (httpURLConnection != null)
httpURLConnection.disconnect();
System.out.println("Invalid response from the server");
}
} catch (Exception e) {
e.printStackTrace();
if (httpURLConnection != null)
httpURLConnection.disconnect();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to add providerChangeSupport.fireProviderRefresh("res");
and you have to make public method for providerChangeSupport.
Here is the link : https://community.oracle.com/message/13203364#13203364
Other than the fix suggested by Rashi Verma, there is one more change required.
The code snippet:
res = (Response[]) res_new.toArray(new Response[res_new.size()]);
setRes(res);
needs to be changed to:
Response[] temp_res;
temp_res = (Response[]) res_new.toArray(new
Response[res_new.size()]);
setRes(temp_res);
Currently, because the value of res is changed before invoking setRes, the propertyChangeEvent is not fired inside setRes. Both this propertyChangeEvent and the providerRefresh are needed for the changes you are making to start reflecting on the UI.

Spring BeanUtils.copyProperties not working

I want to copy properties from one object to another, both are of the same class. However it's not copying the fields. Here is the demo code:
public static void main(String[] args) throws Exception {
A from = new A();
A to = new A();
from.i = 123;
from.l = 321L;
System.out.println(from.toString());
System.out.println(to.toString());
BeanUtils.copyProperties(from, to);
System.out.println(from.toString());
System.out.println(to.toString());
}
public static class A {
public String s;
public Integer i;
public Long l;
#Override
public String toString() {
return "A{" +
"s=" + s +
", i=" + i +
", l=" + l +
'}';
}
}
And the output is:
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
Looks like I have to have setter/getters for the class:
public static void main(String[] args) throws Exception {
A from = new A();
A to = new A();
from.i = 123;
from.l = 321L;
System.out.println(from.toString());
System.out.println(to.toString());
BeanUtils.copyProperties(from, to);
System.out.println(from.toString());
System.out.println(to.toString());
}
public static class A {
public String s;
public Integer i;
public Long l;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public Long getL() {
return l;
}
public void setL(Long l) {
this.l = l;
}
#Override
public String toString() {
return "A{" +
"s=" + s +
", i=" + i +
", l=" + l +
'}';
}
}
Now the output is:
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
A{s=null, i=123, l=321}
A{s=null, i=123, l=321}

Unable to update entities via spring repository

Here is my code. I'm changing
#RequestMapping(value={"/set_channels"}, method={RequestMethod.POST})
public void setChannels(#RequestParam(value = "fromIndex") int fromIndex,
#RequestParam(value = "toIndex") int toIndex,
#RequestBody Channel channel) {
List<Channel> allChannels = repository.findAllByOrderByBinIndexAsc();
if (allChannels.isEmpty()) {
createChannels(fromIndex, toIndex, channel);
}
else {
updateAndOrCreateChannels(allChannels, fromIndex, toIndex, channel);
}
}
private void updateAndOrCreateChannels(List<Channel> allChannels, int fromIndex, int toIndex, Channel channel) {
int minBinIndex = allChannels.get(0).getBinIndex();
int maxBinIndex = allChannels.get(allChannels.size() - 1).getBinIndex();
for (Channel ch: allChannels) {
if (ch.getBinIndex() >= fromIndex && ch.getBinIndex() <= toIndex) {
channel.copySettings(channel);
}
}
// error here!!!
repository.save(allChannels);
if (fromIndex < minBinIndex || toIndex > maxBinIndex) {
List<Channel> newChannels = new ArrayList<>(minBinIndex - fromIndex + toIndex - maxBinIndex);
for (int i = fromIndex; i < minBinIndex; i ++) {
newChannels.add(new Channel(channel, i));
}
for (int i = maxBinIndex + 1; i <= fromIndex; i++) {
newChannels.add(new Channel(channel, i));
}
repository.save(newChannels);
}
}
Here is my channel entity.
package demo.model.processing;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
/**
* Created by michael on 21/08/15.
*/
#Entity
public class Channel {
#NotNull
private ChannelMode mode;
#NotNull
private boolean excluded;
#NotNull
private double manualCoefficient;
#NotNull
private double c1;
#Override
public String toString() {
return "Channel{" +
", mode=" + mode +
", excluded=" + excluded +
", manualCoefficient=" + manualCoefficient +
", c1=" + c1 +
", c2=" + c2 +
", binIndex=" + binIndex +
'}';
}
#NotNull
private double c2;
#Id
private int binIndex;
public void copySettings(Channel other) {
setMode(other.getMode());
setC1(other.getC1());
setC2(other.getC2());
setManualCoefficient(other.getManualCoefficient());
setExcluded(other.isExcluded());
}
public Channel() {}
public Channel(ChannelMode mode,
double c2,
double c1,
double manualCoefficient,
boolean excluded,
int binIndex) {
setMode(mode);
setC2(c2);
setC1(c1);
setManualCoefficient(manualCoefficient);
setExcluded(excluded);
setBinIndex(binIndex);
}
Here is my Channel Entity. As you can see I'm trying to use binIndex as Id.
public Channel(Channel other, int newBinIndex) {
setMode(other.getMode());
setC1(other.getC1());
setC2(other.getC2());
setManualCoefficient(other.getManualCoefficient());
setExcluded(other.isExcluded());
setBinIndex(newBinIndex);
}
public ChannelMode getMode() {
return mode;
}
public void setMode(ChannelMode mode) {
this.mode = mode;
}
public boolean isExcluded() {
return excluded;
}
public void setExcluded(boolean excluded) {
this.excluded = excluded;
}
public double getManualCoefficient() {
return manualCoefficient;
}
public void setManualCoefficient(double manualCoefficient) {
this.manualCoefficient = manualCoefficient;
}
public double getC1() {
return c1;
}
public void setC1(double c1) {
this.c1 = c1;
}
public double getC2() {
return c2;
}
public void setC2(double c2) {
this.c2 = c2;
}
public int getBinIndex() {
return binIndex;
}
public void setBinIndex(int binIndex) {
this.binIndex = binIndex;
}
}
And this gives me the error.
DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PRIMARY KEY ON PUBLIC.CHANNEL(BIN_INDEX)"; SQL statement:
insert into channel (c1, c2, excluded, manual_coefficient, mode, bin_index) values (?, ?, ?, ?, ?, ?) [23505-187]]; nested exception is org.hibernate.exception
Well repository trying to insert instead of update then this message is not surprise, but why insert in the first place. I haven't changed the id.
EDIT1
The idea behind this channel is that there is a fix number of this channels in the system. They unique by binIndex. And this binIndex is a always a number from 0 to n. So if we have 10 channels they would have bin indices 0..10. And after they have been created we only need to update them.
This request is about "Create or update existing channels with binIndices from x to y and with settings like in this example channel".

Resources