WildFlyDataSource无法强制转换为javax.persistence.EntityManagerFactory

时间:2018-04-23 04:44:41

标签: hibernate jdbc orm

我正在尝试从表中选择名为Product的POJO。

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="products")
public class Product implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@Column(name="id", nullable=false)
private int id;

@Column(name="description", nullable=false)
private String description;

@Column(name="image", nullable=false)
private String image;

@Column(name="quantity", nullable=false)
private int quantity;

persistence.xml看起来像

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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">
<persistence-unit name="Product" transaction-type="RESOURCE_LOCAL">
    <!-- Persistence provider -->
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <non-jta-data-source>java:/MySqlDS</non-jta-data-source>
    <!-- Entity classes -->
    <class>com.shoppingwebsite.objects.Product</class>
    <properties>
       <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
       <property name="jboss.entity.manager.factory.jndi.name" value="java:/MySqlDS"/>
    </properties>
</persistence-unit>

要选择的代码是

EntityTransaction transaction = null;
    EntityManager em = null;
    try {
        InitialContext initialContext = new InitialContext();
        EntityManagerFactory emf = (EntityManagerFactory) initialContext.lookup("java:/MySqlDS");
        em = emf.createEntityManager();

然而

EntityManagerFactory emf = (EntityManagerFactory) initialContext.lookup("java:/MySqlDS"); 

给我例外

 java.lang.ClassCastException: org.jboss.as.connector.subsystems.datasources.WildFlyDataSource cannot be cast to javax.persistence.EntityManagerFactory

我知道我在这里做错了,但有人可以指出来吗? 我真的需要直接在Product中选择数据。另一种方法是使用DataSource并获取一个Connection并运行一个简单的查询,但我不想走那条路。

0 个答案:

没有答案