DBに接続する(2/2)
さて、昨日の続き
ConfigクラスでDB接続設定読み込み
Sample001Configuration.java
public class Sample001Configuration extends Configuration { @Valid @NotNull @JsonProperty private DataSourceFactory database = new DataSourceFactory(); @JsonProperty("database") public DataSourceFactory getDataSourceFactory() { return database; } }
DAOを作成
db/SampleDAO.java
public interface SampleDao { @SqlUpdate("INSERT INTO sample(id, name) VALUES(nextval('seq'), :name)") int insert(@Bind("name") String name); @SqlQuery("SELECT name from sample WHERE id = :id") String findById(@Bind("id") int id); }
Resourceを作成
resources/SampleDaoResource.java
@Path("/dao") @Produces(MediaType.APPLICATION_JSON) public class SampleDaoResource { private final SampleDao dao; public SampleDaoResource(SampleDao dao) { this.dao = dao; } @POST public int insert(@FormParam("name")String name) { return dao.insert(name); } @GET @Path("{id}") public Map<String, String> dao(@PathParam("id")Integer id) { String name = dao.findById(id); if( name == null ) throw new NotFoundException("Not found sample id="+id); Map<String,String> result = new HashMap<>(); result.put("id", ""+id); result.put("name", name); return result; } }
Sample001Application でDBIオブジェクトを作成&Resourceを登録
public class Sample001Application extends Application<Sample001Configuration> { ; ; @Override public void run(final Sample001Configuration configuration, final Environment environment) { final DBIFactory factory = new DBIFactory(); final DBI dbi = factory.build(environment, configuration.getDataSourceFactory(), "postgresql"); final SampleDao dao = dbi.onDemand(SampleDao.class); environment.jersey().register(new SampleDaoResource(dao)); } }
ビルド&実行
- % mvn package
- % java -jar target\Sample001-1.0-SNAPSHOT.jar server conf\dev.yml
http://localhost:8080/dao にPOSTアクセス
その際、「name=hoge」というパラメータを付ける
curl コマンドだとこんなカンジかな(未検証)
curl http://localhost:8080/dao -X POST -d "name=hoge"
DBを確認すると、1レコード増えてるハズ
http://localhost:8080/dao/1 にアクセス
今登録したので、
{"name":"hogehoge","id":"1"}
と表示されれば成功