Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create database with JPA?

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

like image 969
Koko Avatar asked Oct 15 '10 12:10

Koko


People also ask

Is JPA repository a database?

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.

Can we use JPA with MySQL?

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.


2 Answers

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.

like image 173
stacker Avatar answered Sep 23 '22 12:09

stacker


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();
}
like image 34
Ben Hocking Avatar answered Sep 26 '22 12:09

Ben Hocking