2

I have connections to my database running. I can execute the following with no issue:

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/people", "root", "r00t");

PreparedStatement statement = (PreparedStatement) conn.prepareStatement("select * from users");
ResultSet result = statement.executeQuery();

However, after setting up JPA and a persistant class, I always get a "No Database Selected" error. It doesn't seem like I need to adjust my database config (MySQL connected to Glassfish 3.1) otherwise the above code wouldn't work.

The call being made:

SELECT USERNAME, FIRSTNAME, LASTNAME, PASSWORD, PERMISSION FROM users

I have tried this call directly in MySQL Workbench and it doesnt work.

This one does work:

SELECT USERNAME, FIRSTNAME, LASTNAME, PASSWORD, PERMISSION FROM people.users

I have been playing round and cant seem to add the database name anywhere ("people"). Here is what I have so far:

Using EclipseLink 2.0.x

JPA implimentation: Disable Library Configuration

Connection: Local MySQL (I have my database successfully connected)

Schema: people

From my servlet:

package com.lowe.samples;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.PreparedStatement;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @PersistenceContext
    private EntityManager em;

    public TestServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter(); 
        out.println("<h1>DataBase Test:<h1>");

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/people", "root", "r00t");

            PreparedStatement statement = (PreparedStatement) conn.prepareStatement("select * from users");
            ResultSet result = statement.executeQuery();

            // prep the table
            out.print("<table border=\"5\">");
            out.print("<tr>");
            out.print("<td>UserName</td>");
            out.print("<td>FirstName</td>");
            out.print("<td>LastName</td>");
            out.print("<td>Password</td>");
            out.print("<td>Permission</td>");
            out.print("</tr>");

            while(result.next()) {
                out.print("<tr>");
                out.print("<td>" + result.getString(1) + "</td>");
                out.print("<td>" + result.getString(2) + "</td>");
                out.print("<td>" + result.getString(3) + "</td>");
                out.print("<td>" + result.getString(4) + "</td>");
                out.print("<td>" + result.getString(5) + "</td>");
                out.print("</tr>");
            }

            out.print("</table>");

            User u = (User)this.em.createNamedQuery("User.findAll").getResultList();
            out.print("User Name: " + u.getFirstName());

        } catch (ClassNotFoundException e) {
            out.print("<h4>" + e.getMessage() + "</h4>");
            e.printStackTrace();
        } catch (SQLException e) {
            out.print("<h4>" + e.getMessage() + "</h4>");
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

}

My persistance class:

package com.lowe.samples;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the users database table.
 */
@Entity
@Table(name="users")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private String userName;

    private String firstName;

    private String permission;

    private String lastName;

    private String password;

    public User() {
    }

    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getPermission() {
        return this.permission;
    }

    public void setPermission(String permission) {
        this.permission = permission;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

the 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="MyFriends">
        <jta-data-source>jdbc/MySQLDataSource</jta-data-source>
        <class>com.lowe.samples.User</class>
    </persistence-unit>
</persistence>
Dror Bereznitsky
  • 20,048
  • 3
  • 48
  • 57
maffo
  • 1,393
  • 4
  • 18
  • 35
  • why are you using jdbc? – nachokk Sep 15 '13 at 19:28
  • @nachokk I don't follow. As opposed to? – maffo Sep 15 '13 at 19:45
  • if you are using jpa you delegate that work to the provider that you are using. In your case toplink. [jpa or jdbc](http://stackoverflow.com/questions/11881548/jpa-or-jdbc-how-are-they-different) – nachokk Sep 15 '13 at 19:52
  • @nachokk I use the JDBC code as a way of proving my db connection is up. I dont intend on keeping it when I have JPA correctly integrated. – maffo Sep 15 '13 at 20:09

4 Answers4

4

The first piece of code is using JDBC to load the database driver, connect and execute a query. The fact that it works shows that you have the MySQL driver in your classpath and that you can connect to your database using the URL and credentials provided. It has nothing to do with JPA.

Your persistent.xml has persistence unit named "MyFriends" with a JTA-aware data source configured:

<jta-data-source>jdbc/MySQLDataSource</jta-data-source>

This data source is bound to JNDI.

According to the error you are getting the connection pool is misconfigured, probably lacking the database name in the URL.

t7bdh3hdhb
  • 438
  • 3
  • 15
Dror Bereznitsky
  • 20,048
  • 3
  • 48
  • 57
  • 2
    I found the issue. After reading that [awesome] link I found that my URL was missing the DB name. Url: jdbc:mysql://:3306/ rather than Url: jdbc:mysql://:3306/test. – maffo Sep 15 '13 at 20:26
  • 1
    FYI my Glassfish 3.1 admin console has two different properties "Url" and "URL". Can't imagine why this makes sense but I had this problem because I had only changed the first one to include the database name, and had to change both of them. – Uncle Long Hair Dec 22 '14 at 20:30
2

If you are using jta data source or using hibernate properties while specifying db url mention db name after db ip-address like jdbc:mysql://:3306/. If somehow that is not possible for you in your entities you can specify the db in which your table is @Table(name="abcd",catalog="dbname/schema name") You can also do this if you are using multiple databases from one server.

rakesh
  • 4,368
  • 1
  • 19
  • 13
0

if your using hbm.xml try the following

<class name="com.javapapers.data.user"  table ="user"  catalog
="<DBNAME.Schema>">
0

Another possbile solution to this problem is to make sure you specify the database in the URL of the jdbc-connection-pool

I ran into this problem and had this URL:

<property name="URL" value="jdbc:mysql://my_host:3306"></property>

When I added the database to the end, problem solved:

<property name="URL" value="jdbc:mysql://my_host:3306/my_db_name"></property>

Hope this helps someone in the future.

Esteban Rincon
  • 2,040
  • 3
  • 27
  • 44