Hibernate MySQL连接无法正常工作

时间:2013-04-29 11:19:08

标签: java hibernate jpa

我只是想尝试一个小的hibernate示例,但我在运行时不断收到此错误:

Exception in thread "main" java.lang.UnsupportedOperationException: The user must supply a JDBC connection

我看不出我犯了什么错误。这是我的persistence.xml

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
    <persistence-unit name="Example" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.hibernatetest.Employee</class>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.url" value="jdbc:mysql://localhost:3306/TestDB" />
            <property name="javax.persistence.user" value="root" />
            <property name="javax.persistence.password" value="" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hbm2ddl.auto" value="update"></property>         
        </properties>
    </persistence-unit>
</persistence>

我在这里看不到任何错误。当我使用Maven时,我将这些依赖项添加到pom

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>3.6.0.Final</version>
</dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.0.Final</version>
        </dependency>

      <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

在我看来,这应该可以胜任。

最后但并非最不重要的是,我的Java代码:

 public void storeEmp(Employee empl) {
        try {
            em.getTransaction().begin();
            em.persist(empl);
            em.getTransaction().commit();
        } catch (PersistenceException e) {
            e.printStackTrace();
        }
    }

Employee是一个遵循bean模式的简单POJO,用@Entity注释。

我真的找不到我的错误?

1 个答案:

答案 0 :(得分:1)

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/TestDB" />
            <property name="hibernate.connection.username" value="root" />
            <property name="hibernate.connection.password" value="" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hbm2ddl.auto" value="update"></property>         
        </properties>

尝试这些属性