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
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
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:
if you face any issue with the database connection, please update the dependency version of mysql-connector-java to 8.0.11
LikeLike