0% found this document useful (0 votes)
56 views

CS547

The document describes two methods for accessing relational databases in Java: JDBC and Hibernate framework. JDBC is a Java library that allows Java programs to execute SQL statements and interact with SQL databases. Hibernate is an ORM framework that maps Java classes to database tables and relieves developers from manual data processing using SQL and JDBC. The document then provides details on using JDBC, Hibernate mapping, and an example program for a shopping cart application that uses JDBC to interact with product and cart tables in a database.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

CS547

The document describes two methods for accessing relational databases in Java: JDBC and Hibernate framework. JDBC is a Java library that allows Java programs to execute SQL statements and interact with SQL databases. Hibernate is an ORM framework that maps Java classes to database tables and relieves developers from manual data processing using SQL and JDBC. The document then provides details on using JDBC, Hibernate mapping, and an example program for a shopping cart application that uses JDBC to interact with product and cart tables in a database.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Question 1

Briefly explain the methods of accessing relational data bases in Java?

There are two methods ways in which Java programs interact with database:
i. JDBC
ii. Hibernate framework
JDBC

JDBC stands for Java DataBase Connectivity. It is a Java library (API) for accessing the relational databases

from Java program. The JDBC library enables Java programs to execute SQL statements and interact with any

SQL compliant database. Before continuing with JDBC, it is highly recommended that programmer have

knowledge of the following:

 Core Java Programming

 MySQL database – syntax for CRUD (Create Read Update Delete) operations

Typically, working with JDBC requires the following steps or procedures:

1. Load the database driver

2. Open a connection

3. Create and execute query – this is where the knowledge of SQL comes in

4. Use result sets to navigate through the results

5. Close the connection

HIBERNATE FRAMEWORK

Hibernate is an ORM framework for Java programs. Hibernate framework provides a way to map Java

classes to database tables, and also map relational database tables to Java classes It does not only takes

care of the mapping from Java classes to database tables, but also provides data query and retrieval

facilities. Java classes whose objects or instances will be stored in database tables are called persistent

classes in Hibernate. These persistent classes are also called POJO classes – Plain Old Java Object

(POJO). The goal of Hibernate framework is to relieve the developer from common data persistence-

1
related programming tasks by eliminating the need for manual, hand-crafted data processing using SQL

and JDBC. Hibernate is most useful with object oriented domain models and business logic in the Java-

based middletier. You don‘t need to have a strong background in SQL in order to use Hibernate,

however having a basic understanding of the SQL can greatly help you understand Hibernate more fully

and quickly.

ORM stands for Object Relational Mapping. It is a programming technique of mapping data from an

object model representation to a relational data model representation (and visa versa). ORM frame

works such as hibernate converts data between relational databases and classes (and vice versa).

Hibernate Mapping

Hibernate uses two method to map Java classes to database tables.

a) Using xml configuration file In this method, an XML file which define to map the java class or

classes to the database tables. Hibernate uses the XML mapping file for the transformation of

data from Java classes (POJO) to database tables.

b) Using Hibernate annotations This is the new most widely used method. Here annotations used

instead of XML file. Hibernate Annotations is the powerful way to provide the metadata for the

Object and Relational Table mapping. Examples of hibernate annotations are: @Entity,

@Column, @Id, etc If you are going to make your application portable to other EJB 3 compliant

ORM applications, you must use annotations to represent the mapping information.

2
Question 2

In a typical online shopping application, a virtual cart is created to hold products that user wishes to buy.
The total amount of products in the cart is always displayed. When user can add or delete products from
the cart, the amount adjusts accordingly. Technically, the cart is nothing but a table in database.
TASK
i. Create a database with the name cs547assignment2021
ii. Create two table with the names products and cart whose structure and content is as
follows:
iii. Products table
id product_name quantity unit_price
1 Peak Milk 900g 32 1050
2 Milo 900g 12 900
3 Sugar cube 40 450
4 Ariel 1kg 26 700
5 Dettol soap 110 900

Cart Table
id product_id qty
1 2 4
2 1 2
3 5 3

Figure 1: Screenshot of Product details design in Netbeans IDE

3
Figure 2: Cart Form designed in Netbeans IDE

Figure 2: Products table database view via PHPMYADMIN

Figure 4: Cart Table in CS5473Assignment2021 Database view via PHPMYADMIN


4
Program Source Code
//Importing java API libraries
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
//import java.sql.SQLException;

/**
*
* @author USMAN SULEH
*/
public class product extends javax.swing.JFrame {

/**
* Creates new form product
*/
public product() {
initComponents();
Connect (); //invoke connect method
LoadProductno(); //invoke LoadProductno method
}

Connection con; //create the connection object con


PreparedStatement pst; // create the PreparedStatement object pst
ResultSet rs; // create the ResultSet object rs
Statement stmt; // create the Statement object stmt

public void Connect()//Method for Database Connection


{
try
{
Class.forName("com.mysql.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost/CS547Assignment2021", "root",
"");

}
catch (ClassNotFoundException ex)
{
Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
// ex.printStackTrace();
}
catch (SQLException ex)
{
Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
// ex.printStackTrace();
}
}

public void LoadProductno() //Method for fetching product_id in the database


table
{
try
{
pst = con.prepareStatement("SELECT id FROM products");
5
rs = pst.executeQuery();
txtpid.removeAllItems();

while (rs.next())
{
txtpid.addItem(rs.getString(1));
}
}
catch ( Exception e)
{
e.printStackTrace();
}
}

private void initComponents() {


//Java Swing Control here (jLabel, JTextField, jCombo, jButton where //declared
here

}// </editor-fold>

//Adding Product to the database


private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {

String pname = txtpname.getText();


String qty = txtqty.getText();
String price = txtprice.getText();

try
{
pst = con.prepareStatement("insert into products
(product_name,quantity,unit_price)values(?,?,?)");
pst.setString(1, pname);
pst.setString(2, qty);
pst.setString(3, price);
int k = pst.executeUpdate();
if(k==1)
{
JOptionPane.showMessageDialog(this, "Record Added Successfully!");
txtpname.setText("");
txtqty.setText("");
txtprice.setText("");
txtpname.requestFocus();
LoadProductno();
}
else
{
JOptionPane.showMessageDialog(this, "Record Failed, Not Inserted!");
}

}
catch (SQLException ex)
{
Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
}
}

6
//to Search Product in the database

private void btnsearchActionPerformed(java.awt.event.ActionEvent evt) {


String pid = txtpid.getSelectedItem().toString();
try
{
pst = con.prepareStatement( "SELECT * FROM products where id = ?" );
pst.setString(1, pid);
rs = pst.executeQuery();

if ( rs.next() == true )
{
txtpname.setText(rs.getString(2));
txtqty.setText(rs.getString(3));
txtprice.setText(rs.getString(4));
}
else
{
JOptionPane.showMessageDialog(this, "Record Not Found");
}
}
catch ( Exception e )
{
e.printStackTrace();
}

//Method to Update Product in the database


private void btnupdateActionPerformed(java.awt.event.ActionEvent evt) {
String pname = txtpname.getText();
String price = txtqty.getText();
String qty = txtprice.getText();
String pid = txtpid.getSelectedItem().toString();
try
{
pst = con.prepareStatement("update products set product_name = ?, quantity = ?,
unit_price= ? where id = ?");
pst.setString(1, pname);
pst.setString(2, qty);
pst.setString(3, price);
pst.setString(4, pid);
int k = pst.executeUpdate();
if(k==1)
{
JOptionPane.showMessageDialog(this, "Record Updated Successfully!");
txtpname.setText("");
txtqty.setText("");
txtprice.setText("");
txtpname.requestFocus();
LoadProductno();
}
else
{
JOptionPane.showMessageDialog(this, "Record Updation Failed!");

7
}

}
catch (SQLException ex)
{
Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
}
}

//Method to Clear Product details in the GUI interface and begin a fresh
private void btnnewActionPerformed(java.awt.event.ActionEvent evt) {

txtpname.setText("");
txtqty.setText("");
txtprice.setText("");
txtpname.requestFocus();
LoadProductno();
}

//Method to Clear Product details in the GUI interface and begin a fresh
private void btndeleteActionPerformed(java.awt.event.ActionEvent evt) {
try {

String pid = txtpid.getSelectedItem().toString();

pst = con.prepareStatement("delete from products where id =?");


pst.setString(1, pid);
int k = pst.executeUpdate();

if(k==1)
{
JOptionPane.showMessageDialog(this, "Record Deleted Successfully!");
txtpname.setText("");
txtqty.setText("");
txtprice.setText("");
txtpname.requestFocus();
LoadProductno();
}
else
{
JOptionPane.showMessageDialog(this, "Record Deletion Failed!");
}

} catch (SQLException ex) {


Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
}

//Method for Database Connection


public void Connect() {
try
{
Class.forName("com.mysql.jdbc.Driver");

8
con =
DriverManager.getConnection("jdbc:mysql://localhost/CS547Assignment2021", "root",
"");

}
catch (ClassNotFoundException ex)
{
Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
// ex.printStackTrace();
}
catch (SQLException ex)
{
Logger.getLogger(product.class.getName()).log(Level.SEVERE, null, ex);
// ex.printStackTrace();
}
}

//Code to fetch and display data from database

//sql statement to select items from database


String sqlFetch = "SELECT * FROM cart"; //sql statement to fetch data from database
rs = stmt.executeQuery(sqlFetch);
//while loop to fetch and display data from database
while (rs.next()) { //getting the items from the resultset by specifying the
column index
int pid = rs.getInt(1);
String pname = rs.getString(2);
int qty = rs.getInt(3);
int price = rs.getInt(4);
System.out.println(sn + "\t" + name + "\t" + quantity + "\t" +
price);
}

//Code to sum up and display the data in unit_price column

// sql statement to sum up the unit price column


String sqlTotal = "SELECT SUM(unit_price) FROM cart";
ResultSet rsTotal = stmt.executeQuery(sqlTotal);
//a while loop to compute the sum
while (rsTotal.next()) {
int total = rsTotal.getInt(1);
System.out.println("Total Price: \t\t\t" + total);

}
9
10
REFERENCES

1. Aliyu, I. (2021). Advance Programming Language. A Lecture Notes, Department of

Mathematical Sciences, Abubakar Tafawa Balewa University, Bauchi.

2. Paul Deital, Harvey Deital. Java How to program, 9th edition. 2012.

3. Cay S. Horstmann, Gary Cornel, Core Java volume I fundamentals. Prentice Hall, 2008.

4. Y. Daniel Liang. Introduction to Java programming Languages, 8th edition. Prentice Hall, 2011.

5. Binstock, Andrew (May 20, 2015). “Java’s 20 Years of Innovation Forbes. Archived from the

original on March 14, 2016. Retrieved August 16, 2021

6. “Consolidated JDK 16 Releases Notes. July 20, 2021. Retrieved August 16, 2021.

7. Gosling, James; Joy, Bill; Steel, Guy; Bracha, Gilad. “The Java Language Specification, @nd

Edition Archived from the original on August 5, 2011. Retrieved August, 2021.

11

You might also like