Dropwizard中集成dropwizard-jdbi3

一、Maven配置

<!-- 依赖注入 -->
<dependency>
    <groupId>ru.vyarus</groupId>
    <artifactId>dropwizard-guicey</artifactId>
    <version>7.0.0</version>
</dependency>
<!-- 集成jdbi3 -->
<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-jdbi3</artifactId>
</dependency>
<!-- jdbi3引入依赖注入 -->
<dependency>
    <groupId>ru.vyarus.guicey</groupId>
    <artifactId>guicey-jdbi3</artifactId>
    <version>7.0.0</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>

二、项目配置

(1)yml文件配置

database:
  # the name of your JDBC driver
  driverClass: org.gjt.mm.mysql.Driver

  # the username
  user: root

  # the password
  password: root

  # the JDBC URL
  url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true

  # any properties specific to your JDBC driver:
  properties:
    charSet: UTF-8

  # the maximum amount of time to wait on an empty pool before throwing an exception
  maxWaitForConnection: 1s

  # the SQL query to run when validating a connection's liveness
  validationQuery: "/* MyService Health Check */ SELECT 1"

  # the timeout before a connection validation queries fail
  validationQueryTimeout: 3s

  # the minimum number of connections to keep open
  minSize: 8

  # the maximum number of connections to keep open
  maxSize: 32

  # whether or not idle connections should be validated
  checkConnectionWhileIdle: false

  # the amount of time to sleep between runs of the idle connection validation, abandoned cleaner and idle pool resizing
  evictionInterval: 10s

  # the minimum amount of time an connection must sit idle in the pool before it is eligible for eviction
  minIdleTime: 1 minute

(2)yml文件读取配置

public class HorseConfiguration extends Configuration {

    @Valid
    @NotNull
    private DataSourceFactory database = new DataSourceFactory();

    @JsonProperty("database")
    public void setDataSourceFactory(DataSourceFactory factory) {
        this.database = factory;
    }

    @JsonProperty("database")
    public DataSourceFactory getDataSourceFactory() {
        return database;
    }
}

(3)注册Guice包

public class HorseApplication extends Application<HorseConfiguration> {

    public static void main(final String[] args) throws Exception {
        new HorseApplication().run(args);
    }

    @Override
    public String getName() {
        return "Horse";
    }

    @Override
    public void initialize(final Bootstrap<HorseConfiguration> bootstrap) {
        GuiceBundle guiceBundle = GuiceBundle.builder()
                .bundles(JdbiBundle.<HorseConfiguration>forDatabase((conf, env) -> conf.getDataSourceFactory()))
                .enableAutoConfig()
                .build();
        bootstrap.addBundle(guiceBundle);
    }

    @Override
    public void run(final HorseConfiguration configuration,
                    final Environment environment) {
    }
}

其中,

JdbiBundle.<HorseConfiguration>forDatabase((conf, env) -> conf.getDataSourceFactory() 

用于创建jdbi包

三、GoodsDAO持久化类、对象映射类开发

(1)持久化类

@JdbiRepository
@InTransaction
public interface GoodsDAO {

    @SqlQuery("select id, name from t_goods")
    List<Goods> findAll();

    @SqlQuery("select id, name from t_goods where id = :id")
    Goods findById(@Bind("id") String id);

    @SqlUpdate("insert into t_goods(id, name) values(:goods.id, :goods.name)")
    void insert(@BindBean("goods") Goods goods);

    @SqlUpdate("update t_goods set name = :goods.name where id = :goods.id")
    void update(@BindBean("goods") Goods goods);

    @SqlUpdate("delete from t_goods where id = :id")
    void delete(@Bind("id") String id);
}

@JdbiRepository:注册jdbi持久化对象

@InTransaction:开启事务

@Bind:参数绑定

@BindBean:对象参数绑定

(2)对象映射类

public class GoodsMapper implements RowMapper<Goods> {
    @Override
    public Goods map(ResultSet rs, StatementContext ctx) throws SQLException {
        String id = rs.getString("id");
        String name = rs.getString("name");
        return new Goods(id, name);
    }
}

此对象映射类,用于将查询出的结果映射成Goods对象 

四、GoodsResource资源类改造

/**
 * 商品资源类
 */
@Path("/goods")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class GoodsResource {

    private final GoodsDAO goodsDao;

    @Inject
    public GoodsResource(GoodsDAO goodsDao) {
        this.goodsDao = goodsDao;
    }

    @GET
    public Response find() {
        return Response.ok().entity(new ResponseResult(0, "成功", this.goodsDao.findAll())).build();
    }

    @POST
    public Response add(Goods goods) {
        // 判断商品是否为空
        if(Objects.isNull(goods)) {
            return Response.ok().entity(new ResponseResult(502, "商品不能为空")).build();
        }

        // 判断商品编号是否为空
        if(Objects.isNull(goods.getId())
            || goods.getId().isBlank()) {
            return Response.ok().entity(new ResponseResult(502, "商品编号不能为空")).build();
        }

        // 判断商品名称是否为空
        if(Objects.isNull(goods.getName())
            || goods.getName().isBlank()) {
            return Response.ok().entity(new ResponseResult(502, "商品名称不能为空")).build();
        }

        // 根据商品编号查询商品
        Goods hadGoods = this.goodsDao.findById(goods.getId());
        if(Objects.nonNull(hadGoods)) {
            return Response.ok().entity(new ResponseResult(502, "商品编号已经存在")).build();
        }

        // 添加商品
        this.goodsDao.insert(goods);
        return Response.ok().entity(new ResponseResult(0, "成功", goods)).build();
    }

    @PUT
    @Path("/{id}")
    public Response update(@PathParam("id") String id, Goods goods) {
        // 查询商品
        Goods hadGoods = this.goodsDao.findById(id);

        // 判断商品是否存在
        if(Objects.isNull(hadGoods)) {
            return Response.ok().entity(new ResponseResult(404, "商品不存在")).build();
        }

        // 修改商品名称
        goods.setId(id);
        this.goodsDao.update(goods);
        return Response.ok().entity(new ResponseResult(0, "成功", goods)).build();
    }

    @DELETE
    @Path("/{id}")
    public Response delete(@PathParam("id") String id) {
        // 查询商品
        Goods hadGoods = this.goodsDao.findById(id);

        // 判断商品是否存在
        if(Objects.isNull(hadGoods)) {
            return Response.ok().entity(new ResponseResult(404, "商品不存在")).build();
        }

        // 删除商品
        this.goodsDao.delete(id);
        return Response.ok().entity(new ResponseResult(0, "成功", hadGoods)).build();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值