我在使用JPA Hibernate的Postgresql时遇到了麻烦。
我的代码:
for
我遇到以下错误。
@Transactional
public void createDatabase(User user) {
Query q = em.createNativeQuery("CREATE USER \"" + user.getEmail()
+ "\" WITH PASSWORD '" + user.getPasswordHash() + "' ;");
q.executeUpdate();
Query q1 = em.createNativeQuery("CREATE DATABASE " + user.getDb() + ";");
q1.executeUpdate();
Query q2 = em.createNativeQuery("GRANT ALL PRIVILEGES ON " + user.getDb()
+ " TO '" + user.getEmail() + "';");
q2.executeUpdate();
}
如果我删除了交易注释,我会收到以下错误:
Hibernate: CREATE USER "test" WITH PASSWORD 'test' ;
Hibernate: CREATE DATABASE test;
2015-05-08 15:15:49.531 WARN 1952 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 25001
2015-05-08 15:15:49.531 ERROR 1952 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : ERREUR: CREATE DATABASE cannot be created in a transaction bloc
2015-05-08 15:15:49.545 ERROR 1952 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERREUR: CREATE DATABASE cannot be created in a transaction bloc
答案 0 :(得分:2)
JPA EntityManager
不是创建新数据库或用户的对象。请参阅文档使用实体管理器的内容。如果要从java创建新数据库,可以使用简单的JDBC来完成此操作 - 这里有一些示例代码:
// without db name
public static final String HOST = "jdbc:postgresql://localhost:5432/";
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE JavaDB");
stmt.executeUpdate("CREATE USER java_user WITH PASSWORD \'java\'");
// ...
答案 1 :(得分:0)
JPA 2.1允许您在创建EntityManagerFactory时创建数据存储表等(以及可选的模式,具体取决于JPA实现和数据存储)。