Dropwizard – Tutorial to write APIs to read/write from database using hibernate

Please go through the first part of this tutorial to set up your dropwizard project. For this project, we will assume you have a working dropwizard project.

Add dependency to your pom.xml

Please add dependency of hibernate and mySQL-connector to your pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordpress.nullpointerexception1</groupId>
<artifactId>myRestProject</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<dropwizard.version>1.3.5</dropwizard.version>
</properties>
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dropwizard.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-hibernate</artifactId>
<version>${dropwizard.version}</version>
</dependency>
</dependencies>
</project>

view raw
pom.xml
hosted with ❤ by GitHub

Create Info Table in MySql

CREATE TABLE `info` (
`name` varchar(50) NOT NULL DEFAULT '',
`empid` varchar(50) NOT NULL DEFAULT '',
PRIMARY KEY (`empid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

view raw
info.sql
hosted with ❤ by GitHub

Add some content to your table. In my case, table content should look like:

Screen Shot 2018-07-12 at 6.58.47 PM.png

Add Info Model

Add Info.java in src/main/java. Your info.java should look like:

package models;
import lombok.Data;
import javax.persistence.*;
/**
* Created by harshvardhan on 10/07/18.
*/
@Entity
@Table(name = "info")
@NamedQueries({
@NamedQuery(name = "com.wordpress.nullpointerexception1.info.findAll",
query = "select e from Info e")
})
public class Info {
@Column(name = "name")
private String name;
@Id
@Column(name = "empid")
private String empid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
}

view raw
Info.java
hosted with ❤ by GitHub

Add InfoDao

Add InfoDao.java in src/main/java. Your info.java should look like:

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 List<Info> findAll() {
return list(namedQuery("com.wordpress.nullpointerexception1.info.findAll"));
}
}

view raw
InfoDao.java
hosted with ❤ by GitHub

Add Database Configuration

Update Configuration.java and dev.yml, it should look like the files below:

import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
/**
* Created by harshvardhan on 12/07/18.
*/
public class MyConfiguration extends Configuration {
private String url;
private DataSourceFactory database = new DataSourceFactory();
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
}

view raw
MyConfiguration.java
hosted with ❤ by GitHub

Add following properties to dev.yml

url: https://nullpointerexception1.wordpress.com/
database:
# the name of the JDBC driver, mysql in our case
driverClass: com.mysql.jdbc.Driver
# the username
user: root
#user: root
# the password
password: welcome
#password:
# the JDBC URL; the database is called DWGettingStarted
url: jdbc:mysql://localhost:3306/<YOUR_DB_NAME>
properties:
charSet: UTF-8

view raw
dev.yml
hosted with ❤ by GitHub

Add API to display all the Employees

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 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() {
System.out.println("All Emp : "+infoDao.findAll());
return infoDao.findAll();
}
}

view raw
MyResource.java
hosted with ❤ by GitHub

Update MyApplication.java to register hibernate

import io.dropwizard.Application;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
/**
* Created by harshvardhan on 12/07/18.
*/
public class MyApplication extends Application<MyConfiguration> {
public static void main(String[] args) throws Exception {
new MyApplication().run(args);
}
public void run(MyConfiguration myConfiguration, Environment environment) throws Exception {
System.out.println("Value from dev.yml is "+myConfiguration.getDataSourceFactory().getUser());
InfoDao infoDao = new InfoDao(hibernate.getSessionFactory());
final MyResource resource = new MyResource(infoDao);
environment.jersey().register(resource);
}
private HibernateBundle<MyConfiguration> hibernate = new HibernateBundle<MyConfiguration>(Info.class) {
@Override
public DataSourceFactory getDataSourceFactory(MyConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
@Override
public String getName() {
return "dropwizard-hibernate";
}
@Override
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
bootstrap.addBundle(hibernate);
}
}

view raw
MyApplication.java
hosted with ❤ by GitHub


Dropwizard Hibernate

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: