使用JPA persistence.xml 配置时,报错:
Unable to acquire JDBC Connection
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
首先检查persistence.xml中url,driver,username,password的写法是否正确,我是直接把hibernate.cfg.xml下面的拷贝过来的,所以写错了,对比如下:
hibernate:
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
JPA:
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
注意driver_class 变为driver,username变为user,还有前缀也要变为 javax.persistence.jdbc,最后附上正确的persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<!--transaction-type:事务类型-->
<!--JTA:JAVA Transaction API-->
<!--RESOURCE_LOCAL:本地代码事务-->
<persistence-unit name="myJPAUnit" transaction-type="RESOURCE_LOCAL">
<!--JPA提供商,可以不写-->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!--JPA注解的实体类位置,可以不写-->
<class>domain.CstCustomer</class>
<class>domain.CstLinkman</class>
<!--以下只要把cfg.xml文件中的拷贝过来稍加改动即可-->
<!--1.连接数据库的信息-->
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
<!--2.hibernate可选配置-->
<!--检测实体类的映射配置和数据库的表结构是否一致,如果不一致,更新表结构-->
<property name="hbm2ddl.auto" value="update"/>
<!--数据库方言-->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<!--是否显示hibernate生成的sql语句-->
<property name="hibernate.show_sql" value="true"/>
<!--是否使用格式化输出sql语句-->
<property name="hibernate.format_sql" value="true"/>
<!--3.设置hibernate的连接池提供商-->
<property name="hibernate.connection.provider_class" value="org.hibernate.c3p0.internal.C3P0ConnectionProvider"/>
</properties>
</persistence-unit>
</persistence>