0

I'm trying to create a Java application that will run on a hypothetical client machine, where members of staff can both view or add customer details from a local MySQL database. I'm trying to use JPA to do so, with query methods being in this form:

public class DataManagerImpl implements DataManager{
@PersistenceContext 
private EntityManager em;  
public List<Customer> AllCustomers(){
    TypedQuery<Customer> query = em.createNamedQuery("Customer.findAll", Customer.class);
    return query.getResultList();
} }

I've got a DBConnection class:

public class MyDBConn implements DBConnectivity {
@Resource(mappedName="jdbc:mysql://localhost:3306/solsoft_DB") DataSource dataSource;
    Connection myConn = null;

    public Connection open_Connection() {

    String user = "root"; 
    String pass = "password"; 

    try {
        Class.forName("com.mysql.jdbc.Driver");
        myConn = dataSource.getConnection(user, pass);
        return myConn;
    } catch (Exception exc) {
        exc.printStackTrace();
        return myConn;
    } 
 }}

And then in my main method:

DataManagerImpl dm = new DataManagerImpl();
    List<Customer> allCustomers = dm.AllCustomers();

    for(Customer c : allCustomers){
       String cust = "" + c.getForename() + " " + c.getSurname(); 
       System.out.println(cust);
    }

I'd really appreciate if anyone could point my in the right direction on how to actually go about getting some information from the DB using JPA in this way.

  • Please explain what is wrong with your code, is there an error or something? – Scary Wombat Mar 28 '18 at 04:21
  • I'm getting a nullPointer exception on trying to run: DataManagerImpl dm = new DataManagerImpl(); for(Customer c : dm.AllCustomers()){ String cust = "" + c.getForename() + " " + c.getSurname(); System.out.println(cust); } – Daniel M Mar 28 '18 at 12:42

1 Answers1

-1

The application will be running in a server? What server? Or is an standalone application?

My guess (the best I can do as there are many things not pointed in the question) is that you are trying to supply the connection that PersistenceContext should use.

If its like this and you are using JPA you should register an EntityManagerFactory with the required properties for connection and get your PersistenceContext from that factory. (See an example here)

Another way to go would be to edit your persistence.xml file defining this properties inside the file like this and just let your context handle the logic for database connection.

Jhilton
  • 420
  • 3
  • 7