jpa动态创建EntityManagerFactory 态设置数据库连接 EntityManager;
时间: 2023-11-28 10:49:50 浏览: 45
在使用 JPA 动态创建 `EntityManagerFactory` 并设置数据库连接时,需要先创建一个 `Map` 对象来存储数据库连接的配置信息。下面是一个示例代码:
```java
Map<String, Object> properties = new HashMap<>();
properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
properties.put("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/mydb");
properties.put("javax.persistence.jdbc.user", "root");
properties.put("javax.persistence.jdbc.password", "mypassword");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit", properties);
EntityManager em = emf.createEntityManager();
```
在上面的代码中,`properties` 对象中存储了数据库连接的配置信息,包括驱动程序类名、数据库 URL、用户名和密码。接着使用 `Persistence.createEntityManagerFactory()` 方法来创建一个 `EntityManagerFactory` 对象,并传入 `properties` 对象作为参数。最后使用 `emf.createEntityManager()` 方法来创建一个 `EntityManager` 对象,以便与数据库进行交互。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)