Create database with JPA?

后端 未结 2 1162
野性不改
野性不改 2021-01-04 10:30

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.

相关标签:
2条回答
  • 2021-01-04 11:22

    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.

    0 讨论(0)
  • 2021-01-04 11:34

    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();
    }
    
    0 讨论(0)
提交回复
热议问题