Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Have you ever created RESTful web services? Have to try that using any Java framework?
This article is focused on one of the frameworks of Java, which is known as Dropwizard. We will also study the Hibernate module of Dropwizard. Let's see all these things in more detail.
About Dropwizard
Dropwizard is an open-source Java framework. It is used to create high-performance RESTful web services quickly. It contains a few well-known libraries to make the lightweight package. It primarily uses the Jetty, Jackson, Jersey, JUnit, and Guava libraries. It also uses its own Metrics library.
Dropwizard Hibernate Module
In dropwizard, the dropwizard-hibernate module helps you with managed access to Hibernate. It is a very robust and industry standard Object Relation Mapper or ORM.
After that, let's talk about its configuration.
Configuration of Hibernate Module
If you want to create a managed and instrumented SessionFactory instance, you need to have a DataSourceFactory instance in your configuration class. Take a look at this example:
public class TestConfiguration extends Configuration {
@Valid
@NotNull
private DataSourceFactory database = new DataSourceFactory();
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
@JsonProperty("database")
public void setDataSourceFactory(DataSourceFactory dataSourceFactory) {
this.database = dataSourceFactory;
}
}
You can also try this code with Online Java Compiler
Now, add an instance of HibernateBundle into your application class. Also, specify the entity classes as well as the getting of DataSourceFactory from the configuration subclass. Let's look at this example:
private final HibernateBundle<TestConfiguration> hibernate = new HibernateBundle<TestConfiguration>(Person.class) {
@Override
public DataSourceFactory getDataSourceFactory(TestConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
@Override
public void initialize(Bootstrap<TestConfiguration> bootstrap) {
bootstrap.addBundle(hibernate);
}
@Override
public void run(TestConfiguration config, Environment environment) {
final PersonDAO testdao = new PersonDAO(hibernate.getSessionFactory());
environment.jersey().register(new UserResource(testdao));
}
You can also try this code with Online Java Compiler
After these above steps, you will be able to create a new pool of managed connections to your database. You can also create a health check. It will help you with the connectivity with the database. You will also be able to create a new instance of SessionFactory and use it in your DAO classes.
After that, your configuration file of the application will look like this:
database:
# This is the name of your JDBC driver.
driverClass: org.postgresql.Driver
# This is the name of the user.
user: cn-user
# This is the password.
password: COdINGninjas
# This is the URL of the JDBC.
url: jdbc:postgresql://db.example.com/db-prod
# These are the properties specific to your JDBC driver.
properties:
charSet: UTF-8
hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect
# This is the maximum amount of time to wait on an empty pool before throwing any exception.
maxWaitForConnection: 1s
# This is the SQL query to run when validating a connection's liveness.
validationQuery: "/* MyApplication Health Check */ SELECT 1"
# This is the minimum number of connections to keep open.
minSize: 8
# This is the maximum number of connections to keep open
maxSize: 32
# To check whether or not idle connections should be validated.
checkConnectionWhileIdle: false
You can also try this code with Online Java Compiler
After a briefing about the hibernate module in dropwizard, let’s now move on to its usage in your application.`
Data Access Objects
Dropwizard also comes with a template known as AbstractDAO. It is a minimal template used for DAO classes that are entity specific. It also contains some type-safe wrappers. These wrappers help to perform common operations of SessionFactory.
public class PersonDAO extends AbstractDAO<Person> {
public PersonDAO(SessionFactory factory) {
super(factory);
}
public Person findById(Long id) {
return get(id);
}
public long create(Person person) {
return persist(person).getId();
}
public List<Person> findAll() {
return list(namedTypedQuery("com.example.helloworld.core.Person.findAll"));
}
}
You can also try this code with Online Java Compiler
When scoping transactional boundaries, Dropwizard uses a declarative method. The @UnitOfWork annotation is provided because some resource methods don't actually need database access.
@GET
@Path("/{id}")
@Timed
@UnitOfWork
public Person findPerson(@PathParam("id") LongParam id) {
return dao.findById(id.get());
}
You can also try this code with Online Java Compiler
As a result, the session will automatically open, a transaction will start, and findById will be called. Then the transaction will be committed, and the session will then terminate. The transaction is reversed if an exception is thrown.
In the application, you can repeat the @UnitOfWork annotation if you use several Hibernate bundles:
The last annotation with the same value() is utilized if several @UnitOfWork annotations are present.
Transactional Resource Methods Outside the Jersey Resources
Only resources handled by Jersey currently work out of the box when creating transactions with the @UnitOfWork annotation. You should instantiate your class with UnitOfWorkAwareProxyFactory if you intend to use it in places other than Jersey resources, such as authenticators.
SessionDao dao = new
SessionDao(hibernateBundle.getSessionFactory());
ExampleAuthenticator exampleAuthenticator = new UnitOfWorkAwareProxyFactory(hibernateBundle)
.create(ExampleAuthenticator.class, SessionDao.class, dao);
You can also try this code with Online Java Compiler
This will create a proxy of the class. This proxy will help us to open a Hibernate session along with a transaction. This transaction will be around methods with an annotation @UnitOfWork.
Perpended Comments in Dropwizard
Dropwizard configures the hibernate module automatically. It is used to prepend a comment which is describing the context of all the queries. Let's check out this example:
/* Load the com.test.helloworld.core.Person */
select
person0_.id as id0_0_,
person0_.fullName as fullName0_0_,
person0_.jobTitle as jobTitle0_0_
from people person0_
where person0_.id=?
You can also try this code with Online Java Compiler
This will help you to quickly find the origin of any query that is either slow or misbehaving.
Frequently Asked Questions
Does Dropwizard use Log4j?
Dropwizard makes use of Logback for its logging backend. It also provides an slf4j implementation. It even routes all Log4j, Java.util.logging, and Apache Commons Logging usage through Logback.
What are Dropwizard bundles?
A Dropwizard Bundle is a reusable collection of functionality. The Dropwizard project itself sometimes provides these functionalities. The purpose of these functionalities is to define blocks of an application's behavior.
Is Dropwizard a framework?
Yes, Dropwizard is an open-source Java framework. The purpose is to develop ops-friendly, high-performance RESTful backends.
Who developed Dropwizard?
Yammer developed Dropwizard to power their JVM-based backend.
What do you mean by managed in Dropwizard?
Dropwizard environment includes all the resources, servlets, filters, health checks, health, jersey providers, managed objects, tasks, and jersey properties.
Conclusion
In this article, we have studied one of the Java frameworks, which is known as Dropwizard, in detail.
We hope that this article has provided you with the help to enhance your knowledge regarding Dropwizard and if you would like to learn more, check out our articles on Dropwizard JDBI3, and Dropwizard Client.