Crud operation basically refers to create, read, update and delete as insert a data or record, get or search data, modify data or record and delete a record. Crud has standardized the use of HTTP action verbs.
• POST as an insert data
• GET as a read/retrieve data
• PUT as an update data
• DELETE as a delete data
What is JAX-RS ?
JAX-RS is a JAVA-based programming language API and specification that allows RESTful Web Services to be established.
Follow these steps
step1
• Open eclipse ide.
• Create a maven project.
• Select org.glassfish.jersey.archetypes
as a group id and select jersey-quickstart-webapp
as an artifact id.

• Then wait a few minutes to download project-related files.

• Add tomcat server (version 10 recommended).

• After creating the project you will have an error called The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path
• To solve that error right click on project -> properties ->Project Facets -. Runtime and select the server.

Step 2 — create classes.
You need to create Resource (POJO Class), Model, and Service classes.
• Expand src/main/java
and right click on com.favtuts.rest.crud
• Select new -> class
• Then name your Resource class and create a package name.

🔺 (my Resource class name CrudResourse and Resource package name com.favtuts.rest.crud.resource).
🔺 (my Model class name CrudModel and Model package name com.favtuts.rest.crud.model)
🔺 (my Service class name CrudService and Service package name com.favtuts.rest.crud.service)
Step 3
• Complete model class with related attributes and add fields (attributes) on entity class with empty constructor, a constructor with parameters, getters, and setters.
package com.favtuts.rest.crud.model; public class CrudModel { private int id; private String name; private int age; public CrudModel() { super(); } public CrudModel(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
• Now go to Resource class and add @Path annotation to the Resource class.
The value of the @Path annotation is a relative URI path identifying the location of the Java class.
• Then add @Path(),@POST, and @Consumes() annotation for insert data. Inside the @Consumes annotation bracket, you need to add transmitting data format between client and server called JSON or XML. Here I use JSON format. Therefore your @Consumes annotation should be @Consumes(MediaType.APPLICATION_JSON)
• Then need to go to pom.xml and uncomment following dependency to get json support.
<!-- uncomment this to get JSON support --> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-binding</artifactId> </dependency>
• Now type following method.
package com.favtuts.rest.crud.resource; import com.favtuts.rest.crud.model.CrudModel; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.MediaType; @Path("/crud") public class CrudResource { @Path("/insertion") @POST @Consumes(MediaType.APPLICATION_JSON) public CrudModel addUser(CrudModel user) { } }
• Then go to service class and make a database connection
Before that you remember to add dependency to pom.xml
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.4</version> </dependency>
package com.favtuts.rest.crud.service; import java.sql.Connection; import java.sql.DriverManager; public class CrudService { Connection con; public CrudService() { try { String url = String.format("jdbc:mysql://localhost:3306/users"); String uname = "root"; String pwd = ""; Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection(url, uname, pwd); } catch (Exception e) { System.out.println(e + "data insert unsuccess."); } } }
• Now create a method for insert data into the database and add relevant insert queries.
package com.favtuts.rest.crud.service; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import com.favtuts.rest.crud.model.CrudModel; public class CrudService { Connection con; ... public CrudModel insertUser(CrudModel user) { String insert = "insert into person(name, age) values(?, ?)"; try { PreparedStatement ps = con.prepareStatement(insert); ps.setString(1, user.getName()); ps.setLong(2, user.getAge()); ps.execute(); } catch (Exception e) { System.out.println(e + "data insert unsuccess."); } return user; } }
• Then go to Resource class and create an object of service class to get insert method in the service class. And add return type inside the resource class method.
package com.favtuts.rest.crud.resource; import com.favtuts.rest.crud.model.CrudModel; import com.favtuts.rest.crud.service.CrudService; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.MediaType; @Path("/crud") public class CrudResource { CrudService service = new CrudService(); @Path("/insertion") @POST @Consumes(MediaType.APPLICATION_JSON) public CrudModel addUser(CrudModel user) { return service.insertUser(user); } }
Step 4 — retrieve data ,update and delete
· Now on Resource class, you need to add the following methods. In here @GET uses for retrieve data, @PUT for update data, and @DELETE for delete data.
· Third method uses to retrieve specific data from the database. @Path(“/retrieveById/{id}”) end of the URL you need to add id value for retrieve record according to added id value.
package com.favtuts.rest.crud.resource; import java.sql.SQLException; import java.util.ArrayList; import com.favtuts.rest.crud.model.CrudModel; import com.favtuts.rest.crud.service.CrudService; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/crud") public class CrudResource { CrudService service = new CrudService(); @Path("/insertion") @POST @Consumes(MediaType.APPLICATION_JSON) public CrudModel addUser(CrudModel user) { return service.insertUser(user); } @Path("/retrieve") @GET @Produces(MediaType.APPLICATION_JSON) public ArrayList<CrudModel> getUser() throws SQLException { return service.getUser(); } @Path("/retrieveById/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public ArrayList<CrudModel> getUser(@PathParam("id") int id) throws SQLException { return service.getUserById(id); } @Path("/updateUser") @PUT @Consumes(MediaType.APPLICATION_JSON) public CrudModel updateUser(CrudModel user) { return service.updateUser(user); } @Path("/deleteUserById/{id}") @DELETE @Consumes(MediaType.APPLICATION_JSON) public int deleteUser(@PathParam("id") int id) { return service.deletUser(id); } }
· Now go to the Service class and add the following methods.
package com.favtuts.rest.crud.service; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.favtuts.rest.crud.model.CrudModel; public class CrudService { Connection con; public CrudService() { try { String url = String.format("jdbc:mysql://localhost:3306/users"); String uname = "root"; String pwd = ""; Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection(url, uname, pwd); } catch (Exception e) { System.out.println(e + "data insert unsuccess."); } } public CrudModel insertUser(CrudModel user) { String insert = "insert into person(name, age) values(?, ?)"; try { PreparedStatement ps = con.prepareStatement(insert); ps.setString(1, user.getName()); ps.setLong(2, user.getAge()); ps.execute(); } catch (Exception e) { System.out.println(e + "data insert unsuccess."); } return user; } public ArrayList<CrudModel> getUser() throws SQLException { ArrayList<CrudModel> data = new ArrayList<CrudModel>(); String select = "select * from person"; PreparedStatement ps = con.prepareStatement(select); ResultSet rs = ps.executeQuery(); while(rs.next()) { CrudModel model = new CrudModel(); model.setId(rs.getInt("id")); model.setName(rs.getString("name")); // column name model.setAge(rs.getInt("age")); data.add(model); } return data; } public ArrayList<CrudModel> getUserById(int id) throws SQLException { ArrayList<CrudModel> data = new ArrayList<CrudModel>(); String select = "select * from person where id = ?"; PreparedStatement ps = con.prepareStatement(select); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); while(rs.next()) { CrudModel model = new CrudModel(); model.setId(rs.getInt("id")); model.setName(rs.getString("name")); // column name model.setAge(rs.getInt("age")); data.add(model); } return data; } public CrudModel updateUser(CrudModel user) { String insert = "update person set name=?, age=? where id=?"; try { PreparedStatement ps = con.prepareStatement(insert); ps.setString(1, user.getName()); ps.setLong(2, user.getAge()); ps.setInt(3, user.getId()); ps.executeUpdate(); } catch (Exception e) { System.out.println(e + "data insert unsuccess."); } return user; } public int deletUser(int id) { String insert = "delete from person where id=?"; try { PreparedStatement ps = con.prepareStatement(insert); ps.setInt(1, id); ps.executeUpdate(); } catch (Exception e) { System.out.println(e + "data insert unsuccess."); } return id; } }
Step 7 — run the project
Add tomcat server to the project
While build the project with Maven, you may encounter some errors
- class file has wrong version 55.0, should be 52.0
- invalid target release: 1.11
- Maven error – invalid target release: 1.11
- https://winterbe.com/posts/2018/08/29/migrate-maven-projects-to-java-11-jigsaw/
- https://youtu.be/kOPqQNQq-iQ
- https://stackoverflow.com/questions/65395942/fatal-error-compiling-invalid-target-release-11-during-pushing-to-heroku
- https://stackoverflow.com/questions/49398894/unable-to-compile-simple-java-10-java-11-project-with-maven
- jakarta.activation.DataSource was not found
Prepare Database
CREATE TABLE `person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `age` int(11) NOT NULL, `name` varchar(256) NOT NULL, PRIMARY KEY (`id`), KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

Testing by postman/cUrl
- Insert = http://localhost:8080/crud/webapi/crud/insertion
- Get = http://localhost:8080/crud/webapi/crud/retrieve
- Get by id = http://localhost:8080/crud/webapi/crud/retrieveById/value
- Update =http://localhost:8080/crud/webapi/crud/updateUser
- Delete = http://localhost:8080/crud/webapi/crud/deleteUserById/value
Insert data
curl --location --request POST 'http://localhost:8080/jax-rs-crud-operation/webapi/crud/insertion' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Favtuts",
"age": 30
}'
Get data
curl --location --request GET 'http://localhost:8080/jax-rs-crud-operation/webapi/crud/retrieve'
Get data by id
curl --location --request GET 'http://localhost:8080/jax-rs-crud-operation/webapi/crud/retrieveById/3'
Update data
curl --location --request PUT 'http://localhost:8080/jax-rs-crud-operation/webapi/crud/updateUser' \
--header 'Content-Type: application/json' \
--data-raw '{
"id":2,
"name": "Max Well",
"age": 18
}'
Delete Data
curl --location --request DELETE 'http://localhost:8080/jax-rs-crud-operation/webapi/crud/deleteUserById/1'
Download Source Code
$ git clone https://github.com/favtuts/java-jax-rs-tutorials.git
$ cd jax-rs-crud-operation