How to Update the data in database by using Angular JS in Spring Mybatis without using X-Editable


What is Spring?
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.

I will create simple web application using SpringMVC +MyBatis + AngularJS to show Update data for View page.

1.Create JSP File:

Create a folder named “jsp” under WEB-INF (This is where the jsp files will be created as indicated in the dispatcher-servlet.xml for the InternalResourceViewResolver bean).

By using Angular Js we can design below screen:



Whenever, Clicking on edit button it just shows the Update and Cancel button.


Related to UI page we can see the code as shown in below:
<div class="generic-container" id="reg" ng-controller="myclr ">
<div class="panel panel-default" id="reg">
<div class="panel-heading" id="reg">
<span class="lead">Personal Details </span>

</div>
<br>
<div class="formcontainer">
<table class="table table">

<tr id="style">
<th>FIRST NAME:</th>
<th>LAST NAME:</th>
<th>EDUCATIONAL QUALIFICATIONS:</th>
<th></th>
</tr>
<tr>
<td>
<div ng- hide="editingData[userData.AppEmail]">{{userData.Firstname}}</div>
<div ng-show="editingData[userData.AppEmail]">
<input type="text" ng-model="userData.Firstname" />
</div>
</td>
<td>
<div ng-hide="editingData[userData.AppEmail]">{{userData.Lastname}}</div>
<div ng-show="editingData[userData.AppEmail]">
<input type="text" ng-model="userData.Lastname" />
</div>
</td>

<td>
<div ng-hide="editingData[userData.AppEmail]">{{userData.Educationalqualification}}</div>
<div ng-show="editingData[userData.AppEmail]">
<select ng-model="userData.Educationalqualification"class="selectBox" id="userData.Educationalqualification"name="userData.Educationalqualification" required=""
ng-options="x for x in Educationalqualification"style='margin-left: -1px;'></select>
</div>
</td>
<td><span id="col">
<button ng-hide="editingData[userData.AppEmail]"class="btn btn-primary custom-width" id="addb"
ng-click="modify(userData)">Edit</button>

<button ng-show="editingData[userData.AppEmail]"
class="btn btn-primary custom-width" id="addb" ng-click="update(userData)">Update</button>

<button ng-show="editingData[userData.AppEmail]"
class="btn btn-primary custom-width" id="addb" ng-click="cancel(userData)">Cancel</button>

</span></td>
</tr>

</table>
</div>
</div></div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set : set,
get : get
}
});
app.controller('myclr', myclr);

myclr.$inject = [ '$scope', 'myService', '$http' ];

