I am new to web services. Please give suggestions how to insert and retrieve data from database using jersey JAX - RS in java?
JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013. JAX-RS uses annotations available from Java SE 5 to simplify the development of JAVA based web services creation and deployment.
The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services. Developers decorate Java programming language class files with JAX-RS annotations to define resources and the actions that can be performed on those resources.
The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.
Below is an example of a JAX-RS service implemented as a session bean using JPA for persistence and JAXB for messaging might look like.
CustomerService
package org.example;
import java.util.List;
import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@Stateless
@LocalBean
@Path("/customers")
public class CustomerService {
@PersistenceContext(unitName="CustomerService",
type=PersistenceContextType.TRANSACTION)
EntityManager entityManager;
@POST
@Consumes(MediaType.APPLICATION_XML)
public void create(Customer customer) {
entityManager.persist(customer);
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{id}")
public Customer read(@PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}
@PUT
@Consumes(MediaType.APPLICATION_XML)
public void update(Customer customer) {
entityManager.merge(customer);
}
@DELETE
@Path("{id}")
public void delete(@PathParam("id") long id) {
Customer customer = read(id);
if(null != customer) {
entityManager.remove(customer);
}
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("findCustomersByCity/{city}")
public List<Customer> findCustomersByCity(@PathParam("city") String city) {
Query query = entityManager.createNamedQuery("findCustomersByCity");
query.setParameter("city", city);
return query.getResultList();
}
}
Customer
Below is an example of one of the entities. It contains both JPA and JAXB annotations.
package org.example;
import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Set;
@Entity
@NamedQuery(name = "findCustomersByCity",
query = "SELECT c " +
"FROM Customer c " +
"WHERE c.address.city = :city")
@XmlRootElement
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private long id;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
private Address address;
@OneToMany(mappedBy="customer", cascade={CascadeType.ALL})
private Set<PhoneNumber> phoneNumbers;
}
For More Information
UPDATE
what are the jars required
You can deploy a JAX-RS/EJB/JPA/JAXB application to any Java EE 6 compliant application server without requiring any additional server set up. Programming the client you can get the JAX-RS APIs from the Jersey (http://jersey.java.net/), and the JPA and JAXB APIs from EclipseLink (http://www.eclipse.org/eclipselink/).
and where the database connections is written
JDBC Resource & Connection Pool
You need to configure a connection pool on your application server. Below are the steps to do this on GlassFish. The steps will vary depending on the application server you are using.
JPA Configuration
Then we reference the database connection we created above in the persistence.xml
file for our JPA entities as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="CustomerService" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>CustomerService</jta-data-source>
<class>org.example.Customer</class>
<class>org.example.Address</class>
<class>org.example.PhoneNumber</class>
<properties>
<property name="eclipselink.target-database" value="Oracle" />
<property name="eclipselink.logging.level" value="FINEST" />
<property name="eclipselink.logging.level.ejb_or_metadata" value="WARNING" />
<property name="eclipselink.logging.timestamp" value="false"/>
<property name="eclipselink.logging.thread" value="false"/>
<property name="eclipselink.logging.session" value="false"/>
<property name="eclipselink.logging.exceptions" value="false"/>
<property name="eclipselink.target-server" value="SunAS9"/>
</properties>
</persistence-unit>
</persistence>
Have a look at this link, there is a video tutorial that explains one way how it can be done.
So the video is explaining how a web service retrieves some value to tell the client that the given credentials match against some data in a database.
This is how the method that handle the client request looks like:
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/login")
public Response login(@FormParam("email") String email, @FormParam("password") String password) {
Response.ResponseBuilder responseBuilder = null;
boolean result = entityFacade.doLogin(email, password);
if (result) {
responseBuilder = Response.ok("Success");//Login good!
}
else {
responseBuilder = Response.ok("Wrong credentials!");//Login bad!
}
return responseBuilder.build();
}
This Web service transfers the credentials to the business layer where an EJB will perform a select operation in the database:
@Stateless
public class EntityFacade implements EntityFacadeLocal {
@Resource
private UserTransaction ut;
private CredentialJpaController controller;
@PostConstruct
public void init() {
controller = new CredentialJpaController(ut, Persistence.createEntityManagerFactory("ROLEProject-ejbPU"));
}
public boolean doLogin(String email, String password){
return controller.loginWithParameters(email,password);
}
}
The EJB relies in a service class that will do the task of interact with the database
public class CredentialJpaController implements Serializable {
public CredentialJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public boolean loginWithParameters(String email, String password) {
boolean result = false;
EntityManager em = getEntityManager();
Long l = (Long) em.createNamedQuery("loginquery").setParameter("emailParam", email).setParameter("passwordParam", password).getSingleResult();
if (l == 1) {
result = true;
}
return result;
}
}
Finally to be able to interact with the DB, the data must be represented as a JPA entity. Also to be able to marshal the selected row back to the client as whatever MediaType is desired, the entity must contain some JaxB annotations:
@XmlRootElement
@Entity
@Table(name = "CREDENTIALS")
@NamedQuery(name="loginquery", query="SELECT COUNT(c) FROM Credential c WHERE c.email = :emailParam AND c.password = :passwordParam")
public class Credential implements Serializable {
@Id
private String email;
@Column(nullable = false)
private String password;
@XmlElement
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@XmlElement
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Here is some sample client code so you can see one of the ways how the web-service can be called:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
</head>
<body>
<div>TODO write content</div>
<form action="http://localhost:8080/ROLEProject-war/role/login" method="POST">
Email <input name="email"/>
Password <input type="password" name="password"/>
<input type="submit"/>
</form>
</body>
</html>
I hope this helps to give you an idea.
To do insert data the process is almost the same, just use the method persist() instead of find() from the entity manager.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With