ru.vyarus
dropwizard-guicey
7.0.0
io.dropwizard
dropwizard-jdbi3
ru.vyarus.guicey
guicey-jdbi3
7.0.0
mysql
mysql-connector-java
5.1.49
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
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;
}
}
public class HorseApplication extends Application {
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 bootstrap) {
GuiceBundle guiceBundle = GuiceBundle.builder()
.bundles(JdbiBundle.forDatabase((conf, env) -> conf.getDataSourceFactory()))
.enableAutoConfig()
.build();
bootstrap.addBundle(guiceBundle);
}
@Override
public void run(final HorseConfiguration configuration,
final Environment environment) {
}
}
其中,
JdbiBundle.
forDatabase((conf, env) -> conf.getDataSourceFactory()
用于创建jdbi包
@JdbiRepository
@InTransaction
public interface GoodsDAO {
@SqlQuery("select id, name from t_goods")
List 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:对象参数绑定
public class GoodsMapper implements RowMapper {
@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对象
/**
* 商品资源类
*/
@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();
}
}