Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.ekranos.misc.economy;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class StandardTransaction implements Transaction {
- private int id = Integer.MIN_VALUE;
- private Deposit source;
- private Deposit target;
- private double amount = Double.MIN_VALUE;
- private String description;
- private boolean executed = false;
- private boolean fetched = false;
- public StandardTransaction(int id) {
- this.id = id;
- }
- public StandardTransaction(Deposit source, Deposit target, double amount, String description) {
- this.source = source;
- this.target = target;
- this.amount = amount;
- this.description = description;
- setFetched(true);
- }
- @Override
- public long getId() {
- return id;
- }
- @Override
- public Deposit getSource() {
- fetch();
- return source;
- }
- @Override
- public Deposit getTarget() {
- fetch();
- return target;
- }
- @Override
- public double getAmount() {
- fetch();
- return amount;
- }
- @Override
- public String getDescription() {
- fetch();
- return description;
- }
- @Override
- public boolean isExecuted() {
- return executed;
- }
- public void setExecuted(boolean executed) {
- this.executed = executed;
- }
- public boolean isFetched() {
- return fetched;
- }
- public void setFetched(boolean fetched) {
- this.fetched = fetched;
- }
- public Transaction fetch() {
- if (isFetched()) return this;
- try (Connection connection = StandardEconomyService.getConnection()) {
- PreparedStatement statement = connection.prepareStatement("SELECT * FROM transactions WHERE id = ?");
- statement.setInt(1, id);
- ResultSet result = statement.executeQuery();
- if (result.next()) {
- source = new StandardDeposit(result.getInt("source"));
- target = new StandardDeposit(result.getInt("target"));
- amount = result.getDouble("amount");
- description = result.getString("description");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- setFetched(true);
- return this;
- }
- public Transaction save() {
- try (Connection connection = StandardEconomyService.getConnection()) {
- PreparedStatement statement = connection.prepareStatement("INSERT INTO transactions (source, target, amount, description) VALUES (?, ?, ?, ?)");
- statement.setInt(1, source.getId());
- statement.setInt(2, target.getId());
- statement.setDouble(3, amount);
- statement.setString(4, description);
- statement.execute();
- setExecuted(true);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return this;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement