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

Class - 2 June

The document discusses using JDBC to work with relationships in Java using one-to-many and many-to-many relationships. It includes code for creating tables for categories, products, and admins with the appropriate foreign key relationships. It also includes code for beans and DAO classes to work with categories, products, and admins.

Uploaded by

Vikas Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Class - 2 June

The document discusses using JDBC to work with relationships in Java using one-to-many and many-to-many relationships. It includes code for creating tables for categories, products, and admins with the appropriate foreign key relationships. It also includes code for beans and DAO classes to work with categories, products, and admins.

Uploaded by

Vikas Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Working with Relationship using JDBC :

- One to many
- Many to many

MariaDB [training]> create table categories (id int primary key, name varchar(20) not
null unique, description varchar(100));
Query OK, 0 rows affected (0.048 sec)

MariaDB [training]> create table products (id int primary key auto_increment, name
varchar(50), description varchar(200), price float,
-> brand varchar(20), image varchar(50), cid int, foreign key(cid) references
categories(id));
Query OK, 0 rows affected (0.078 sec)
MariaDB [training]> create table admin (id int primary key auto_increment, name
varchar(20), userid varchar(20), password varchar(20));
Query OK, 0 rows affected (0.038 sec)

MariaDB [training]> insert into admin(name, userid,password) values('vikas


pathak','[email protected]', 'vikas12345');
Query OK, 1 row affected (0.007 sec)
MariaDB [training]> insert into admin(name, userid,password) values('rohit
kumar','[email protected]', 'rohit12345');
Query OK, 1 row affected (0.006 sec)

Admin Bean :

package models.beans;
public class Admin {
private int id;
private String name,userid, password;

public Admin() {
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public String getUserid() {
return userid;
}

public void setUserid(String userid) {


this.userid = userid;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

}
adminDao :

package models.doas;
import java.sql.*;
import models.connect.ConnectionProvider;
import models.beans.Admin;

public class AdminDao {


public Admin findByLoginDetails(String userid,String password){
Admin admin =null;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "select * from admin where userid=? and password=?";
PreparedStatement smt= con.prepareStatement(sql);
smt.setString(1, userid);
smt.setString(2, password);
ResultSet rs = smt.executeQuery();
if(rs.next()){
admin = new Admin();
admin.setId(rs.getInt("id"));
admin.setName(rs.getString("name"));
admin.setUserid(rs.getString("userid"));
admin.setPassword(rs.getString("password"));
}
con.close();
}catch(Exception e){
System.out.println("Admin login error : " + e.getMessage());
}
return admin;

public boolean changePassowrd(int id,String password){


boolean status= false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "update admin set password=? where id=?";
PreparedStatement smt= con.prepareStatement(sql);
smt.setString(1, password);
smt.setInt(2, id);
if(smt.executeUpdate()>0)
status=true;

con.close();
}catch(Exception e){
System.out.println("Admin login error : " + e.getMessage());
}
return status;

}
Category Bean :
package models.beans;

public class Category {


private int id;
private String name, description;

public Category() {
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


this.description = description;
}

}
CategoryDao :

package models.doas;
import java.sql.*;
import java.util.ArrayList;
import models.connect.ConnectionProvider;
import models.beans.Category;

public class CategoryDao {


public boolean add(Category category){
boolean status=false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "insert into categories(id,name,description) values(?,?,?)";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1, category.getId());
smt.setString(2, category.getName());
smt.setString(3,category.getDescription());
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("inser error : " + e.getMessage());
}
return status;
}

public boolean update(Category category){


boolean status=false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "update categories set name=? , description = ? where id=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(3, category.getId());
smt.setString(1, category.getName());
smt.setString(2,category.getDescription());
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("update error : " + e.getMessage());
}
return status;
}

public Category findById(int id){


Category category =null;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "select * from categories where id = ?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1,id);
ResultSet rs = smt.executeQuery();
if(rs.next()){
category = new Category();
category.setId(rs.getInt("id"));
category.setName(rs.getString("name"));
category.setDescription(rs.getString("description"));
}
con.close();
}catch(Exception e){
System.out.println("find error : " + e.getMessage());
}

return category;
}

public ArrayList<Category> findAll(){


ArrayList <Category> list = new ArrayList();
try{
Connection con = ConnectionProvider.getConnection();
String sql = "select * from categories";
PreparedStatement smt = con.prepareStatement(sql);
ResultSet rs = smt.executeQuery();
while(rs.next()){
Category category = new Category();
category.setId(rs.getInt("id"));
category.setName(rs.getString("name"));
category.setDescription(rs.getString("description"));

list.add(category);
}
con.close();
}catch(Exception e){
System.out.println("find all error : " +e.getMessage());
}

return list;
}

public boolean delete(int cid){


boolean status=false;
ProductDao pd = new ProductDao();
pd.deleteByCatId(cid);
try{
Connection con = ConnectionProvider.getConnection();
String sql = "delete from categories where id=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1, cid);
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("delete error : " + e.getMessage());
}

return status;
}
}
Product Bean :
package models.beans;
public class Product {
private int id,cid;
private String name, description, brand, image;
private float price;

public Product() {
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}
public int getCid() {
return cid;
}

public void setCid(int cid) {


this.cid = cid;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


this.description = description;
}

public String getBrand() {


return brand;
}

public void setBrand(String brand) {


this.brand = brand;
}

public String getImage() {


return image;
}

public void setImage(String image) {


this.image = image;
}

public float getPrice() {


return price;
}

public void setPrice(float price) {


this.price = price;
}

}
ProductDao :
package models.doas;
import java.sql.*;
import models.beans.Product;
import models.connect.ConnectionProvider;
import java.util.ArrayList;

