Cannot update entity - spring-boot

I'm trying to update an entity with a particular mapping :
#Entity
#Table(name = "obs_structure2")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Structure implements Serializable{
private String id;
private String tag;
private String description;
private Set<Version> parentVersions = new HashSet<>();
private List<StructureElement> children = new ArrayList<>();
private List<StructureElement> slaves = new ArrayList<>();
private PersistenceSignature signature = new PersistenceSignature();
#OneToMany(mappedBy = "parentStructure")
public List<StructureElement> getChildren() {
return children;
}
public void addChild(StructureElement se)
{
if(this.children.contains(se))
{
this.children.add(se);
}
}
and
#Entity
#Table(name = "obs_structure_element2")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class StructureElement implements Serializable{
private long id;
private String tag;
private String description;
private boolean repetitive = false;
private boolean optional = false;
private Integer position = 1;
private Structure parentStructure;
private Structure typeStructure;
private PersistenceSignature signature = new PersistenceSignature();
#ManyToOne
#JoinColumn(name = "parent_id")
#JsonIgnore
public Structure getParentStructure() {
return parentStructure;
}
and this is my controller :
#PutMapping("/update")
public StructureElement update(#RequestBody StructureElement se){
logger.info("Call to StructureElementController.update with se = " + se);
this.connectToDatabase();
StructureElement updatedSE;
try{
boolean exists = this.repository.exists(se.getId());
if(!exists){
logger.error("Could not find StructureElement to update. se = " + se);
return null;
}
updatedSE = this.repository.save(se);
logger.info("Updated SE = " + updatedSE);
}catch (Exception e){
logger.error("Could not update structure element. se = " + se, e);
return null;
}
return updatedSE;
}
When I try to update an element the parentStructure is overwritten to null.
If I delete the #JsonIgnore annotation I'm getting this StackOverflow error:
[ERROR] 2018-01-03 14:22:38.577 [http-nio-8080-exec-5] o.a.c.c.C.[.[.[.[dispatcherServlet] 181 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null
at java.util.AbstractCollection.toString(AbstractCollection.java:454) ~[?:1.8.0_151]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at be.groups.observatory.server.model.Structure.toString(Structure.java:147) ~[classes/:?]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at be.groups.observatory.server.model.StructureElement.toString(StructureElement.java:116) ~[classes/:?]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[?:1.8.0_151]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at be.groups.observatory.server.model.Structure.toString(Structure.java:147) ~[classes/:?]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at be.groups.observatory.server.model.StructureElement.toString(StructureElement.java:116) ~[classes/:?]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[?:1.8.0_151]
at java.lang.String.valueOf(String.java:2994) ~[?:1.8.0_151]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[?:1.8.0_151]
at be.groups.observatory.server.model.Structure.toString(Structure.java:147) ~[classes/:?]
and for those who know vue.js here is my component :
<template>
<div class="t-body">
<obs-sidebar></obs-sidebar>
<main class="t-content">
<div v-if="updated" class="c-notification c-notification--success" role="dialog" aria-label="first notification" aria-describedby="desc_1">
<p id="desc_1" class="c-notification__message">L'élément de structure à bien été mise à jour.</p>
</div>
<div v-if="errors && errors.length">
<div v-for="error of errors" class="c-notification c-notification--danger">
{{ error.message }}
</div>
</div>
<div class="l-row l-row--gutter">
<div class="l-col">
<h1>{{ msg }} - {{ element_id }}</h1>
</div>
</div>
<loader v-if="visible"></loader>
<div class="l-row l-row--gutter" v-else>
<div class="l-col-4">
<form class="c-form full-width" #submit.prevent="updateStructureElement">
<div class="l-row">
<fieldset class="c-form__fieldset">
<legend class="c-form__legend">Remplissez le formulaire</legend>
<div class="l-row nice-top">
<div class="l-col-3 l-justify--end nice-right">
<div class="c-form__field-group">
<label for="tag" class="c-form__label">Tag <span class="s-text s-text--danger">* </span></label>
</div>
</div>
<div class="l-col-7">
<div class="c-form__field-group full-width">
<input id="tag" class="c-form__field full-width" type="text" name="tag" v-model="element.tag"/>
</div>
</div>
</div>
<div class="l-row nice-top">
<div class="l-col-3 l-justify--end nice-right">
<div class="c-form__field-group">
<label for="description" class="c-form__label">Description <span class="s-text s-text--danger">* </span></label>
</div>
</div>
<div class="l-col-7">
<div class="c-form__field-group full-width">
<textarea id="description" class="c-form__field minimal-h" name="description" v-model="element.description"></textarea>
</div>
</div>
</div>
<div class="l-row nice-top">
<div class="l-col-6 l-justify--end nice-right">
<div class="c-form__field-group">
<label for="optional" class="c-form__label">Optional <span class="s-text s-text--danger">* </span></label>
</div>
</div>
<div class="l-col-6">
<div class="c-form__field-group">
<input id="optional" class="c-form__field" type="checkbox" name="optional" v-model="element.optional"/>
</div>
</div>
</div>
<div class="l-row nice-top">
<div class="l-col-6 l-justify--end nice-right">
<div class="c-form__field-group">
<label for="repetitive" class="c-form__label">Répétitif <span class="s-text s-text--danger">* </span></label>
</div>
</div>
<div class="l-col-6">
<div class="c-form__field-group full-width">
<input id="repetitive" class="c-form__field" type="checkbox" name="repetitive" v-model="element.repetitive"/>
</div>
</div>
</div>
</fieldset>
</div>
<div class="l-row nice-top">
<div class="l-col-offset-3 l-col-7">
<button class="c-btn c-btn--primary c-btn--raised c-btn--ripple c-form__button full-width s-text--center" type="submit">Soumettre</button>
</div>
</div>
</form>
</div>
</div>
</main>
</div>
</template>
<script>
import Loader from 'gso-loader';
import {state, show, hide} from 'gso-loader/store';
import {HTTP} from '../http-common';
import ObsSidebar from './parts/sidebar.vue';
export default{
name: 'update-structure-element',
props: ['element_id'],
data() {
return {
msg: 'Mise à jour de l\'élément',
element: [],
errors: [],
updated: false
};
},
computed: {
visible() {
return state.visible;
}
},
methods: {
updateStructureElement: function () {
let seToUpdate = this.element;
console.log('To update = ' + JSON.stringify(seToUpdate));
HTTP.put('structure-element/update', seToUpdate, {headers: {'Content-Type': 'application/json'}})
.then(response => {
console.log('response = ' + response);
this.element = response.data;
this.updated = true;
})
.catch(e => {
console.log('Error = ' + e);
this.errors.push(e);
});
}
},
components: {ObsSidebar, Loader},
created() {
show();
let elementId = this.$route.params.element_id;
HTTP.get('structure-element/' + elementId)
.then(response => {
this.element = response.data;
hide();
})
.catch(e => {
this.errors.push(e);
hide();
});
}
};
</script>

Well, I've looking in some articles and changed the way I update the entity:
#PutMapping("/update")
public StructureElement update(#RequestBody StructureElement se){
StructureElement databaseElement;
logger.info("Call to StructureElementController.update with se = " + se);
this.connectToDatabase();
try{
databaseElement = this.repository.findOne(se.getId());
if(databaseElement == null){
logger.error("Could not find StructureElement to update. se = " + se);
return null;
}
// Update
databaseElement.setDescription(se.getDescription());
databaseElement.setTag(se.getTag());
databaseElement.setOptional(se.isOptional());
databaseElement.setRepetitive(se.isRepetitive());
databaseElement.getSignature().setModificationDate(new Date());
databaseElement = this.repository.save(databaseElement);
logger.info("Updated SE = " + databaseElement);
}catch (Exception e){
logger.error("Could not update structure element. se = " + se, e);
return null;
}
return databaseElement;
}
Now this works.
Seems that Spring data JPA doesnt want to update an entity like a simple JPA EntityManager....

Related

Many To one datatable spring mvc hibernate with ajax

I was trying to show the model with dataTable in Spring but how can i get the value from the #ManyToOne relationship ? Below is my code
Model file - I want to get
"private long usersId" from Users model and "private long roles_id" from Role model but i don't know how to get it out
package com.hospital.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
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 com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="users_roles")
public class Users_Roles implements Serializable{
private static final long serialVersionUID = -1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "users_roles_id", updatable = false, nullable = false)
private long users_roles_id;
#JsonIgnore
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "users_id", nullable = false, updatable = false, insertable = false, referencedColumnName = "users_id")
private Users users;
#JsonIgnore
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "roles_id", nullable = false, updatable = false, insertable = false, referencedColumnName = "roles_id")
private Role roles;
private boolean status;
public Users_Roles() {
}
public long getUsers_roles_id() {
return users_roles_id;
}
public void setUsers_roles_id(long users_roles_id) {
this.users_roles_id = users_roles_id;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
public Role getRoles() {
return roles;
}
public void setRoles(Role roles) {
this.roles = roles;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
Index file - The error appear at DataTable calling ajax json[i][1] = json[i].usersId; and json[i][2] = json[i].roles_id;
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layouts/main}">
<head>
<meta charset="ISO-8859-1">
<title>Role Assign to User</title>
<link rel="stylesheet" type="text/css" href="/static/assets/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="/static/assets/css/dataTables.bootstrap4.min.css">
</head>
<body>
<div layout:fragment="content" style="margin-right: 10px; margin-left: 10px;">
<div class="row" style="margin-top: 20px;">
<div class="col-sm-4 col-5">
<h4 class="page-title">Account</h4>
</div>
<div class="col-sm-8 col-9 text-right m-b-20">
<a th:href="${'/admin/users_roles/create'}"
class="btn btn btn-primary btn-rounded float-right"><i
class="fa fa-plus"></i> Add New</a>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table
class="table table-border table-striped custom-table mb-0" id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>Account ID</th>
<th>Role ID</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Disable confirm modal -->
<div class="modal fade" id="disableConfirm">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h4>Disable Record</h4>
</div>
<div class="modal-body">
<h4>Are you sure you want to disable this?</h4>
</div>
<div class="modal-footer">
Cancel
Confirm
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(loaddata);
function loaddata() {
$("#dataTable")
.DataTable(
{
"ajax" : {
"url" : "/admin/users_roles/list",
"type" : "GET",
"datatype" : "json",
"dataSrc" : function(json) {
for (var i = 0; i < json.length; i++) {
json[i][0] = json[i].users_roles_id;
json[i][1] = json[i].usersId;
json[i][2] = json[i].roles_id;
json[i][3] = json[i].status == 1 ? '<span class="custom-badge status-green">Active</span>' : '<span class="custom-badge status-red">Inactive</span>';
json[i][4] = "<a href='/admin/users_roles/update/"+json[i].users_roles_id+"' class='btn btn-primary btn-outline'><i class='fa fa-pencil'></i></a>"
+ " "
+ "<a href='#' onclick='DisableRecord("+ json[i].users_roles_id+")' class='btn btn-danger btn-outline'><i class='fa fa-trash'></i></a>";
}
return json;
}
},
"language" : {
"emptyTable" : "No data found, please add new"
}
});
}
//Disable
var id;
function DisableRecord(usersId) {
id = usersId;
$("#disableConfirm").modal("show");
}
function ConfirmDisable() {
$.ajax({
type : "POST",
url : "/admin/users/disable?users_roles_id=" + id,
success : function(result) {
window.location.href = "/admin/users_roles/index";
$("#disableConfirm").modal("hide");
}
})
}
</script>
</div>
</body>
</html>
Or do i have a way to get the name of the model instead of the ID ? Thank you.

Cant get view of the form in thymeleaf after put to it list of object

I have a big problem to solve and I don`t see the sollution of this, because IntelliJ not given me any log. Here is the point:
When I try to open the page with form where I put data od employee and address, address form is invisible.
My code:
View:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Dodaj nową firmę</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" th:href="#{/webjars/bootstrap/4.4.1-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.5.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/4.4.1-1/js/bootstrap.min.js}"></script>
</head>
<body>
<div style = "text-align: center;">
<h1>Dodaj nowego pracownika do bazy danych</h1>
</div>
<form class="form-horizontal" th:object="${employee}" th:action="#{/employees}" th:method="post">
<div class="container" style="margin-top:10mm;">
<div class="row">
<div class="col-sm">
<div style = "text-align: center;">
<h5>Dane osobowe</h5>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{name}"/>
<label class="control-label">Imię</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('name')}" th:errors="*{name}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{surname}"/>
<label class="control-label">Nazwisko</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('surname')}" th:errors="*{surname}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{position}"/>
<label class="control-label">Stanowisko</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('position')}" th:errors="*{position}"/></div>
</div>
<div class="form-group">
<input type="number" class="form-control" th:field="*{age}"/>
<label class="control-label">Wiek</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{nationality}"/>
<label class="control-label">Obywatelstwo</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('nationality')}" th:errors="*{nationality}"/></div>
</div>
</div>
<div class="col-sm">
<div th:object="${listAddress}">
<div style = "text-align: center;">
<h5>Dane adresowe</h5>
</div>
<div style = "text-align: center;">
<h6>Adres stały</h6>
</div>
<div th:each="row, stat : ${listAddress.addresses}">
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].type}"/>
<label class="control-label">Typ adresu</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('type')}" th:errors="*{type}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].street}"/>
<label class="control-label">Ulica</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('street')}" th:errors="*{street}"/></div>-->
</div>
<div class="form-group">
<input type="number" class="form-control" th:field="*{addresses[__${stat.index}__].streetNr}"/>
<label class="control-label">Numer domu</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('streetNr')}" th:errors="*{streetNr}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].flatNr}"/>
<label class="control-label">Numer mieszkania</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('flatNr')}" th:errors="*{flatNr}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].postalCode}"/>
<label class="control-label">Kod pocztowy</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('postalCode')}" th:errors="*{postalCode}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].city}"/>
<label class="control-label">Miasto</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('city')}" th:errors="*{city}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].country}"/>
<label class="control-label">Kraj</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('country')}" th:errors="*{country}"/></div>-->
</div>
</div>
</div>
<div style = "text-align: right;">
<button type="submit" class="btn btn-primary btn-lg active center-block">ZAPISZ</button>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Controller:
#RequestMapping("/new")
public String addNewEmployee(Model model) {
AddressesList listOfAddress = new AddressesList();
ArrayList<Address> addressesArray = new ArrayList<>();
listOfAddress.setAddresses(addressesArray);
model.addAttribute("employee", new Employee()).addAttribute("listAddress", listOfAddress);
return "new_employee_form";
}
AddressList class
public class AddressesList {
private List<Address> addresses;
public AddressesList() {
}
public AddressesList(List<Address> addresses) {
this.addresses = addresses;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
}
Address class
public class Address {
public Long idAddress;
public Long idEmployee;
public String type;
public String street;
public String streetNr;
public Integer flatNr;
public String postalCode;
public String city;
public String country;
public Address() {
}
private Address(Long idEmployee, String type, String street, Integer flatNr, String streetNr, String postalCode, String city, String country) {
this.idEmployee = idEmployee;
this.type = type;
this.street = street;
this.streetNr = streetNr;
this.flatNr = flatNr;
this.postalCode = postalCode;
this.city = city;
this.country = country;
}
public static class AddressBuilder{
private Long idAddress;
private Long idEmployee;
private String type;
private String street;
private String streetNumber;
private Integer flatNr;
private String postalCode;
private String city;
private String country;
public AddressBuilder setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
return this;
}
public AddressBuilder setType(String type) {
this.type = type;
return this;
}
public AddressBuilder setStreet(String street) {
this.street = street;
return this;
}
public AddressBuilder setFlatNr(Integer flatNr) {
this.flatNr = flatNr;
return this;
}
public AddressBuilder setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
return this;
}
public AddressBuilder setPostalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
public AddressBuilder setCity(String city) {
this.city = city;
return this;
}
public AddressBuilder setCountry(String country) {
this.country = country;
return this;
}
public Address build(){
return new Address(idEmployee, type, street, flatNr, streetNumber, postalCode, city, country);
}
}
public void setIdAddress(Long idAddress) {
this.idAddress = idAddress;
}
public void setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
}
public void setType(String type) {
this.type = type;
}
public void setStreet(String street) {
this.street = street;
}
public void setFlatNr(Integer flatNr) {
this.flatNr = flatNr;
}
public void setStreetNr(String streetNr) {
this.streetNr = streetNr;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
public Long getIdAddress() {
return idAddress;
}
public Long getIdEmployee() {
return idEmployee;
}
public String getType() {
return type;
}
public String getStreet() {
return street;
}
public Integer getFlatNr() {
return flatNr;
}
public String getStreetNr() {
return streetNr;
}
public String getPostalCode() {
return postalCode;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
#Override
public String toString() {
return "Address{" +
"idAddress=" + idAddress +
", idEmployee=" + idEmployee +
", type='" + type + '\'' +
", street='" + street + '\'' +
", flattNr=" + flatNr +
", streetNumber='" + streetNr + '\'' +
", postalCode='" + postalCode + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}
}
I get the page like this with no errors
with no address form on the right side od page.
Please help to solve this problem.
You are adding an empty list of addresses to your backing object:
ArrayList<Address> addressesArray = new ArrayList<>();
listOfAddress.setAddresses(addressesArray);
If you want the form to show up, you need to add at least one address so it has something to loop over.
ArrayList<Address> addressesArray = new ArrayList<>();
addressesArray.add(new Address());
listOfAddress.setAddresses(addressesArray);
I think I do this wrong.
When I add index to ArrayList form showed up.
#RequestMapping("/new")
public String addNewEmployee(Model model) {
AddressesList listOfAddress = new AddressesList();
ArrayList<Address> addressesArray = new ArrayList<Address>(2);
addressesArray.add(0, new Address());
addressesArray.add(1, new Address());
listOfAddress.setAddresses(addressesArray);
model.addAttribute("employee", new Employee()).addAttribute("listAddress", listOfAddress);
return "new_employee_form";
}
I want to enter a permanent and correspondence address in the form, accept the form (POST) and save it to class objects. How to do it?

Image uploading and displaying from database H2 error spring boot thymleaf

I am trying to build a Book shop website using Springboot,thymleaf,H2 embedded. When I try to upload the picture of new book category it gives me a null pointer error
this is my Category.class
#Entity
#Table(name="category")
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Size(min=1, max=90)
#Column(name="CATEGORY_NAME")
private String CategoryName;
#Lob
#Column(name="CATEGORY_PHOTO")
private byte[] CategoryPhoto;
public Category(Long id, #Size(min = 1, max = 90) String categoryName, byte[] categoryPhoto) {
super();
this.id = id;
CategoryName = categoryName;
CategoryPhoto = categoryPhoto;
}
public byte[] getCategoryPhoto() {
return CategoryPhoto;
}
public void setCategoryPhoto(byte[] categoryPhoto) {
CategoryPhoto = categoryPhoto;
}
public Category() {}
#OneToMany(mappedBy = "category", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Book> Books = new HashSet<>();
public Set<Book> getBooks() {
return Books;
}
CategoryController:
#Controller
#RequestMapping(value="/categories")
public class CategoryController {
private final Logger logger = LoggerFactory.getLogger(BookController.class);
private MessageSource messageSource;
#Autowired
private CategoryService categoryService;
#GetMapping
public String list(Model uiModel) {
logger.info("Listing categories:");
List<Category> categories = categoryService.findALL();
uiModel.addAttribute("categories", categories);
logger.info("No. of categories: " + categories.size());
return "categories";
}
#GetMapping(value = "/{id}")
public String show(#PathVariable Long id, Model model) {
Category category = categoryService.findbyID(id);
if(category.getCategoryPhoto() == null) {
logger.debug("Downloading photo for id: {} with size{}",
category.getId(), category.getCategoryPhoto().length);
}
model.addAttribute("category", category);
return "showCategory";
}
#GetMapping(value = "/new")
public String create(Model uiModel) {
logger.info("creating Category ...");
Category category = new Category();
uiModel.addAttribute("category", category);
return "updateCategory";
}
#PostMapping
public String saveCategory(#Valid Category category, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes,
Locale locale, #RequestParam(value="file", required=false) Part file) {
logger.info("Creating Category....");
if(bindingResult.hasErrors())
{
uiModel.addAttribute("message", new Message("error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
uiModel.addAttribute("Category", category);
return "categories/new";
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("Category_save_success", new Object[] {}, locale)));
logger.info("Category ID" + category.getId());
//process upload file
if(file != null) {
logger.info("File name:" + file.getName());
logger.info("File size:" + file.getSize());
logger.info("File content type:" + file.getContentType());
byte[] filecontent = null;
try
{
InputStream inputStream = file.getInputStream();
if(inputStream == null)
logger.info("File InputStream is null");
filecontent = IOUtils.toByteArray(inputStream);
category.setCategoryPhoto(filecontent);
}catch(IOException ex) {
logger.error("Error Saving uploaded file");
}
category.setCategoryPhoto(filecontent);
}
categoryService.save(category);
return "redirect:/categories/" + category.getId();
}
}
updatecategories.html page :: used for creating a new category and updating category with Name and Categoryphoto
<form class="form-horizontal" th:object="${category}" th:action="#{/categories}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Category Name</label>
<div class="col-sm-10">
<input class="form-control" th:field="*{CategoryName}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Category Photo</label>
<div class="col-sm-10">
<input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
</div>
</div>
<div class="row">
<button class="btn btn-default">Save</button>
</div>
</form>
show Categories.html page for showing the category name and photo after creating or updating
<form class="form-horizontal" th:object="${category}" th:action="#{/categories}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Category Name</label>
<div class="col-sm-10">
<input class="form-control" th:field="*{CategoryName}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Category Photo</label>
<div class="col-sm-10">
<input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
</div>
</div>
<div class="row">
<button class="btn btn-default">Save</button>
</div>
</form>
here is a image when I create a new category
error Image:
sorry for Long Question description but I want to clarify the details. Help would be appreciated.
I got the mistake I am using MessageSource without autowiring it Done that. And Adding Messages to my properties file.

Bad request error while submitting a form in Spring 4

I'm getting a 400 bad request error while submitting my form.
I'm using spring 4.0.6 version. I don't why this is happening. Please see the below error what I'm getting.
Here is my JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page isELIgnored="false" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="<c:url value='/static/js/jquery-3.3.1.js' />"></script>
<script src="<c:url value='/static/js/bootstrap.min.js' />"></script>
<script src="<c:url value='/static/js/jquery.validate.min.js' />"></script>
<script src="<c:url value='/static/js/additional-methods.min.js' />"></script>
<script src="<c:url value='/static/js/jquery.mask.js' />"></script>
<script src="<c:url value='/static/js/jquery-ui.js' />"></script>
<link href="<c:url value='/static/css/bootstrap.min.css' />" rel="stylesheet"></link>
<link href="<c:url value='/static/css/jquery-ui.css' />" rel="stylesheet"></link>
<style>
.head-color {
background: rgb(243, 246, 234);
color: #800000;
text-align:center;
}
.date-width{
width:25% !important;
}
.error{
color:red;
}
</style>
<script type="text/javascript">
$(function() {
document.getElementById("claimFilingForm").reset();
$('.phone-us').mask('(000) 000-0000');
$('.zip-code').mask('00000-0000');
$( "#phoneAssignedDate" ).datepicker();
jQuery.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg !== value;
}, "This field is required.");
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#claimFilingForm" ).validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
// valueNotEquals: "default"
},
nickname: {
required: true
},
zip: {
required: true,
zipcodeUS: true
},
phone: {
required: true,
phoneUS: true
},
email: {
required: true,
email: true
},
optradio: {
required: true
},
phoneAssignedDate: {
required: {
depends: function() {
return $('input[name="optradio"]:checked').val() == 'N';
}
}
},
signature: {
required: true
}
},
messages: {
},
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(element).css("display","");
$(placement).append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
if ($(form).valid())
{
form.submit();
}
return false; // prevent normal form posting
}
})
});
</script>
</head>
<body>
<div class="container">
<h2 class="well head-color">CLAIM FILING</h2>
<div class="form-group">
<span style="font-weight: bold; color: #875a24;">This is a claim in connection with a class of persons
who were successfully sent unsolicited Pollo Trophical Commercial text messages on
what are commonly called recycled numbers between March 1, 2012 and March 15, 2017</span>
</div>
<div class="col-lg-12 well">
<div class="row">
<form:form id="claimFilingForm" modelAttribute="claimant" method="POST" action="claimFiling">
<div class="col-sm-12">
<div class="form-group">
<span style="font-weight: bold;">1. You Must Provide Your Contact Information, including any nicknames or
aliases or any name you use to obtain mobile telephone service for you or your
family members</span>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>First Name</label>
<form:input type="text" id="firstName" name="firstName" path="firstName" placeholder="Enter First Name" class="form-control" autofocus=""/>
</div>
<div class="col-sm-6 form-group">
<label>Last Name</label>
<form:input type="text" id="lastName" name="lastName" path="lastName" placeholder="Enter Last Name" class="form-control"/>
</div>
</div>
<div class="form-group">
<label>Address</label>
<form:textarea placeholder="Enter Address" id="address" name="address" path="address" rows="3" class="form-control"></form:textarea>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label>City</label>
<form:input type="text" id="city" name="city" path="city" placeholder="Enter City Name" class="form-control"/>
</div>
<div class="col-sm-4 form-group">
<label>State</label>
<form:input type="text" id="state" name="state" path="state" placeholder="Enter State Name" class="form-control"/>
</div>
<div class="col-sm-4 form-group">
<label>Zip</label>
<form:input type="text" id="zip" name="zip" path="zip" placeholder="Enter Zip5-Zip4 Code" class="form-control zip-code"/>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>Company/Nickname/Alias</label>
<form:input type="text" id="nickname" name="nickname" path="nickname" placeholder="Enter Company/Nickname/Alias" class="form-control"/>
</div>
<div class="col-sm-6 form-group">
<label>Phone Number</label>
<form:input type="text" id="phone" name="phone" path="phone" placeholder="Enter Phone Number" class="form-control phone-us"/>
</div>
</div>
<div class="form-group">
<label>Email Address</label>
<form:input type="text" id="email" name="email" path="email" placeholder="Enter Email Address" class="form-control"/>
</div>
<div class="form-group">
<br/><br/>
<span style="font-weight: bold;">2. You Must Verify Ownership of the Number Listed Above please select one</span>
</div>
<div class="form-group radio">
<label><form:radiobutton id="optradio1" name="optradio" path="optradio" value="N" data-error="#optradio-error"/>The telephone number listed above was assigned
to me as of below mentioned date
and I did not consent to receive Pollo Trophical advertising text messages
<form:input type="text" id="phoneAssignedDate" name="phoneAssignedDate" placeholder="Select a Date" path="phoneAssignedDate" class="form-control date-width" style="cursor: pointer;" readonly="true"/></label>
</div>
<br/>
<div class="form-group radio">
<label><form:radiobutton id="optradio2" name="optradio" path="optradio" value="Y" />The number listed above was assigned to me and I consented to receive texts from Pollo Trophical</label>
</div>
<div class="form-group">
<span id="optradio-error" class="text-danger align-middle error">
<!-- Put name validation error messages here -->
</span>
</div>
<div class="form-group">
<label>Signature</label>
<form:input type="text" id="signature" name="signature" path="signature" placeholder="Enter Your Name" class="form-control"/>
</div>
<button type="submit" class="btn btn-lg btn-info">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</body>
</html>
Here is my Controller
package com.application.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.application.model.Claimant;
import com.application.service.ClaimFilingService;
#Controller
#RequestMapping("/")
public class ClaimFilingController {
#Autowired
private ClaimFilingService claimFilingService;
#RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String home(ModelMap model) {
return "redirect:/claimFiling";
}
/*
* This method will serve as default GET handler.
*/
#RequestMapping(value = { "/claimFiling" }, method = RequestMethod.GET)
public String newRegistration(ModelMap model, HttpServletRequest request) {
Claimant claimant = new Claimant();
model.addAttribute("claimant", claimant);
return "claimFiling";
}
/*
* This method will be called on form submission, handling POST request It
* also validates the user input
*/
#RequestMapping(value = { "/claimFiling" }, method = RequestMethod.POST)
public String saveRegistration(#ModelAttribute("claimant") Claimant claimant, ModelMap model, HttpServletRequest request) {
String result = claimFilingService.insertClaimDetails(claimant, request);
if(!result.equalsIgnoreCase("")) {
model.addAttribute("ClaimId", result);
return "success";
}
model.addAttribute("message","Process Failed");
return "claimFiling";
}
}
Here is my Claimant model class
package com.application.model;
import java.sql.Date;
public class Claimant {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zip;
private String nickname;
private String phone;
private String email;
private String optradio;
private Date phoneAssignedDate;
private String signature;
public Claimant(String firstName, String lastName, String address, String city, String state, String zip,
String nickname, String phone, String email, String optradio, Date phoneAssignedDate, String signature) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.nickname = nickname;
this.phone = phone;
this.email = email;
this.optradio = optradio;
this.phoneAssignedDate = phoneAssignedDate;
this.signature = signature;
}
public Claimant() {
super();
// TODO Auto-generated constructor stub
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOptradio() {
return optradio;
}
public void setOptradio(String optradio) {
this.optradio = optradio;
}
public Date getPhoneAssignedDate() {
return phoneAssignedDate;
}
public void setPhoneAssignedDate(Date phoneAssignedDate) {
this.phoneAssignedDate = phoneAssignedDate;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
}
I'm a beginner to spring so can some body help me to identify the problem.
Yes, I found the mistake. In the POJO class I changed the type of phoneAssignedDate to String. This resolved my problem :-)

Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 on updating of an entity via hibernate

When trying to update an entity from the controller, I keep getting this exception. Rest assured, thorough research regarding this exception has been made, but none of the suggestions have worked in my case.
I am trying to update the doctor entity by calling hibernate session.update(entity);
Doctor model:
#Entity
#Table(name = "tbl_doctor")
public class Doctor {
private Long id;
private PersonInfo personInfo;
private String licenseNumber;
private User user;
private String specialization;
private String employmentStatus;
private String suffix;
private List<Patient> patients;
//
// #OneToMany
// #JoinTable(name = "Doctor_Appointment", joinColumns = { #JoinColumn(name
// = "doctor_id") }, inverseJoinColumns = { #JoinColumn(name = //
// "appointment_id") })
// private List<Appointment> appointments;
public Doctor() {
super();
user = new User();
personInfo = new PersonInfo();
}
#Override
public String toString() {
String patients= "";
for(Patient p: this.patients) {
patients += p.toString();
}
return "Doctor [id=" + id + ", personInfo=" + personInfo
+ ", licenseNumber=" + licenseNumber + ", user=" + user
+ ", specialization=" + specialization + ", employmentStatus="
+ employmentStatus + ", suffix=" + suffix + ", patients="
+ patients + "]";
}
#Column(name = "fld_license_number")
public String getLicenseNumber() {
return licenseNumber;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "key_user")
public User getUser() {
return user;
}
#Column(name = "fld_specialization")
public String getSpecialization() {
return specialization;
}
#Column(name = "fld_employment_status")
public String getEmploymentStatus() {
return employmentStatus;
}
#Column(name = "fld_suffix")
public String getSuffix() {
return suffix;
}
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "key_patient")
#Fetch(value = FetchMode.SUBSELECT)
public List<Patient> getPatients() {
return patients;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "key_doctor")
public Long getId() {
return id;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "key_person_info")
public PersonInfo getPersonInfo() {
return personInfo;
}
//setters
}
Person info just includes the biodata like first name, last name, sex, birthday etc.
Controller
#RequestMapping(value="/update_doctor.it", method=RequestMethod.POST)
public String updateDoctor(HttpSession session, #ModelAttribute("doctor") Doctor doctor, Model model, #RequestParam("id") long adminId) {
System.err.println("update doctor controller");
String username = session.getAttribute("user").toString();
session.setAttribute("user", username);
doctor.getUser().setEnabled(true);
doctor.getPersonInfo().setDateModified(LocalDate.now());
doctorDao.updateDoctor(doctor);
return "redirect:/view_doctor_profile.it?id=" + doctor.getId();
}
DaoImpl
#Override
public void updateDoctor(Doctor doctor) {
Session session = sessionFactory.getCurrentSession();
session.update(doctor);
}
JSP
form:form class="docForm" method="post" commandName="doctor" action="update_doctor.it?id=${adminUser.getId() }" >
<section>
<header>
<h3>Doctor Information</h3>
</header>
<form:hidden path="id" value="${doctor.id}" />
<ul class="fields">
<li><label>First Name</label>:<form:input value="${doctor.getPersonInfo().getFirstName()}" path="personInfo.firstName" type="text" required="true" /></li>
<li><label>Last Name</label>:<form:input value="${doctor.getPersonInfo().getLastName()}" path="personInfo.lastName" type="text" required="true" /></li>
<li><label>Suffix</label>:<form:input value="${doctor.getSuffix() }" path="suffix" /></li>
<li><label>License Number</label>:<form:input value="${ doctor.getLicenseNumber() }" path="licenseNumber" /></li>
<li><label>Occupation</label>:<form:input value="${doctor.getPersonInfo().getOccupation() }" path="personInfo.occupation" /></li>
<li><label>Specialization</label>:<form:input value="${ doctor.getSpecialization() }" path="specialization" required="true"/></li>
<li><label>Date of Birth</label>:<input value="${doctor.getPersonInfo().getDateOfBirth() }" name="personInfo.dateOfBirth" type="text" id="datepicker" readonly/></li>
<li><label>Gender</label>:
<label>Male</label><form:radiobutton path="personInfo.sex" value="male"/>
<label>Female</Label><form:radiobutton path="personInfo.sex" value="female"/>
</li>
<li><label>Phone Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(0).getPhoneNumber() }" path="personInfo.contacts[0].phoneNumber"/></li>
<li><label>Mobile Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(0).getMobileNumber() }" path="personInfo.contacts[0].mobileNumber" type="text" required="true"/></li>
<li><label>E-mail Address</label>:<form:input value="${ doctor.getPersonInfo().getEmail() }" path="personInfo.email" type="text" required="true"/></li>
</ul>
</section>
<section>
<header><h3>Address</h3></header>
<ul class="fields">
<li><label>Address</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getAddress() }" path="personInfo.addresses[0].address"/></li>
<li><label>City</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getCity() }" path="personInfo.addresses[0].city"/></li>
<li><label>Province</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getProvince() }" path="personInfo.addresses[0].province"/></li>
<li><label>Zip Code</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getZipCode() }" path="personInfo.addresses[0].zipCode" /></li>
</ul>
</section>
<section>
<header><h3>Account Details</h3></header>
<ul class="fields">
<li><label>Username</label>:<form:input value="${ doctor.getUser().getUsername() }" path="user.username" required="true"/></li>
<li><label>Password</label>:<form:password value="${ doctor.getUser().getPassword() }" path="user.password" required="true"/></li>
</ul>
</section>
<section>
<header>
<h3>Hospital Details</h3>
</header>
<ul class="fields">
<li><label>Name</label>:<form:input value="${doctor.getPersonInfo().getCompanyName() }" path="personInfo.companyName"/></li>
<li><label>Employment Status</label>:
<label>Full-time</label><form:radiobutton path="employmentStatus" value="full-time"/>
<label>Part-time</Label><form:radiobutton path="employmentStatus" value="part-time"/>
</li>
<li><label>Phone Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(1).getPhoneNumber()}" path="personInfo.contacts[1].phoneNumber"/></li>
<li><label>Work Mobile Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(1).getPhoneNumber()}" path="personInfo.contacts[1].mobileNumber" /></li>
<li><label>Address</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getAddress() }" path="personInfo.addresses[1].address" /></li>
<li><label>City</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getCity() }" path="personInfo.addresses[1].city"/></li>
<li><label>Province</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getProvince() }" path="personInfo.addresses[1].province" /></li>
<li><label>Zip Code</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getZipCode() }" path="personInfo.addresses[1].zipCode" />
</ul>
</section>
<section>
<ul class="btnForm">
<li><span class="btn"><input type="submit"
value="Save" class="btnS"></span></li>
<li><span class="btn"><input type="button"
value="Cancel" class="btnCancel" onClick="viewPotentialsList()"></span></li>
</ul>
Error
SEVERE: Servlet.service() for servlet [emrMVC] in context with path [/emr] threw exception [Request processing failed; nested exception is org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1] with root cause
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:657)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:475)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:270)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy27.updateDoctor(Unknown Source)
at com.ust.emr.controller.admin.EditDoctorController.updateDoctor(EditDoctorController.java:56)
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.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I figured it out. A lot of classes or entities are dependent on the doctor, the entity I'm updating. In order for the batch update to execute successfully, I had to place a on the jsp, fetching all the ids of the dependent classes. Thank you!

Resources