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.
Can I also make it to auto create the database (if it doesn't exist)?
My objectif is :
I mean it creates inside the database the tables and fields, but not the database, and if the database hasn't been created before (by hand) - everything fails. So before running the project (which will auto generate the tables and fields if needed) I first must create (by hand) a database.
I use : Eclipse (Java, Hibernate, Flex/Air), MySQL
Thanks for all information
Spring Data JPA focuses on using JPA to store data in a relational database. Its most compelling feature is the ability to create repository implementations automatically, at runtime, from a repository interface. CustomerRepository extends the CrudRepository interface.
Implementation: We are going to build a simple Java application by creating a maven project and we are going to save some data inside the MySQL Database with the help of both Hibernate and JPA concepts. Step 2: When you have successfully created a maven project you have to add some dependencies in your pom. xml file.
The database has to be created manually (Fortunatly you didn't ask why ;-). Which is similar to the user/password combination you use to connect to your database server, which must already exist in order to connect to the DB.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With