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) {
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


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.
public class MyResource {
private InfoDao infoDao;
public MyResource(InfoDao infoDao) {
this.infoDao = infoDao;
public String getName() {
return "Harsh";
public String postName(String name) {
System.out.println("Name given by : "+name);
return "Ok";
public List<Info> findAllEmp() {
return infoDao.findAll();
public String saveEmp(Info info) {
return infoDao.create(info);

view raw


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




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


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 )

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

Blog at WordPress.com.

Up ↑

%d bloggers like this: