Created by 5zig. All rights reserved © 2015
| 18 | * All rights reserved © 2015 |
| 19 | */ |
| 20 | public class Database { |
| 21 | |
| 22 | private static final Logger LOGGER = LogManager.getLogger("5zig"); |
| 23 | |
| 24 | protected final IDatabaseConfiguration databaseConfiguration; |
| 25 | protected Connection connection; |
| 26 | protected boolean connected = false; |
| 27 | |
| 28 | final ExecutorService EXECUTOR; |
| 29 | |
| 30 | public Database(IDatabaseConfiguration databaseConfiguration) throws NoConnectionException { |
| 31 | this.databaseConfiguration = databaseConfiguration; |
| 32 | this.connection = openConnection(); |
| 33 | EXECUTOR = Executors.newFixedThreadPool(databaseConfiguration == null ? 1 : databaseConfiguration.getThreadCount(), |
| 34 | new ThreadFactoryBuilder().setNameFormat("Database Queue #%d").build()); |
| 35 | } |
| 36 | |
| 37 | public IDatabaseConfiguration getDatabaseConfiguration() { |
| 38 | return databaseConfiguration; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Connects to a Database. |
| 43 | */ |
| 44 | protected synchronized Connection openConnection() throws NoConnectionException { |
| 45 | try { |
| 46 | try { |
| 47 | if (connection != null) { |
| 48 | closeConnection(); |
| 49 | } |
| 50 | } catch (Exception ignored) { |
| 51 | } |
| 52 | getLogger().debug("Connecting to " + databaseConfiguration); |
| 53 | Class.forName(databaseConfiguration.getDriver()); |
| 54 | Connection conn = databaseConfiguration.getConnection(); |
| 55 | getLogger().debug("Connected to Database!"); |
| 56 | connected = true; |
| 57 | return this.connection = conn; |
| 58 | } catch (Exception e) { |
| 59 | throw new NoConnectionException("Could not connect to " + databaseConfiguration, e); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | public <T> SQLQuery<T> get(Class<T> entity) { |
| 64 | return new SQLQuery<T>(this, entity); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Executes a MySQL Update with a PreparedStatement and given fields. |
| 69 | * |
| 70 | * @param query The Prepared Statement Query. Use {@code ?} for fields. |
| 71 | * @param fields The Fields that should be inserted into the Statement. |
| 72 | */ |
| 73 | public void update(final String query, final Object... fields) { |
| 74 | update(null, query, fields); |
| 75 | } |
| 76 | |
| 77 | /** |