Add getShop to DAO, preparing to refactor shop loading

This commit is contained in:
P0nk
2023-03-29 21:14:19 +02:00
parent c71ca7f4d5
commit 2139147dcd
4 changed files with 55 additions and 8 deletions

View File

@@ -7,21 +7,32 @@ import database.maker.MakerReagentRowMapper;
import database.maker.MakerRecipeRowMapper;
import database.note.NoteRowMapper;
import database.shop.ShopItemRowMapper;
import database.shop.ShopRowMapper;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.mapper.RowMapper;
import javax.sql.DataSource;
import java.util.List;
public final class JdbiConfig {
private JdbiConfig() {}
public static Jdbi createConfigured(DataSource dataSource) {
return Jdbi.create(dataSource)
.registerRowMapper(new NoteRowMapper())
.registerRowMapper(new MakerReagentRowMapper())
.registerRowMapper(new MakerRecipeRowMapper())
.registerRowMapper(new MakerIngredientRowMapper())
.registerRowMapper(new MonsterDropRowMapper())
.registerRowMapper(new GlobalMonsterDropRowMapper())
.registerRowMapper(new ShopItemRowMapper());
final Jdbi jdbi = Jdbi.create(dataSource);
rowMappers().forEach(jdbi::registerRowMapper);
return jdbi;
}
private static List<RowMapper<?>> rowMappers() {
return List.of(
new NoteRowMapper(),
new MakerReagentRowMapper(),
new MakerRecipeRowMapper(),
new MakerIngredientRowMapper(),
new MonsterDropRowMapper(),
new GlobalMonsterDropRowMapper(),
new ShopRowMapper(),
new ShopItemRowMapper()
);
}
}

View File

@@ -0,0 +1,4 @@
package database.shop;
public record Shop(int id, int npcId) {
}

View File

@@ -6,6 +6,7 @@ import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.JdbiException;
import java.util.List;
import java.util.Optional;
public class ShopDao {
private final PgDatabaseConnection connection;
@@ -14,6 +15,20 @@ public class ShopDao {
this.connection = connection;
}
public Optional<Shop> getShop(int shopId) {
try (Handle handle = connection.getHandle()) {
return handle.createQuery("""
SELECT *
FROM shop
WHERE id = ?;""")
.bind(0, shopId)
.mapTo(Shop.class)
.findOne();
} catch (JdbiException e) {
throw new DaoException("Failed to get shop with id %d".formatted(shopId), e);
}
}
public List<ShopItem> getShopItems(int shopId) {
try (Handle handle = connection.getHandle()) {
return handle.createQuery("""

View File

@@ -0,0 +1,17 @@
package database.shop;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ShopRowMapper implements RowMapper<Shop> {
@Override
public Shop map(ResultSet rs, StatementContext ctx) throws SQLException {
final int shopId = rs.getInt("id");
final int npcId = rs.getInt("npc_id");
return new Shop(shopId, npcId);
}
}