public class ProductDao {


public boolean add(Product product){
boolean status= false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "insert into products
(name,description,price,brand,cid,image)values(?,?,?,?,?,?)";
PreparedStatement smt = con.prepareStatement(sql);
smt.setString(1, product.getName());
smt.setString(2, product.getDescription());
smt.setFloat(3, product.getPrice());
smt.setString(4, product.getBrand());
smt.setInt(5, product.getCid());
smt.setString(6, product.getImage());
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("insert error : " +e.getMessage());
}
return status;

public boolean update(Product product){


boolean status= false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "update products set name=?, description = ? , price=?,
brand=?,cid=?,image=? where id=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setString(1, product.getName());
smt.setString(2, product.getDescription());
smt.setFloat(3, product.getPrice());
smt.setString(4, product.getBrand());
smt.setInt(5, product.getCid());
smt.setString(6, product.getImage());
smt.setInt(7, product.getId());
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("insert error : " +e.getMessage());
}

return status;

}
public boolean delete(int id){
boolean status= false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "delete from products where id=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1, id);
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("insert error : " +e.getMessage());
}
return status;

public boolean deleteByCatId(int cid){


boolean status= false;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "delete from products where cid=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1, cid);
if(smt.executeUpdate()>0)
status=true;
con.close();
}catch(Exception e){
System.out.println("update error : " + e.getMessage());
}

return status;
}

public Product findById(int id){


Product product=null;
try{
Connection con = ConnectionProvider.getConnection();
String sql = "select * from products where id=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1, id);
ResultSet rs = smt.executeQuery();
if(rs.next()){
product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setDescription(rs.getString("description"));
product.setPrice(rs.getFloat("price"));
product.setBrand(rs.getString("brand"));
product.setImage(rs.getString("image"));
product.setCid(rs.getInt("cid"));

}
con.close();
}catch(Exception e){
System.out.println("insert error : " +e.getMessage());
}

return product;
}

public ArrayList<Product> findAll(){


ArrayList<Product> list = new ArrayList();
try{
Connection con = ConnectionProvider.getConnection();
String sql = "select * from products";
PreparedStatement smt = con.prepareStatement(sql);
ResultSet rs = smt.executeQuery();
while(rs.next()){
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setDescription(rs.getString("description"));
product.setPrice(rs.getFloat("price"));
product.setBrand(rs.getString("brand"));
product.setImage(rs.getString("image"));
product.setCid(rs.getInt("cid"));
list.add(product);
}
con.close();
}catch(Exception e){
System.out.println("insert error : " +e.getMessage());
}
return list;
}

