Wednesday, July 8, 2009
Thursday, February 26, 2009
What Is Hibernate
Hibernate
Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables. It liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.
This article discusses the following:
History and Background
How Hibernate Works
When to Use Hibernate
Learning More
History and Background
Most applications have some need to work with data. Java applications, when running, tend to encapsulate data as networks of interconnected objects, but those objects vanish in a puff of logic when the program ends, so there needs to be some way to store them. And sometimes the data is already "out there" before the application is even written, so there needs to be a way to read it in and represent it as objects. Writing code by hand to perform these tasks is tedious and error-prone, and can represent a major portion of the effort involved in the overall application.
As good object-oriented developers got tired of this repetitive work, their typical tendency towards enlightened laziness started to manifest itself in the creation of tools to help automate the process. When working with relational databases, the culmination of such efforts were object/relational mapping tools.
There have been a variety of such tools, ranging from expensive commercial offerings to the EJB standards built into J2EE. In many cases, however, the tools introduce their own complexity, force the developer to learn detailed rules for using them, and to modify the classes making up their applications to conform to the needs of the mapping system. As the tools evolved to handle ever more rigorous and complex enterprise requirements, the intricacies required to use them started to overwhelm the savings you could obtain by doing so in simpler, common cases. This has led to something of a revolution favoring more lightweight solutions, of which Hibernate is an example.
How Hibernate Works
Hibernate doesn't get in your way; nor does it force you to change the way your objects behave. They don't need to implement any magical interfaces in order to be blessed with the ability to persist. All you need to do is create an XML "mapping document" telling Hibernate the classes you want to be able to store in a database, and how they relate to the tables and columns in that database, and then you can ask it to fetch data as objects, or store objects as data for you. Compared to most of the alternatives, it's almost magical.
There isn't room in an introductory article like this to work through a concrete example of building and using a Hibernate mapping document (that's what the first couple of chapters in my Hibernate: A Developer's Notebook are for, after all). And there are some good examples already on the Web and in the Hibernate online documentation; see "Learning More," on page 2. It really is straightforward, though. Properties in the application objects are associated with appropriate database structures in a simple, natural way.
At runtime, Hibernate reads the mapping document and dynamically builds Java classes to manage the translation between the database and Java worlds. There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database. To change those objects you just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; you just create them in the normal way and tell Hibernate about them so they can get stored to the database.
The Hibernate API is simple to learn and interacts quite naturally with the flow of your program. You invoke it in sensible places, and it does what you'd like it to. The benefits it brings in terms of automation and code savings greatly outweigh the short time it takes to learn. And you get an additional bonus in that your code doesn't care (or even have to know) what kind of database you're using. My company has had projects forced to change database vendors late in the development process. This can be a horrible mess, but with Hibernate it has required nothing more than a single change to the Hibernate configuration file.
This discussion has assumed that you already had a relational database set up, as well as Java classes to map, through the creation of the Hibernate mapping document. There is a Hibernate "toolset" that works at build time to support different workflows. For example, if you've got the Java classes and mapping document, Hibernate can create (or update) the necessary database tables for you. Or, starting with just the mapping document, Hibernate can generate the data classes for you, too. Or it can reverse engineer your database and classes to sketch out a mapping document for you. There are also some alpha plugins for Eclipse to provide intelligent editing support and graphical access to these tools right from within the IDE.
If you're in a Hibernate 2 environment, fewer of these tools are provided, but there are third-party options available.
Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables. It liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.
This article discusses the following:
History and Background
How Hibernate Works
When to Use Hibernate
Learning More
History and Background
Most applications have some need to work with data. Java applications, when running, tend to encapsulate data as networks of interconnected objects, but those objects vanish in a puff of logic when the program ends, so there needs to be some way to store them. And sometimes the data is already "out there" before the application is even written, so there needs to be a way to read it in and represent it as objects. Writing code by hand to perform these tasks is tedious and error-prone, and can represent a major portion of the effort involved in the overall application.
As good object-oriented developers got tired of this repetitive work, their typical tendency towards enlightened laziness started to manifest itself in the creation of tools to help automate the process. When working with relational databases, the culmination of such efforts were object/relational mapping tools.
There have been a variety of such tools, ranging from expensive commercial offerings to the EJB standards built into J2EE. In many cases, however, the tools introduce their own complexity, force the developer to learn detailed rules for using them, and to modify the classes making up their applications to conform to the needs of the mapping system. As the tools evolved to handle ever more rigorous and complex enterprise requirements, the intricacies required to use them started to overwhelm the savings you could obtain by doing so in simpler, common cases. This has led to something of a revolution favoring more lightweight solutions, of which Hibernate is an example.
How Hibernate Works
Hibernate doesn't get in your way; nor does it force you to change the way your objects behave. They don't need to implement any magical interfaces in order to be blessed with the ability to persist. All you need to do is create an XML "mapping document" telling Hibernate the classes you want to be able to store in a database, and how they relate to the tables and columns in that database, and then you can ask it to fetch data as objects, or store objects as data for you. Compared to most of the alternatives, it's almost magical.
There isn't room in an introductory article like this to work through a concrete example of building and using a Hibernate mapping document (that's what the first couple of chapters in my Hibernate: A Developer's Notebook are for, after all). And there are some good examples already on the Web and in the Hibernate online documentation; see "Learning More," on page 2. It really is straightforward, though. Properties in the application objects are associated with appropriate database structures in a simple, natural way.
At runtime, Hibernate reads the mapping document and dynamically builds Java classes to manage the translation between the database and Java worlds. There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database. To change those objects you just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; you just create them in the normal way and tell Hibernate about them so they can get stored to the database.
The Hibernate API is simple to learn and interacts quite naturally with the flow of your program. You invoke it in sensible places, and it does what you'd like it to. The benefits it brings in terms of automation and code savings greatly outweigh the short time it takes to learn. And you get an additional bonus in that your code doesn't care (or even have to know) what kind of database you're using. My company has had projects forced to change database vendors late in the development process. This can be a horrible mess, but with Hibernate it has required nothing more than a single change to the Hibernate configuration file.
This discussion has assumed that you already had a relational database set up, as well as Java classes to map, through the creation of the Hibernate mapping document. There is a Hibernate "toolset" that works at build time to support different workflows. For example, if you've got the Java classes and mapping document, Hibernate can create (or update) the necessary database tables for you. Or, starting with just the mapping document, Hibernate can generate the data classes for you, too. Or it can reverse engineer your database and classes to sketch out a mapping document for you. There are also some alpha plugins for Eclipse to provide intelligent editing support and graphical access to these tools right from within the IDE.
If you're in a Hibernate 2 environment, fewer of these tools are provided, but there are third-party options available.
Labels:
Hibernate
What is JDBC?
JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems.
Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.
Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to your query.
Labels:
JDBC
Accessing EJB In JBoss From Swing Client
This articles shows how to access a simple stateless session bean in EJB 3.0 from a Swing client. Though it sounds like a simple process, it needs good number of steps. You need to use good number or .jar files and properties to access ejb 3.0 from a remote client.
At the end of this article you will have learnt how to do the following:
Creating a simple stateless session bean using JBoss and NetBeans.
Getting access to Naming Service of JBoss from remote client
Using appropriate .jar file of JBoss to access an EJB deployed in JBoss from a remote client.
Creating a simple stateless session bean in JBoss with NetBeans
Follow the steps and code given below to create a stateless session bean with a single method. I use JBoss as the EJB Container and NetBeans IDE.
First configure NetBeans to use JBoss as application server using Tools ->Server Manager option of NetBeans.
Create a new project using File->New Project
Select Enterprise as category and EJB Module as type of project
Enter HelloEJB as the name of the project
Select Stateless and type of EJB and Remote as the interface
NetBeans provides - HelloRemote.java and HelloBean.java
Go to HelloBean.java. Invoke popup menu (right click) and select EJB Methods->Add Business Method
Enter sayHello as name of the method and String as return type
Write the code shown below. At the end of the process HelloRemote.java and HelloBean.java should be as shown below.
// HelloRemote.java
package st;
import javax.ejb.Remote;
@Remote
public interface HelloRemote {
String sayHello();
}
// HelloBean.java
package st;
import javax.ejb.Stateless;
@Stateless
public class HelloBean implements HelloRemote {
public HelloBean() {
}
public String sayHello() {
return "Hello";
}
}
Go to Projects window using Window->Projects
Right click on project name to invoke popup menu and select Deploy Project option to deploy project
Creating Swing Client
Now, let us create a frame-based swing application to access EJB. This swing application runs on its own and not in JBoss. So, it is called as remote client to EJB. Client project needs to have access to a couple of .jar files to access to JBoss and EJB deployed in JBoss.
Take the following steps related to client:
Create a new project using File->New Project
Select General in category and Java Application as project type
Give project name as SwingClient
Select the project (SwingClient) in Projects window. Go to libraries node, right click and select Add Jar/Folder .
Add the following libraries (.jar files) to SwingClient project.
HelloEjb.jar - Jar file of HelloEJB application. This is found in dist directory of the project
jboss-ejb3-client.jar, jboss-aop-jdk50-client.jar, jboss-aspect-jdk50-client.jar and jbossall-client.jar - all these .jar files are found in client folder of JBoss installation directory( For ex, d:\jboss)
Add a Java class (HelloClient) to project using File->New File, select Java Classes in categories and Java Class as File Type
Write the following code in HelloClient.java
import java.util.Properties;
import javax.naming.InitialContext;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import st.HelloRemote;
public class HelloClient extends JFrame {
public HelloClient() {
super("Hello Client");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JButton b1 = new JButton("Access EJB");
getContentPane().add(b1, BorderLayout.PAGE_END);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String msg = "";
try {
// Access JNDI Initial Context.
Properties p = new Properties();
p.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
p.put("java.naming.provider.url","jnp://localhost:1099");
p.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
InitialContext ctx = new InitialContext(p);
// Change jndi name according to your server and ejb
HelloRemote remote = (HelloRemote) ctx.lookup("HelloBean/remote");
msg = "Message From EJB --> " + remote.sayHello();
}
catch(Exception ex){
msg = "Error --> " + ex.getCause().toString();
}
JOptionPane.showMessageDialog(HelloClient.this,msg,"Message", JOptionPane.INFORMATION_MESSAGE);
}
});
setSize(200,200);
} //
public static void main(String args[]) {
new HelloClient().setVisible(true);
}
}
Run HelloClient class by selecting Run File option from popup menu (right click).
Click on Access EJB button and you must see a message dialog with message coming from ejb - Hello.
I hope this article helps you to understand how to access an EJB deployed in JBoss from a remote client. Remote client may be a swing application, a console application or a web application.
At the end of this article you will have learnt how to do the following:
Creating a simple stateless session bean using JBoss and NetBeans.
Getting access to Naming Service of JBoss from remote client
Using appropriate .jar file of JBoss to access an EJB deployed in JBoss from a remote client.
Creating a simple stateless session bean in JBoss with NetBeans
Follow the steps and code given below to create a stateless session bean with a single method. I use JBoss as the EJB Container and NetBeans IDE.
First configure NetBeans to use JBoss as application server using Tools ->Server Manager option of NetBeans.
Create a new project using File->New Project
Select Enterprise as category and EJB Module as type of project
Enter HelloEJB as the name of the project
Select Stateless and type of EJB and Remote as the interface
NetBeans provides - HelloRemote.java and HelloBean.java
Go to HelloBean.java. Invoke popup menu (right click) and select EJB Methods->Add Business Method
Enter sayHello as name of the method and String as return type
Write the code shown below. At the end of the process HelloRemote.java and HelloBean.java should be as shown below.
// HelloRemote.java
package st;
import javax.ejb.Remote;
@Remote
public interface HelloRemote {
String sayHello();
}
// HelloBean.java
package st;
import javax.ejb.Stateless;
@Stateless
public class HelloBean implements HelloRemote {
public HelloBean() {
}
public String sayHello() {
return "Hello";
}
}
Go to Projects window using Window->Projects
Right click on project name to invoke popup menu and select Deploy Project option to deploy project
Creating Swing Client
Now, let us create a frame-based swing application to access EJB. This swing application runs on its own and not in JBoss. So, it is called as remote client to EJB. Client project needs to have access to a couple of .jar files to access to JBoss and EJB deployed in JBoss.
Take the following steps related to client:
Create a new project using File->New Project
Select General in category and Java Application as project type
Give project name as SwingClient
Select the project (SwingClient) in Projects window. Go to libraries node, right click and select Add Jar/Folder .
Add the following libraries (.jar files) to SwingClient project.
HelloEjb.jar - Jar file of HelloEJB application. This is found in dist directory of the project
jboss-ejb3-client.jar, jboss-aop-jdk50-client.jar, jboss-aspect-jdk50-client.jar and jbossall-client.jar - all these .jar files are found in client folder of JBoss installation directory( For ex, d:\jboss)
Add a Java class (HelloClient) to project using File->New File, select Java Classes in categories and Java Class as File Type
Write the following code in HelloClient.java
import java.util.Properties;
import javax.naming.InitialContext;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import st.HelloRemote;
public class HelloClient extends JFrame {
public HelloClient() {
super("Hello Client");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JButton b1 = new JButton("Access EJB");
getContentPane().add(b1, BorderLayout.PAGE_END);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String msg = "";
try {
// Access JNDI Initial Context.
Properties p = new Properties();
p.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
p.put("java.naming.provider.url","jnp://localhost:1099");
p.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
InitialContext ctx = new InitialContext(p);
// Change jndi name according to your server and ejb
HelloRemote remote = (HelloRemote) ctx.lookup("HelloBean/remote");
msg = "Message From EJB --> " + remote.sayHello();
}
catch(Exception ex){
msg = "Error --> " + ex.getCause().toString();
}
JOptionPane.showMessageDialog(HelloClient.this,msg,"Message", JOptionPane.INFORMATION_MESSAGE);
}
});
setSize(200,200);
} //
public static void main(String args[]) {
new HelloClient().setVisible(true);
}
}
Run HelloClient class by selecting Run File option from popup menu (right click).
Click on Access EJB button and you must see a message dialog with message coming from ejb - Hello.
I hope this article helps you to understand how to access an EJB deployed in JBoss from a remote client. Remote client may be a swing application, a console application or a web application.
Labels:
EJB
Subscribe to:
Posts (Atom)