function myclr($scope, myService, $http) {
$scope.Educationalqualification = [ "MBA", "MCA", "B.TECH/BE","M.TECH" ];


// Click on edit button its shows the update and cancel buttons by depending upon the ng-click ID.

$scope.editingData = {};

if ($scope.tableData != undefined) {
for (var i = 0; i < $scope.tableData.length; i++) {

$scope.editingData[$scope.tableData[i].AppEmail] = false;
}
}

$scope.modify = function(userData) {
$scope.editingData[userData.AppEmail] = true;
};

$scope.cancel = function(userData) {
console.log('Canceled editing', userData.AppEmail);
$scope.editingData[userData.AppEmail] = false;
};
//Editable text boxes are appeared when click on the edit button, Now we can update the data and the data can be stored in database

$scope.update = function(userData) {
$scope.editingData[userData.AppEmail] = false;
var userdata = {};
userData["email"] = $scope.userData['AppEmail'];
userData["Firstname"] = $scope.userData['Firstname'];
userData["Educationalqualification"] = $scope.userData['Educationalqualification'];
userData["Lastname"] = $scope.userData['Lastname'];


$http
.post(
"http://localhost:8021/StudentJobApplication/CourseService/courseupdatestudentdetails",
userData)
.success(
function(response) {
var data = {};
data["email"] = $scope.userData['AppEmail'];
$http
.post(
"http://localhost:8021/StudentJobApplication/CourseService/coursegetpersonaldetails",
data)
.success(
function(response) {
response = JSON.stringify(response);
var myObj = JSON.parse(response);
getresponse = JSON.stringify(myObj.getstudentlist);
localStorag.removeItem("userData");
localStorage.setItem("userData",getresponse);
$scope.userData = JSON.parse(localStorage.getItem("userData"));
$scope.userData = $scope.userData[0];
});
}), function myError(response) {
alert("Error");
};
};

2.Create packages for Controller, Model, Service and Mappers:

Create packages each for the Spring Controller, Model and Service classes under the src/main/java folder. Also create a package for the MyBatis Mapper class under the same src/main/java folder.
A sample snapshot of the project after the package creation is as shown below:


3.Create classes for Model Tier:

Create a POJO class named Student.java  and StudentModel.java inside the package com.mybatis.model to include the details of the Student model entity during login.
StudentModel.java:
package com.mybatis.model;
public Student
  {
     // no need of getters and setters
}
Instead of this just create an interface for the model
4.StudentMapper.java:
package com.mybatis.mapper;
import java.util.List;
import java.util.Map;
public interface StudentMapper
  {
void getupdatedetails(Map guiMapMessage);
}
5.MyBatis Mapper:
A Mapper in MyBatis framework is similar to the Repository tier in a Spring environment. Crude SQL queries takes its place here. Create an interface class named  StudentMapper.java inside the package com.mybatis.mapper to support the database operations.
studentmapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC '-//mybatis.org//DTD Mapper 3.0//EN'
 'http://mybatis.org/dtd/mybatis-3-mapper.dtd'>
<mapper namespace='com.mybatis.mappers.StudentMapper'>
  <update id="getupdatedetails" parameterType="java.util.Map">
update student set Firstname=#{Firstname},Lastname=#{Lastname},Educationalqualification=#{Educationalqualification} where AppEmail= #{email};
</update>
</mapper>
where  Firstname, Lastname, Educationalqualification are the field names or column names in MYSQL DB and where class condition should be mentioned in ng-model name in view page.
6.Create classes for Service Tier:
Create an interface class named StudentService.java inside the package com.mouri.service to support the service tier operations.
StudentService.java :
package com.mouri.service;
import java.util.List;
import java.util.Map;
 public interface StudentService
 {
void getupdatedetails(Map guiMapMessage);
 }
7.Create a service tier implementation :
Create a service tier implementation class (a POJO indeed) named StudentServiceImpl.java
inside the package com.mouri.serviceImpl. This is where the application logic goes –
either to select the student details into the database.
StudentServiceImpl.java:
package com.mouri.serviceImpl;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.mybatis.mappers.StudentMapper;
import com.mouri.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService
{
@Autowired
private StudentMapper studentMapper;
@Autowired
@Qualifier("studentSessionFactory")
private SqlSessionFactoryBean studentSessionFactory;
//Update data
@Override
public void getupdatedetails(Map guiMapMessage) {
// TODO Auto-generated method stub
System.out.println("updaetStudentdetailsSuccessfully.....");
studentMapper.getupdatedetails(guiMapMessage);
}
}
8.Create class for Controller Tier:
Create a Controller tier POJO class named StudentController.java inside the package
controller:
RESTful Web services controller is the way the HTTP response body is created.
REST Web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML.
StudentController.java :
@Controller
@RequestMapping(value = { "/CourseService" })
public class StudentController {
@Autowired
private StudentService studentService;
public static Map<String, Object> jsonToMap(String jsonStr) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject(jsonStr);
if (jsonObject != null )
{
retMap = toMap(jsonObject);
}
return retMap;
   }
//General method to convert JSON object to Map.
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
  Map<String, Object> map = new HashMap<String, Object>();
 Iterator<String> keysItr = object.keys();
 while (keysItr.hasNext()) {
  String key = keysItr.next();
  Object value = object.get(key);
    if (value instanceof JSONArray)
                       {    value = toList((JSONArray) value);
                       }
                  else if (value instanceof JSONObject)
       {
        value = toMap((JSONObject) value);
       }
map.put(key, value);
}
 return map;
}
//General method to convert JSONArray to Map.
public static List<Object> toList(JSONArray array) throws JSONException {
 List<Object> list = new ArrayList<Object>();
 for (int i = 0; i < array.length(); i++) {
  Object value = array.get(i);
  if (value instanceof JSONArray) {
   value = toList((JSONArray) value);
  } else if (value instanceof JSONObject) {
   value = toMap((JSONObject) value);
  }
  list.add(value);
 }
 return list;
}
@RequestMapping(value = {
"/courseupdatestudentdetails" }, method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody Map courseupdatestudentdetailsEntry(@Valid @RequestBody String requestBody,
HttpSession session) {
Map returnMapMessage = new HashMap();
try {
Map guiMapMessage = jsonToMap(requestBody);
System.out.println(guiMapMessage);
// Map searchMap = (Map)guiMapMessage.get("search");
studentService.getupdatedetails(guiMapMessage);
} catch (Exception e) {
e.printStackTrace();
returnMapMessage.put("result", "error");
returnMapMessage.put("errortext",
"Internal Application Error. Contact Administrator. Error RefId : " + e.getMessage());
}
return returnMapMessage;
}
       Whenever we run the application first of all it hits the service and then it pass the call to controller, where it will perform the required action and then calls the mapping resource in order to update the data in database which will turn and displays the data on UI part.
Here,
If you want dispatcher-servlet.xml, web.xml, config.xml, please click to refer below link.
Getting the data from the database on UI page:
A Sample snapshot as shown below.


Thanks & Regards,
Chandrika Muddigari,
Technical Trainee,
MOURI Tech PVT LTD.
http://www.mouritech.com/




















Comments