Please follow the first two part of the tutorial before starting this:
Read Data From Database Using Dropwizard
Modify InfoDao To Persist Data
Add a method to persist data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} | |
} |
Add POST API to store the info
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Test Your API
Run your project.
Test using postman or any other rest client.
Database screenshot to show “Yash” stored.
Reference:
https://www.dropwizard.io/1.0.0/docs/manual/hibernate.html
https://dzone.com/articles/dropwizard-hibernate-mysql
If you liked this article and would like one such blog to land in your inbox every week, consider subscribing to our newsletter: https://skillcaptain.substack.com
if you face any issue with the database connection, please update the dependency version of mysql-connector-java to 8.0.11