TCB - RESTFul CRUD With A Pinch of AJAX and Hibernate
TCB - RESTFul CRUD With A Pinch of AJAX and Hibernate
com
TCB
RESTFul CRUD with a pinch of AJAX and Hibernate thecodebu
TCB
About Me
thecode
View my co
Hello Buddies...
FB Page
Find me o
A commonly known task developers generally come across for sure, in their coding tenure, is working with the REST APIs.
Get code o
While consuming these can be easy, thanks to various tools like POSTMAN and SOAPUI, what can be challenging is writing
Follow
these APIs. We can go through so many online materials available these days that can share ins and outs of the REST
architecture, but what we want is to save time and get the code working. So here we set the stage for this discussion.
html-css-b
What I am going to follow is an approach that will pick 4 commonly asked-for HTTP methods - POST, GET, PUT, DELETE
(for Create, Read, Update and Delete respectively), with a few bonus code snippets for you - using AJAX for making calls
from the JSPs and our very own Mr. Popular - Hibernate. This will make you get your hands dirty, over the journey, with
database related tasks using Hibernate and MySQL workbench.
Exam 48
Issuer: M
Provided
The above plan is not going to cost you anything, but it demands satisfactory code writing and mind-boggling for behind Acclaim
the scenes' theory.
Contact fo
https://github.com/namitsharma99/restHibernateCRUD Name
Email *
You are welcome if you still wish to have a discussion. Let's start.
Message *
1. Do we have DB ready?
Send
Make good use of MySQL workbench and have a local schema up and available with your table that you wish to use further.
Here, we have 'myEmployees' under 'namit_schema' and the table records will be impacted by the CRUD UI operations.
Blog archi
A snapshot of the table currently in my local - ► 2020 (6
► 2018 (7
▼ 2017 (3
► Nove
► Octo
► July
► June
► May
► April
▼ Marc
STRU
IMA
DO
SERV
CREATE TABLE `myEmployees` ( DA
UP
DO
`id` int(11) NOT NULL, Epic
one
com
`firstName` varchar(255) DEFAULT NULL,
Write
jav
`lastName` varchar(255) DEFAULT NULL, Writin
jav
`myEmployees`.`lastName` Mesm
Read
jav
FROM `namit_schema`.`myEmployees`;
Read
jav
Binar
Imp
Jav
Linea
Don't mind the vague entries :P Imp
Jav
White
Please note - Keep the DB credentials handy. Un
ECST
MAG
WSO
2. Are we ready to integrate our JAVA code with the DB? Pa
Me
JAVA
can
usi
For fun, we will be using Hibernate for this task. You are free to use other techniques like pure JDBC or JPA.
Javas
Ma
Op
Following some commonly available tutorials, I saved time and got the hibernate connection up and running. REST
pin
Hib
► Febr
Please note - Since consuming requisite jars can be a headache, hence it's always better to go for a maven project with the
dependencies listed in pom.xml. ► 2016 (3
POM.xml
custom cla
on to cover
Create the backing bean
using mous
Complete c
package com.myBeans; https:/...
code writte
private int id; very basic
complete c
time. A com
return id; developers
}
JAVA code
comparison
Hello Budd
public String getFirstName() {
useful piec
you in hand
comparison
return firstName;
O(n^2) vs O
the max co
numerical S
}
Hello Budd
question re
so thought
public void setFirstName(String firstName) {
Given a str
this.firstName = firstName;
Search Th
}
Blog archi
return lastName;
► 2020 (6
► 2018 (7
}
▼ 2017 (3
► Nove
public void setLastName(String lastName) {
► Octo
} ► May
► April
} ▼ Marc
STRU
IMA
DO
SERV
DA
Set up the 2 essential XMLs here - UP
DO
Epic
one
com
a. employee.hbm.xml
Write
jav
Writin
jav
<?xml version="1.0" encoding="UTF-8"?>
JAVA
-A
<!DOCTYPE hibernate-mapping PUBLIC FO
JAVA
-T
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" &D
JAVA
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> -H
JAVA
-S
<hibernate-mapping>
JAVA
-R
<class name="com.myBeans.Employee" table="myEmployees"> SIM
Dream
<id name="id"> Mesm
Read
jav
<generator class="increment"></generator>
Read
jav
</id>
Binar
Imp
Jav
<property name="firstName"></property>
Linea
Imp
<property name="lastName"></property> Jav
White
</class>
Un
ECST
</hibernate-mapping> MAG
WSO
Pa
b. hibernate.cfg.xml Me
JAVA
can
usi
Javas
<?xml version="1.0" encoding="UTF-8"?>
Ma
Op
<!DOCTYPE hibernate-configuration PUBLIC REST
pin
Hib
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
► Febr
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> ► 2016 (3
<hibernate-configuration>
Newsletter
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:XXXX/namit_schema</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Why not. As a good practice, have atleast 3 layers (especially for enterprise app projects). Here we can have Service
Classes <-> Facade Layers <-> DAO Layers.
EmployeeService.java
This class will provide you the API declarations and will help in providing endpoints per various http methods.
package com.myCode;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.json.simple.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
/**
* @author namit
*
Head First
* */ A...
INR 870.0
@Path("/employees") Shop n
/**
*
* */
@GET
@Produces("text/html")
return Response.status(200).entity(output).build();
/**
* */
@GET
@Path("list")
@Produces("application/json")
try {
output = serviceFacade.getEmployees();
output = jsonError.toJSONString();
}
} catch (JsonProcessingException e) {
e.printStackTrace();
return Response.status(200).entity(output).build();
/**
* */
@POST
@Path("/save")
@Consumes("application/json")
map.put("firstname", fname);
map.put("lastname", lname);
serviceFacade.saveEmployees(map);
return Response.status(201).entity(result).build();
}
/**
* */
@PUT
@Path("/update")
@Consumes("application/json")
String id = inputArray[0].split("=")[1];
map.put("id", id);
map.put("firstname", fname);
map.put("lastname", lname);
serviceFacade.updateEmployees(map);
return Response.status(201).entity(result).build();
/**
* */
@DELETE
@Path("/delete")
@Consumes("application/json")
int i = Integer.valueOf(str.split("=")[1]);
serviceFacade.deleteEmployee(i);
return Response.status(200).entity(result).build();
ServiceFacade.java -
This class acts as an intermediate step while passing data from front end to the backend and vice versa. It can be
advantageous if we need to alter the request/ response as per destination methods.
package com.myFacade;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myBeans.Employee;
import com.myDB.ServiceDAO;
/**
* @author namit
*
* */
public class ServiceFacade {
List<Employee> ls = serviceDAO.getEmployees();
return jsonStr;
serviceDAO.saveEmployees(map);
serviceDAO.updateEmployees(map);
serviceDAO.deleteEmployee(i);
ServiceDAO.java -
package com.myDB;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import com.connectors.HibernateConnector;
import com.myBeans.Employee;
/**
* @author namit
*
* */
@SuppressWarnings("deprecation")
@SuppressWarnings({ "unchecked" })
session = HibernateConnector.getInstance().getSession();
return null;
} else {
session.beginTransaction();
employee.setFirstName(fname);
employee.setLastName(lname);
session.save(employee);
session.getTransaction().commit();
session.close();
session.beginTransaction();
employee.setId(id);
employee.setFirstName(fname);
employee.setLastName(lname);
session.update(employee);
session.getTransaction().commit();
session.close();
session.beginTransaction();
Employee e = (Employee) o;
session.delete(e);
session.getTransaction().commit();
session.close();
Since we are using Hibernate for DB access, I wanted to have a common place for Hibernate connection, hence following
class came into the picture.
HibernateConnector.java
package com.connectors;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
cfg.configure("hibernate.cfg.xml");
cfg.addResource("employee.hbm.xml");
sessionFactory = cfg.buildSessionFactory();
}
public static synchronized HibernateConnector getInstance() throws HibernateException {
if (hibConn == null) {
return hibConn;
if (!session.isConnected()) {
this.reconnect();
return session;
this.sessionFactory = cfg.buildSessionFactory();
Once you have your code in place, your project folder structure may look somewhat like this -
Please ignore the com.ignore package, it was just for created to see some if-else flows, I came across in an interview for a
big investment firm. Have a look if that interests you, I will share more of such questions if someone needs.
Anyway, coming back to our quest, now we have the code ready, I mean from APIs perspective.
Have a look at the javadocs for service class, you will get an idea what API to hit, to check the response directly through
the browser.
Well that's said, now its time to try some UI related stuff to make you proficient at both backend as well as front end.
What I have came across so far is that majority of java developers are assigned evaluation projects during onboarding
times, to come up with APIs and UI to consume them.
So the below section of the discussion will help you to get a taste of such assignment.
welcome.jsp
<html>
<head>
<title>Welcome Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function getList() {
$("#loaderDiv").attr("style", "display: block");
url: "rest/employees/list",
type: "GET"
});
request.done(function(msg) {
console.log("Request successful!");
$("#drop").empty();
});
request.fail(function(jqXHR, textStatus) {
});
function prepareEdit() {
console.log('The option with value ' + $("#drop").val() + ' and text ' + $("#drop option:selected").text() + ' was sele
$("#editId").val($("#drop").val());
$("#editFName").val(splittedSource[0]);
$("#editLName").val(splittedSource[1]);
function updateName() {
url: "rest/employees/update",
type: 'PUT',
data: {
id: $("#editId").val(),
fname: $("#editFName").val(),
lname: $("#editLName").val()
});
request.done(function(msg) {
getList();
});
request.fail(function(jqXHR, textStatus) {
});
function deleteName() {
url: "rest/employees/delete",
type: 'DELETE',
data: {
id: $("#editId").val()
});
request.done(function(msg) {
getList();
request.fail(function(jqXHR, textStatus) {
});
function addName() {
function hide() {
function hide2() {
function add() {
url: "rest/employees/save",
type: 'POST',
data: {
fname: $("#addFName").val(),
lname: $("#addLName").val()
});
request.done(function(msg) {
hide();
});
request.fail(function(jqXHR, textStatus) {
</script>
</head>
<body>
<h3>Hello Buddies</h3>
</div>
</div>
</div>
<hr>
<hr>
<a href="#" onclick="hide2()" style="color: red; font-size: 18px"> <span class="glyphicon glyphicon-remove-sign"></span
<br> </div>
<hr>
<label>EmpID : </label>
<br>
<label>FNAME : </label>
<input id="editFName">
<br>
<label>LNAME : </label>
<input id="editLName">
<br>
<label>EDIT : </label>
<br>
<label>DELETE : </label>
<br>
<!-- option to use for using hidden variable as local storage -->
<hr>
<label>FNAME :</label>
<input id="addFName">
<br>
<label>LNAME :</label>
<input id="addLName">
<br>
<label>ADD : </label>
<a href="#" onclick="hide()" style="color: red; font-size: 18px"> <span class="glyphicon glyphicon-remove-sign"></span>
<br> </div>
</div>
</body>
</html>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.myCode</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
This will give your application a nice UI for interacting with the APIs already created. Some of the screenshots I took while
going through this app are -
So buddies, go ahead and try this out.
We will soon discuss about the UI components, why they are being used and how they are makig life easier.
Your suggestions and thoughts are always welcome, and will surely improve my knowledge as well. ;)
Happy Coding....
Labels: AJAX, Bootstrap, eclipse, Hibernate, HTTP GET POST PUT DELETE, Java, JSP, MySQL, Path Annotations, REST, Workbench
No comments:
Post a comment
Featured post
How to take backup of MYSQL tables daily and remove the older backups
In day to day heavy transactions happening in our DB, we sometimes wish to retain the previous states of the tables. This not only prevents ...
WSO2 ESB - How to use PayloadFactory Mediator
How to use PayloadFactory Mediator As per the WSO2-ESB documentation of PayloadFactory Mediator, it is stated that this me...
JAVASCRIPT SAMPLES - TIC TAC TOE GAME & DYNAMIC TABLE CREATION IN JSP
Hello Buddies. It's time to play tic-tac-toe, but this time, not with pen and paper. We will create our own page that allows us to ...
Labels
AJAX algo Amazon Web Services Android Angular 2 Angular Components Apache httpd apache poi API API GATEWAY APK Automate build AWS AWS and Gmail AWS Email AWS Lambda AWS Lambda No
SES backup binary search binary tree Bootstrap browser issue BST chat Cheat sheet chrome class mediator cloning code code-snippet Complexity Analysis concurrency consumer core java css CSV cu
structures Data Structures and Algorithms database management deep download DSA DTMF eclipse EDM Electronic Digital Music electronic music Electronics Enum epic violins ESB esb5 event
fedora file firefox foreach mediator game games Git Git Hub Git Lab Git Repo Go Go Tutorials GoLang hello world Hibernate hip hop html HTTP GET POST PUT DELETE J2EE Java JAVA.
Jenkins jquery jQuery in Angular 2 JS JSP kafka KEYGEN LAMBDA linear search mediation messaging microservices mozilla MSTSC multi threading MySQL NG-2 NODEJS NPM Path Annotations Payload
PUTTY quick reference read text file read write csv remote access REST S3 schedulers sequence Server shallow shooting game small programs snake game socket programming Speech to Text springboot S
questions tables text file writer thecodebuddy tic-tac-toe game time complexity topic Trance TUNNEL unix upload version-check white paper WINDOWS Workbench WSO2 WSO2 ESB XML JSON transformation
Awesome Inc. theme. Powered by Blogger.