Dropwizard : Write Data Into Database Using Hibernate

Please follow the first two part of the tutorial before starting this:

Introduction To Dropwizard

Read Data From Database Using Dropwizard

Modify InfoDao To Persist Data

Add a method to persist data

import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import java.util.List;
/**
* Created by harshvardhan on 10/07/18.
*/
public class InfoDao extends AbstractDAO<Info> {
public InfoDao(SessionFactory factory) {
super(factory);
}
public Info findById(String id) {
return get(id);
}
public String create(Info info) {
return persist(info).getEmpid();
}
public List<Info> findAll() {
return list(namedQuery("com.wordpress.nullpointerexception1.info.findAll"));
}
}

view raw
InfoDao.java
hosted with ❤ by GitHub

Add POST API to store the info

import com.codahale.metrics.annotation.Timed;
import io.dropwizard.hibernate.UnitOfWork;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* Created by harshvardhan on 12/07/18.
*/
@Path("/resource")
@Produces(MediaType.APPLICATION_JSON)
public class MyResource {
private InfoDao infoDao;
public MyResource(InfoDao infoDao) {
this.infoDao = infoDao;
}
@GET
@Timed
@Path("/getName")
public String getName() {
return "Harsh";
}
@POST
@Timed
@Path("/postName")
public String postName(String name) {
System.out.println("Name given by : "+name);
return "Ok";
}
@GET
@Timed
@UnitOfWork
@Path("/findAllEmp")
public List<Info> findAllEmp() {
return infoDao.findAll();
}
@POST
@Timed
@UnitOfWork
@Path("/saveEmp")
public String saveEmp(Info info) {
return infoDao.create(info);
}
}

view raw
MyResource.java
hosted with ❤ by GitHub

Test Your API

Run your project.

Test using postman or any other rest client.

Screen Shot 2018-07-17 at 2.19.48 AM

Database screenshot to show “Yash” stored.

Screen Shot 2018-07-17 at 2.22.11 AM.png


Reference:

https://www.dropwizard.io/1.0.0/docs/manual/hibernate.html

https://dzone.com/articles/dropwizard-hibernate-mysql

2 thoughts on “Dropwizard : Write Data Into Database Using Hibernate

Add yours

  1. if you face any issue with the database connection, please update the dependency version of mysql-connector-java to 8.0.11

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: