如何在不使用Entity类的情况下使用EclipseLink与Tables交互?

时间:2014-03-02 07:04:31

标签: java mysql sql jpa eclipselink

我的项目中没有实体类。我的要求是当我连接到DataBase时基于模式我必须从该模式中获取所有表名。

这里我有一个Schema作为“companydb”,有5个表。下面是我从特定模式中检索表总数的代码。

这可能是“查询”发生的异常。查询不是很好,所以我必须使用什么类型的查询以及如何获取表列表。

persiatance.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="reports" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>

        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/reports" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="root" />
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
    </properties>
</persistence-unit>
</persistence>    

GetTableList.java

@WebServlet("/GetTableList")
public class GetTableList extends HttpServlet {

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    EntityManager entityManager = EntityManagerUtil.getEmf()
            .createEntityManager();
    try {

        Query query = entityManager.createQuery("SELECT * FROM companydb.tables");
        List list = query.getResultList();
        System.out.println(list);
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            iterator.next();

        }
        out.print(list);
        System.out.println("Data retrived successfully");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        entityManager.close();
    }
}
}

例外是:

java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Syntax error parsing the query [SELECT * FROM companydb], line 1, column 7: unexpected token [*].
Internal Exception: NoViableAltException(93@[330:16: ( DISTINCT )?])

我怎么能过来。

1 个答案:

答案 0 :(得分:1)

使用Native查询从模式中获取表的列表

Query query = entityManager.createNativeQuery("SHOW TABLES FROM companydb");