This article will show how to create connection pool and JDBC resource in Glassfish so it can be use in an EJB 3 for database connection. This is Glassfish v2 by the way.

Prequisites:
- Place database jdbc lib on $GLASSFISH_HOME/lib

First, start Glassfish ($GLASSFISH_HOME/bin/asadmin start-domain domain-name), then go to admin page

Let’s create connection pool for MySql:
1. Select Resources –> JDBC –> Connection Pools, then click new… button.

glassfish01

2. Enter connection pool name, resource type, and database vendor. then click next.

glassfish02
3. on page 2, scroll down to bottom of the page. And set Additional Properties with your own environtment. Like DatabaseName, User, Password, Port, ServerName, URL, etc. Then click finish.

glassfish03
4. We can see our connection pool we had just create on the list. Click on the connection pool name.

glassfish04
5. Click Ping button to see if the connection is succeed.

glassfish05

6. Now we create JDBC resource using connection pool we had just create. Select Resources –> JDBC –>JDBC Resources, then click New… button

glassfish06

7. Enter JNDI name, Pool name, etc. JNDI name ussualy in format “jdbc/JNDI_NAME”. Then click OK

glassfish07

8. JDBC Resources is created

glassfish08

Now lets test it. to see if the JDBC connection pool and resource we had just created is working. I use EJB 3 on this.

(to be continued…)

My laptop is Lenovo 3000 G430, i don’t really sure what it’s official name. Sometimes it’s called LENOVO IdeaPad G430 953, 953 is my laptop series. I was using openSUSE 11 and Widows Vista as operating system, and here is the result: on openSUSE 11 everything is fine except for the touchpad, wifi, and dial-up modem (maybe), it is not working. on Windows Vista everything is working, thanks to the drivers on Windows Vista version.

Only openSUSE 11 and Fedora 9-10, linux distros that succesfully installed. Ubuntu 8.04 and Linux Mint was failed on installation process.

I think Lenovo 3000 G430 is very Widows Vista oriented, they only provide drivers for Windows Vista. Even I can’t install Windows XP, it’s raised error message when booting from the installation CD. When i try openSUSE 11 installation CD on other laptop, the touchpad is working, but when i try openSolaris 2008 live CD on my laptop, the touchpad is woking :D . I spend many time to get the touchpad works, it’s just keep failed, it’s gave me a headache just to make the touchpad working. Maybe someone can help me? And also my wifi device still not working even after i get instruction from this sites.

Overall, i almost satisfied with the colaboration of Lenovo 3000 G430 and openSUSE 11, many of hardware device isn’t working on Windows Vista if I dont install the driver, but openSUSE 11 has done a good job. Maybe if the touchpad and wifi is working with openSUSE 11, I will be very pleased and can get rid off Windows :P . Just sharing my experiences….

Updated 03-08-2009:
Finally WIFI is working using Ndiswrapper, because my wireless PCI device is not supported by Linux at this momment.

My wireless is BCM4310 with device PID is 14e4:4315 as state here it is not supportted :( , so i install ndiswrapper using OpenSUSE 1-Click Install. Using Ndiswrapper we need INF file from Windows driver which is bcmwl5.inf , i got it from here and here and here, there is 482.1kb and 727.3kb version, just use the 727.3kb version.

Updated 28-09-2009:
Now i’ve got Ubuntu 9.04 installed. Everything work fine except for touchpad need to press Fn+F8 twice to get it working. Wifi NO NEED Ndiswrapper, but sometimes need to turn on wifi from Windows.

See you Lufthansa Systems, thank you so much for great moments… :)

Welcome PT. Aero Systems Indonesia, let’s build this company… :)

Refer to this link to prepare the instalation. Follow every steps mentioned. Here is the steps:

  1. Install openSUSE 11.0 with “C/C++ Development” selection.
  2. Download and Install orarun package. Enable and set password for newly created user oracle by orarun.
  3. Change some environment variables – ORACLE_HOME, ORACLE_SID, TNS_ADMIN in /etc/profile.d/oracle.sh.
  4. Set updated kernel parameters by executing /etc/init.d/oracle start or rcoracle start.
  5. Download and extract Oracle Oracle 11gR1 SW.
  6. login as user oracle and run Oracle Universal Installer “database/runInstaller“. Just follow step by step questions of Oracle installer.

On my experience the setup isn’t working after I try to login (from console) as “oracle” user and start installation (step 6).
The orarun setup create “oracle” user as “System Users” not as “Local Users”, so i decide to delete “oracle” user and make the user manually from Yast –> Security And Users –> User and Group Management. Set Default Group to “oinstall” and additional groups to “dba” and “disk”.