public ArrayList<Product> findByCatId(int cid){


ArrayList<Product> list = new ArrayList();
try{
Connection con = ConnectionProvider.getConnection();
String sql = "select * from products where cid=?";
PreparedStatement smt = con.prepareStatement(sql);
smt.setInt(1, cid);
ResultSet rs = smt.executeQuery();
while(rs.next()){
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setDescription(rs.getString("description"));
product.setPrice(rs.getFloat("price"));
product.setBrand(rs.getString("brand"));
product.setImage(rs.getString("image"));
product.setCid(rs.getInt("cid"));
list.add(product);
}
con.close();
}catch(Exception e){
System.out.println("insert error : " +e.getMessage());
}
return list;
}

Login.jsp :

<%@page import="models.beans.Student"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<%@include file="csslink.jsp"%>

<style>
body{
font-family: corbel;
font-size: 20px;
align-content: center;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}

button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}

button:hover {
opacity: 0.8;
}

.cancelbtn {
width: 500px;
padding: 10px 18px;
background-color: #f44336;
}

img.avatar {
width: 40%;
border-radius: 50%;
}

.container {
padding: 16px;
}

span.psw {
float: right;
padding-top: 16px;
}

</style>
</head>
<body>
<jsp:include page="menubar.jsp"></jsp:include>
<br>

<%
Student student = (Student)session.getAttribute("student");
if(student!=null){
response.sendRedirect("student/dashboard.jsp");
}
String userid="", password="";
Cookie cookies[] = request.getCookies();
if (cookies!=null){
for(Cookie c :cookies){
if(c.getName().equals("uid"))
userid=c.getValue();
if(c.getName().equals("pwd"))
password = c.getValue();
}
}
%>

<div class="container">
<div class="row">
<div class="col col-md-12">
<h2>Login Form</h2>

<form action="StudentController?op=login" method="post">


<center>
<div class="container" style="width:500px;">
<img src="https://www.w3schools.com/howto/img_avatar2.png"
style="width:200px;height: 200px;" alt="Avatar" class="avatar">
<br/><br/>
<select name="role" class="form-control dropdown-item">
<option value="admin">Admin </option>
<option value="student">Student</option>
</select>
<span style="color:red;font-size: 16px; font-family: corbel"> ${param.msg} </span>
<br/>
<input type="text" placeholder="Enter Username" name="userid"
value="<%=userid%>" required>
<br/>
<input type="password" placeholder="Enter Password" name="password"
value="<%=password%>" required>

<button type="submit">Login</button>
<label>
<input type="checkbox" name="remember" value="remember"> Remember me
</label>
</div>
</center>
</form>

</div>
</div>
</div>

</body>
</html>

StudentController :



protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
StudentDao sd = new StudentDao();

String op = request.getParameter("op");
if (op != null && op.equals("login")) {
String userid = request.getParameter("userid");
String password = request.getParameter("password");

String role = request.getParameter("role");


if (role != null && role.equals("admin")) {
AdminDao ad = new AdminDao();
Admin admin = ad.findByLoginDetails(userid, password);
if (admin == null) {
response.sendRedirect("login.jsp?msg=Sorry! Invalid Userid or Password ");
} else {
HttpSession session = request.getSession();
session.setAttribute("admin", admin);
//cookie:
String remember = request.getParameter("remember");
if (remember != null) {
Cookie cookie1 = new Cookie("uid", userid);
Cookie cookie2 = new Cookie("pwd", password);
cookie1.setMaxAge(60 * 60*24*2);
cookie2.setMaxAge(60 * 60*24*2);
response.addCookie(cookie1);
response.addCookie(cookie2);
}

response.sendRedirect("admin/dashboard.jsp");
}
}
if (role != null && role.equals("student")) {
Student student = sd.findByLoginDetail(userid, password);
if (student == null) {
response.sendRedirect("login.jsp?msg=Sorry! Invalid Userid or Password ");
} else {
HttpSession session = request.getSession();
session.setAttribute("student", student);
//cookie:
String remember = request.getParameter("remember");
if (remember != null) {
Cookie cookie1 = new Cookie("uid", userid);
Cookie cookie2 = new Cookie("pwd", password);
cookie1.setMaxAge(60 * 60);
cookie2.setMaxAge(60 * 60);
response.addCookie(cookie1);
response.addCookie(cookie2);
}

response.sendRedirect("student/dashboard.jsp");
}
}
}


….

Make the Design of Admin Dashboard yourself or See the Recorded class video.

You might also like