When I create (using JPA - java persistence api) a persistence unit and then persistence entities they auto create the corresponding tables and fields in the database.
My solution to this problem was to add the following right before I create my entity manager:
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost/?user=" + DB_USER);
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + DB_NAME);
You'll need to either surround that with a try/catch block or add a throws SQLException notation to the function in which it exists. So, for example, here is my initEntityManager
function:
public static void initEntityManager() throws SQLException {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost/?user=" + DB_USER);
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + DB_NAME);
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}