Add user 1 Add user 2

Note: Do not create user from console (using useradd command), the created user not registered with X Server (and i dont know how to register user with X Server :) ), caused failed when try to start installation.

After “oracle” user is created, login as “oracle” user from console then start installation by typing “./runInstaller”. Just fill every required information, and keep press next or press yes if there’s prerequisite check warning, until installation is finished. After installation is finished we can browse to oracle database using Oracle Enterprise Manager Database Control using address https://[HOST_NAME]:1158/em

Installation Screenshot
oracle01 oracle02

oracle03 oracle04

oracle05 oracle06

oracle07 oracle08

oracle09 oracle10

Starting Oracle database after Reboot/Restarting
Oracle 11g database is not automatically started when we turn on computer/laptop, this is steps to start oracle database:
1. Open console, login as “oracle” user
startoracle01

2. login to sqlplus, then type “STARTUP” to start database.
startoracle02

3. Exit from sqlplus (type “exit”)

4. Start Oracle Net Listener, type “lsnrctl start [LISTENER]“
startoracle03

5. Start Oracle Enterprise Manager Database Control service, type “emctl start dbconsole”
startoracle04

Oracle Enterprise Manager Database Control Screenshot
oem01 oem02oem03

- Extract tar.gz files
> tar -xvzf FILE_NAME.tar.gz

- Compress to tar.gz
> tar -cvzf OUTPUT_FILE_NAME.tar.gz FOLDER_OR_FILES_BEING_COMPRESS/

- Extract tar.bz2 files
> tar -xvjf FILE_NAME.tar.bz2

- Compress to tar.bz2
> tar -cvjf OUTPUT_FILE_NAME.tar.bz2 FOLDER_OR_FILES_BEING_COMPRESS/

- Start/Restart network
> /etc/init.d/network [start|restart]

- Force kill process
> kill -9 [PID]

- Show services/process
> ps aux

- Show services/process with filter
> ps aux | grep [FILTER]

- SSH
> ssh [USERNAME]@[HOST/IP] <enter then enter pasword>

- Change files or folder owner (must as root)
> chown USERNAME:GROUP FILE_NAME_OR_FOLDER_NAME

- Change folder owner and it’s subdirectory (must as root)
> chown -R USERNAME:GROUP FOLDER_NAME

- Start Mysql service on openSuse 11
> service mysql start (as root)
then type “mysql” to login into Mysql

- SCP , transfer files over network
(for single file)
> scp [USER@HOST:]SOURCE_FILE_NAME USER@HOST:DESTINATION_DIRECTORY
(eg. “> scp Twilight.avi root@168.27.10.200:/home/root/movie“)
then enter destination password.

(for directory with multiple files)
> scp -r [USER@HOST:]SOURCE_DIRECTORY_NAME USER@HOST:DESTINATION_DIRECTORY
(eg. “> scp -r Movies budi@140.27.10.240:/home/budi“)
then enter destination password.

Other samples:
“> scp -r budi@140.27.10.240:/home/budi/SexyImage .” , will copies “SexyImage” directory from user “budi” at “140.27.10.240″ to our current directory. We need to provide user “budi” password.

- Remove folder
> rm -rf FOLDER_NAME

I use Glassfish for application server. Here is the EJB:
(interface)

package ejb3.bean;
import javax.ejb.Remote;

@Remote
public interface HelloEjb {
    String printHello(String name);
}

(implementation)

package ejb3.bean;
import javax.ejb.Stateless;

@Stateless( name="HelloEjb")
public class HelloEjbBean implements HelloEjb {
    public HelloEjbBean() {}

    public String printHello(String name) {
        return "Hello bro " + name + " welcome to EJB 3";
    }
}

