如何验证实体管理器是否可以建立与数据库的连接?

时间:2013-12-07 18:37:13

标签: hibernate java-ee persistence tomee

的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_2_0.xsd"
version="2.0">

<persistence-unit name="prod" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>webadmin.domain.WebSite</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/dummy?useUnicode=yes&amp;characterEncoding=utf8;" />
        <property name="hibernate.connection.username" value="root1" />
        <property name="hibernate.connection.password" value="root1" />

    </properties>

</persistence-unit>

服务

@Stateless
public class WebSiteService {
@PersistenceContext(unitName = "prod")
private EntityManager entityManager;

public WebSite saveWebSite(WebSite webSite) {
    System.out.println("before query");
    Query q=entityManager.createNativeQuery("insert into dum values (1, 'ws');");
    System.out.println("before execution");
    q.executeUpdate();
    System.out.println("after execution");

问题

我正在解决org.hsqldb.HsqlException: user lacks privilege or object not found: DUM问题。在尝试查找根本原因时,我使用无效的数据库名称和无效的用户/密码更新了我的persistence.xml。但是,我没有看到与此相关的例外情况。所以我相信即使使用正确的参数,我也绝不会连接到数据库。这里缺少什么?我该如何检查这种连接?

TomEE 1.6,MySQL 5。

解决方案

根据JB的评论,TomEE需要在tomee.xml中定义数据源,因此在那里添加数据源。

<tomee>
    <Resource id="prodDataSource" type="javax.sql.DataSource">
    jdbcDriver com.mysql.jdbc.Driver
    jdbcUrl jdbc:mysql://localhost:3306/yourdbname
    jtaManaged true
    password root
    userName root
    InitialSize 50 
    MaxActive 100
    MaxIdle 3   
    </Resource>
</tomee>

没有其他人可以访问我的服务器,因此我将凭据保存在tomee.xml中。这样,我的persistence.xml属性部分就缩减为:

<properties>
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
</properties>

从服务器中删除项目。双击服务器以转至服务器概述。在服务器位置下:选择Tomcat安装目录。清理服务器,项目,重启。为我工作。

RajV的一个有价值的评论:How to define MySQL data source in TomEE?

1 个答案:

答案 0 :(得分:0)

您必须为MySQL数据库配置一个DataSource:http://tomee.apache.org/configuring-datasources.html

然后你必须遵循关于Hibernate的Tomee文档:http://tomee.apache.org/tomee-and-hibernate.html。注意

的使用
<jta-data-source>movieDatabase</jta-data-source>

引用第一步中配置的数据源(movieDatabase)。