Wednesday 14 September 2011

Configure MySQL datasource in Glassfish 3.1

Part 1 of this article shows how to configure a MySQL datasource in Glassfish 3.1.

Part 2 of this article shows how to test the connection with a standalone Java client program.


Part 1

Assume Glassfish's installation folder is D:\glassfish3\glassfish

Copy mysql-connector-java-xxx-bin.jar to D:\glassfish3\glassfish\lib or D:\glassfish3\glassfish\domains\domain1\lib\ext

Start MySQL server, assume the following settings

URL: jdbc:mysql://localhost:3306/mydb
username: root
password: root

Start Glassfish, go to Admin Console, http://localhost:4848

Resources -> JDBC -> JDBC Connection Pools


Click on 'New'


Click on 'Next'


Scroll down, specify the following properties, and leave others as they are.


User  root
Password  root
Url  jdbc:mysql://localhost:3306/mydb
URL  jdbc:mysql://localhost:3306/mydb

Click on 'Save'

Go to Resources -> JDBC -> JDBC Resources


Click on 'New'


Click on 'OK'


Click on 'Ping' to test.

Part 2

Create a java project in Eclipse (must use JDK 1.6)

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) 
      throws Exception{
        Context ctx = new InitialContext();
        DataSource ds 
          = (DataSource) ctx.lookup("jdbc/mysql");
        Connection con = ds.getConnection();
        con.close();
    }
}

Add the following two jar files to class path


Note: You can't directly copy gf-client.jar into project's folder. You have to point to the jar file under glassfish\lib

After starting MySQL server and Glassfish Server, we can test the program.

No comments:

Post a Comment