Package it as JAR or EAR, start Glassfish( GLASSFISH_HOME/bin/asadmin start-domain DOMAIN_NAME ) then use Admin Console (default: http://localhost:4848 ) to deploy the EJB.

To call the EJB from servlet we can directly use @EJB annotations, to get the instance of the EJB. In below sample i send the EJB to JSP page:

package ejb3.servlet;

import ejb3.bean.HelloEjb;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.ejb.EJB;
import java.io.IOException;

public class HelloEjb3Servlet extends HttpServlet {
    @EJB
    private HelloEjb helloEjb;

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

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

	private void execute(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
        	request.setAttribute("helloEjb", helloEjb);
        	request.setAttribute("printHello", helloEjb.printHello("Djunaedi"));
        	request.getRequestDispatcher("/HelloEjb3.jsp").forward(request, response);
	}
}

To get EJB instance in JSP using @EJB (inside scriplets) isn’t working, i get null instance. So i use JNDI lookup and that’s work:

<%@ page import="ejb3.bean.HelloEjb" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.Context" %>
<html>
<head><title>Hello EJB 3 !</title></head>
<body>
<%!
HelloEjb helloEjb;
%>
<%
try {
Context context = new InitialContext();
helloEjb = (HelloEjb) context.lookup(HelloEjb.class.getName());
}
catch(Exception e) {
// exception code here
}
%>
<p>
Object HelloEjb Directly : <%= helloEjb %><br>
Print Hello : <%= helloEjb.printHello("Ujang") %>

<p>
Object HeloEjb from Servlet : <%= request.getAttribute("helloEjb") %><br>
Print Hello : <%= request.getAttribute("printHello") %>
</body>
</html>

notes:
Calling EJB 3 using JNDI lookup isn’t the same between Application Server, JNDI lookup name is not standardized. Refer to this article find out more.

References:
- http://www.adam-bien.com/roller/abien/entry/ejb_3_portability_issue_why
- http://javahowto.blogspot.com/2006/09/default-jndi-name-for-resource-or-ejb.html
- https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html

I was trying to make an alternative of @MappedSuperclass using Hibernate XML (*.hbm.xml) files. The case is i want every persistent class have default column like ID, CREATED_ON, CREATED_BY, UPDATED_ON, UPDATED_BY – that reside on a superclass, so i don’t have to repeat those column in every mapping files. Unfortunately, basically hibernate do not support this kind of superclass mapping. Maybe the technique here will do just fine, but lack of something that i will tell later.

Nowaday programming style is coding by interface so i use interface for every persistent class and separate it’s implementation. The relationship is one-to-many between Singer and Album.

Here is BaseModel interface that every persistent class will inherits all the properties, followed by it’s concrete class and mapping:
(BaseModel.java)

package hibernate.example.model;

import java.util.Date;

public interface BaseModel {
    public Integer getId();
    public void setId(Integer id);
    public String getCreatedBy();
    public void setCreatedBy(String createdBy);
    public Date getCreatedOn();
    public void setCreatedOn(Date createdOn);
    public String getUpdatedBy();
    public void setUpdatedBy(String updatedBy);
    public Date getUpdatedOn();
    public void setUpdatedOn(Date updatedOn);
    public String getName();
    public void setName(String name);
}

(BaseModelImpl.java)

package hibernate.example.model;

import java.util.Date;

public class BaseModelImpl implements BaseModel {
    private Integer id;
    private String createdBy;
    private Date createdOn;
    private String updatedBy;
    private Date updatedOn;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public String getUpdatedBy() {
        return updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }

    public Date getUpdatedOn() {
        return updatedOn;
    }

    public void setUpdatedOn(Date updatedOn) {
        this.updatedOn = updatedOn;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

(BaseModel.hbm.xml)

<hibernate-mapping package="hibernate.example.model">
    <class name="BaseModel" abstract="true">
        <id name="id" type="integer" column="ID">
            <generator class="increment"/>
        </id>
       <property name="createdBy" type="string" column="CREATED_BY"/>
       <property name="createdOn" type="timestamp" column="CREATED_ON"/>
       <property name="updatedBy" type="string" column="UPDATED_BY"/>
       <property name="updatedOn" type="timestamp" column="UPDATED_ON"/>
       <property name="name" type="string" column="NAME"/>
    </class>
</hibernate-mapping>

Singer Entity:
(Singer.java)

package hibernate.example.model;

import java.util.Set;

public interface Singer extends BaseModel {
    public Set<Album> getAlbums();
    public void setAlbums( Set<Album> albums );
}

(SingerImpl.java)

package hibernate.example.model;

import java.util.Set;

public class SingerImpl extends BaseModelImpl implements Singer {
    private Set<Album> albums;

    public SingerImpl() {}

    public Set<Album> getAlbums() {
        return albums;
    }

    public void setAlbums(Set<Album> albums) {
        this.albums = albums;
    }
}

(Singer.hbm.xml)

<hibernate-mapping package="hibernate.example.model">
    <union-subclass name="Singer" extends="BaseModel" abstract="true">
        <set name="albums" inverse="true" cascade="all-delete-orphan">
            <key column="ID_SINGER"/>
            <one-to-many class="Album"/>
        </set>
    </union-subclass>

    <union-subclass name="SingerImpl" extends="Singer" table="SINGER"/>
</hibernate-mapping>

Album Entity:
(Album.java)

package hibernate.example.model;

public interface Album extends BaseModel {
    public String getYear();
    public void setYear(String year);
    public Singer getSinger();
    public void setSinger(Singer singer);
}

(AlbumImpl.java)

package hibernate.example.model;

public class AlbumImpl extends BaseModelImpl implements Album {
    private Singer singer;
    private String year;

    public Singer getSinger() {
        return singer;
    }

    public void setSinger(Singer singer) {
        this.singer = singer;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }
}

(Album.hbm.xml)

<hibernate-mapping package="hibernate.example.model">
    <union-subclass name="Album" extends="BaseModel" abstract="true">
        <property name="year" type="string" column="YEAR" />

        <many-to-one name="singer" column="ID_SINGER"
            class="Singer" not-null="true" />

    </union-subclass>

    <union-subclass name="AlbumImpl" extends="Album" table="ALBUM" />
</hibernate-mapping>

Here is hibernate.cfg.xml:

<hibernate-configuration>
  <session-factory>
<!--    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/SCHEMA_NAME</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
-->
    <property name="hibernate.connection.url">jdbc: oracle:thin:@localhost:1521:SID</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

    <!-- DB schema will be updated if needed -->
    <property name="hibernate.hbm2ddl.auto">update</property>

    <mapping resource="hibernate/example/model/BaseModel.hbm.xml" />
    <mapping resource="hibernate/example/model/Singer.hbm.xml" />
    <mapping resource="hibernate/example/model/Album.hbm.xml" />
  </session-factory>
</hibernate-configuration>

Simple test application can look like this:
(TestApp.java)

package hibernate.example.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.example.model.Singer;
import hibernate.example.model.SingerImpl;
import hibernate.example.model.Album;
import hibernate.example.model.AlbumImpl;

import java.util.Date;

public class TestApp {
    private Session session;
    private Transaction tx;

    public TestApp() {
        SessionFactory sessionFac = new Configuration().configure().buildSessionFactory();
        session = sessionFac.openSession();
    }

    public static void main(String args[]) {
        TestApp app = new TestApp();
        app.insertSinger();
        app.insertAlbum();
    }

    // insertSinger
    public void insertSinger() {
        Singer singer = new SingerImpl();
        singer.setCreatedOn( new Date() );
        singer.setCreatedBy( "admin" );
        singer.setName( "Mariah Carey" );

        tx = session.beginTransaction();
        session.save( singer );
        tx.commit();
    }

    // insertAlbum
    public void insertAlbum() {
        Singer singer = (SingerImpl) session.get( SingerImpl.class, 1 );

        Album album = new AlbumImpl();
        album.setCreatedOn( new Date() );
        album.setCreatedBy( "admin" );
        album.setName( "Rainbow" );
        album.setYear( "2000" );
        album.setSinger( singer );

        tx = session.beginTransaction();
        session.save( album );
        tx.commit();
    }
}

Result table will look like:
- Singer table
Singer table
- Album table
Album table

Here or here is full source code. Change *.odt to *.zip, then extract it. Edit hibernate.cfg.xml to match your environtment, and add required library to lib folder.

Dependency Library:
depandency's

NOTE :
Using <union-subclass> Hibernate still treat the mapping as table per concrete class. Every id’s for each persistent class will use the same generated id. And also in Oracle database it doesn’t create Singer foreign key constraint on Album table, so if we dropped Singer table it doesn’t make constraint violation error.

There is few ways to set path or environment variables in linux. Not every linux distros had the same way to do this, but the commons way we can set path using this three methods:

- using file ~/.bashrc
- using file ~/.bash_profile
- create bash file (*.sh) in folder /etc/profile.d/

Sometimes in a linux distro can use all that three methods, sometimes it isn’t, based on the distro. We only have to use one of that three methods to setting path or environment variables.

I don’t really know what is the different between setting path in ~/.bashrc or in ~/.bash_profile, the result is the same :) . It’s user level bash file, the setting is only work for current user. I think when a user login or a user open a shell terminal, it will read settings on those two files (user own version). To set path in that two files just open in text editor or using VI editor, and enter the path, usually in the last line. Save and reopen shell terminal. The sample will look like:

export JAVA_HOME=/opt/jdk1.6.0
PATH=$PATH:$JAVA_HOME/bin:.
export PATH

Other alternative is create .sh in folder /etc/profile.d/, for example blablabla.sh. To create file in that folder we need root access, and the setting will apply in all user, so it’s system wide setting (that’s i called it). Again i think when linux boot and run, it will read every *.sh files in the folder and set the linux system based on the files. But notes, not every linux distro set linux system using this method, sometimes it’s not working. So in the blablabla.sh, enter path setting like in above sample. Save and reboot your computer.

If there’s other ways, please tell me. Thanks.