Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

ENTERPRISE PROGRAMMING - 17CS3116R

TEST-2 KEY & SCHEMA

Part-A (4X 3M=12M)


Answer ALL Questions
Q. No. 1, 2 from CO3 with BTL 1,2
Q. No 3, 4 from CO4 with BTL 1,2
1. Jakir Hussain wants to provide mapping between Department POJO and Department table in
the database using hibernate. so please help him to write proper hibernate mapping xml file.
Sol:-
Scheme:
Proper syntax for tags and attributes -- 1
Mapping file -- 2
<hibernate-mapping>
<class name="com.klu.Department" table="Department">
<id name="deptId" column="DID">
<generator class="assigned"></generator>
</id>
<property name="dname" column="DNAME"></property>
<property name="university" column="UNIVERSITY"></property>
</class>
</hibernate-mapping>
2. Configure Employee bean in applicationContext.xml using setter injection with the following
properties empId,empName,empDesig and empSal.
Sol:-
Scheme:
Proper syntax for tags and attributes -- 1
Spring configuration file -- 2
<beans>
<bean id="address" class="com.klef.Address">
<property name="street" value="OneTown"></property>
<property name="city" value="VJA"></property>
<property name="state" value="AMARAVATHI"></property>
</bean>
<bean id="stud" class="com.klef.Student">
<property name="sid" value="1001"></property>
<property name="sname" value="Raja"></property>
<property name="fees" value="100000"></property>
<property name="addr" ref="address"></property>
</bean> </beans>
3. The following form contains Student details. create cookies for the form fields after capturing
from the form and add those cookies to the response using jsp.
Student Form
Student ID : (studId)
Student Name: (studName)
Student Course: (studCourse)
Student Fees : (studFees)
SUBMIT

Solution:-
Scheme:
Data capturing from Form --- 1
Creating cookies and adding to the response --- 2
<%
String id = request.getParameter("studId");
String name = request.getParameter("studName");
String course = request.getParameter("studCourse");
String fees = request.getParameter("studFees");
Cookie c1 = new Cookie("cid",id);
Cookie c2 = new Cookie("cname",name);
Cookie c3 = new Cookie("ccourse",course);
Cookie c4 = new Cookie("cfees",fees);
response.addCookie(c1);
response.addCookie(c2);
response.addCookie(c3);
response.addCookie(c4);
%>
4. A Bank Customer wants to try Inheritance through Table per class Hierarchy so he created a
base class named Payment, containing attributes like paymentId, amount and two derived
classes namely CreditCard consisting type of CreditCard they used and Cheque containing type
of cheque. So, when the object of derived class is saved, object of base class will also get
stored in the database in a single table. To know the Object of which class is stored we must
use the Discriminator column. So help him to write hibernate mapping xml file for the above
inheritance mapping by applying the Concept of Table per Class Hierarchy.
Solution:-
Scheme:
Proper syntax for tags and attributes -- 1
Spring configuration file -- 2

<hibernate-mapping>
<class name="com.klef.Payment" table="PAYMENT">
<id name="paymentId" column="pid"></id>
<discriminator column="type" length="10"></discriminator>
<property name="amount" column="amount"></property>

<subclass name="com.klef.CreditCard" discriminator-value="CC">


<property name="cardType" column="CARDTYPE"></property>
</subclass>

<subclass name="com.klef.Cheque" discriminator-value="CQ">


<property name="chequeType" column="CHEQUETYPE"></property>
</subclass>
</class>
</hibernate-mapping>
Part-B (4 X 5M=20M)
Answer ALL Questions
Q. No. 5, 6 from CO3 with BTL 3
Q. No 7, 8 from CO4with BTL 3
5. Mr. Robert Hiezman is a Manager at Company and he wants to hire different types of
employees like regular employee and contract employees. Regular employees will get
salary, bonus and contract employees will get amount they earn per hour and time
duration they work. So create a super class where it gets and sets the values like
name and Id of employee and two sub classes like RegularEmployee and
ContractEmployee. Use Concept of Table per Concrete Class Hierarchy to insert data into
DB using Hibernate Frame Work
Solution:-
Sheme:
For Pojo classes ---- 2
For Mapping file ----- 1
For Inserting Data ----- 2
Solution:-
Employee.java:
public class Employee {
private int id;
private String name;

//getters and setters


}

Regular_Employee.java:-
Public class Regular_Employee extends Employee{
Private double salary;
Private double bonus;
//setters and getters
}
Contract_Employee.java:
Public class Contract_Employee extends Employee{
Private double pay_per_hour;
Private String contract_duration;
//setters and getters
}
Employee.hbm.xml:-
<hibernate-mapping>
<class name="com.klu.Employee" table="emp">
<id name="id">
<generator class="increment"></generator>
</id>

<property name="name"></property>

<union-subclass name="com.klu.Regular_Employee" table="regemp">


<property name="salary"></property>
<property name="bonus"></property>
</union-subclass>

<union-subclass name="com.klu.Contract_Employee" table="contemp">


<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>

</class>

</hibernate-mapping>
TestInsert.java:
-------------------
Class TestInsert{
Public static void main(String args[]){
Configuration c = new Configuration();
c.configure("hibernate.cfg.xml");
SessionFactory factory=
Session session=c.openSession();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.save(e1);
session.save(e2);
session.save(e3);

t.commit();
session.close();
System.out.println("success");
6. Develop a Hibernate application to perform all CRUD operations on Product table in the
database.
Solution:-
Sheme:
--> For Mapping file --- 1
--> For Pojo class --- 1
--> For all crud operations ---- 3
Product.java:
public class Product
{
int product_id;
String product_name;
Double product_price;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public Double getProduct_price() {
return product_price;
}
public void setProduct_price(Double product_price) {
this.product_price = product_price;
}
}
Product.hbm.xml:
<hibernate-mapping>
<class name="Product" table="product">

<id name="product_id" column="product_id" >


<generator class="assigned" />
</id>

<property name="product_name" column="product_name" />


<property name="product_price"/>

</class>
</hibernate-mapping>
HibernateCrudOperations.java:
------------------------------------------
Public class HibernateCrudOperations{
Public static void main(String args[]){
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");

SessionFactory factory = cfg.buildSessionFactory();


Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Product p=new Product();

p.setProduct_id(100);
p.setProduct_name("ABC");
p.setProduct_price(100.00);
session.save(p);
tx.commit();
System.out.println("insert success"); Session.close();
Object o=session.load(Product.class,new Integer(100));
Product s=(Product)o;
s.setProduct_price(200.00); // implicitly update method will be called..

tx.commit();
System.out.println("Object Updated successfully.....!!"); Session.close();
Object o=session.load(Product.class,new Integer(100));
Product s1=(Product)o;
Session.delete(s1);
Tx.commit();
System.out.println("Object deleted"); Session.close();
Object o=session.load(Product.class,new Integer(100));
Product s2=(Product)o;

System.out.println("Loaded object product id is___"+s2.getProduct_id());


System.out.println("Loaded object product name
is___"+s2.getProduct_name());
System.out.println("Loaded object product price
is___"+s2.getProduct_price());

System.out.println("Object Loaded successfully.....!!");


Session.close();
Sf.close();
}
}
7. Implement the spring IOC application using setter injection with primitive and string based
values
Solution:
Scheme:
--> For Bean class Definition --- 1
--> For Bean configuration in xml -- 2
--> For Test the bean object -- 2
Student.java:
package com.klef;
public class Student {
//vars
private int sid;
private String sname;
private double fees;
//setters and getters
}
ApplicationContext.xml:
-------------------------------
<beans>
<bean id="stud" class="com.klef.Student">
<property name="sid" value="1001"></property>
<property name="sname" value="Raja"></property>
<property name="fees" value="100000"></property>
</bean>
</beans>
TestClient.java:
---------------------
package com.klef;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class TestClient {


public static void main(String[] args) {
Resource res = new ClassPathResource("applicationContext.xml");
BeanFactory f = new XmlBeanFactory(res);
Student s = (Student)f.getBean("stud");

System.out.println("Student ID:" + s.getSid());


System.out.println("Student Name:" + s.getSname());
System.out.println("Student Fees:" + s.getFees());
}
}
8. The Navodaya Johar school is wanting to direct a get-together of their 2014-2015 batch
students. To design this occasion and oversee, principal appointed a student from a similar
batch. To do this the student needed to make hibernate application with spring application. He
initially made a table in database to store the subtleties of his companions who are going to
the gathering. He made the table with the name Reunion with properties ID No, Name,
Contact Number, Amount paid, and Status. ID.NO being the primary key has the most
extreme size of 4 digits and Status speaks to how much sum has been paid i.e..; completely
paid, or partially paid, or not paid. Note that the sum should be paid to go to the gathering is
2000 rupees. Now he needs to make a java project with springs and hibernate integration.
Help him in Creating POJO class and Hibernate mapping xml file DAO class for inserting,
delete, update and retrieving subtleties in/from database.
Solution:
Scheme:
--> Pojo class and DAO --- 1
--> TestClient --- 2
--> Spring Configuration file --- 2
Reunion.java:-
-------------------
public class Reunion{
//vars
private int id;
private String name;
private int contactNo;
private double amountPaid;
private boolean status;
//setters and getters
}
ReunionDAO.java:
-------------------------
import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class ReunionDAO {


//vars
HibernateTemplate template;
public HibernateTemplate getTemplate() {
return template;
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void insertRecord(Reunion e) {
template.save(e);
}
public void deleteRecord(Reunion e) {
template.delete(e);
}
public List<Reunion> loadAllRecords(){
ArrayList<Reunion> list = new ArrayList<Reunion>();
list = (ArrayList<Reunion>)template.loadAll(Reunion.class);
return list;
}
public Employee loadSpecificRecord(int id) {
Reunion e = null;
e = (Reunion)template.load(Reunion.class, id);
return e;
}
public void updateRecord(Reunion e) {
template.update(e);
}
}
applicationContext.xml:
--------------------------------
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="tiger"></property>
</bean>

<bean id="mysessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>

<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="ht" class="org.springframework.orm.hibernate3.HibernateTemplate">


<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="studDao" class="com.klef.ReunionDAO">
<property name="template" ref="ht"></property>
</bean>
</beans>
ClientTest.java:
--------------------
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class ClientTest {


public static void main(String args[]) {
BeanFactory f = new XmlBeanFactory(new
ClassPathResource("applicationContext.xml"));
ReunionDAO dao = (ReunionDAO)f.getBean("studDao");

Reunion e = new Reunion();


e.setId(1004);
e.setName("Ramya krishna");
e.setContanctNo(234323452);
e.setAmountPaid(10000);
e.setStatus(true);

dao.insertRecord(e);
*/
System.out.println("Specific Student Details:");
Employee x = dao.loadSpecificEmployee(1004);
System.out.println("Id:" + x.getId());
System.out.println("Name:" + x.getName());
System.out.println("Contact No:" + x.getContactNo());
System.out.println("Amount Paid:" + x.getAmountPaid());
System.out.println("status:" + x.getStatus());

System.out.println("List of all Record:");


for(Reunion x:list) {
System.out.println("Id:" + x.getId());
System.out.println("Name:" + x.getName());
System.out.println("Contact No:" + x.getContactNo());
System.out.println("Amount Paid:" + x.getAmountPaid());
System.out.println("status:" + x.getStatus());
}
Dao.deleteRecord(e);
}
}

Part-C (2 X 9M=18M)
Answer ALL Questions
Q. No. 9,10 from CO3 with BTL 3
Q. No. 11,12 from CO4 with BTL 3
9. Consider you have a base class(super) named Payment and 2 derived classes(sub
classes) like CreditCard and Check. If you store any sub class object into database, then
automatically it's super class object data also stored in the database. But all the data
will be stored in single table which is super class table. So please develop the Hibernate
application based on the above details.
Solution:

Scheme:

POJO Classes (Base Class – Payment, Derived Classes – CreditCard & Check) –
2M
Mapping file – 3M
Configuration file – 2M
Java Main Class to Save Objects – 2M

Payment.java
public class Payment
{

private int paymentId;

private double amount;


public int getPaymentId() {
return paymentId;
}
public void setPaymentId(int paymentId) {
this.paymentId = paymentId;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
CreditCard.java

public class CreditCard extends Payment


{

private int cardNumber;

private String cardType;


public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}

}
DebitCard.java
public class DebitCard extends Payment
{

private int pinNumber;


private String cardName;
public int getPinNumber() {
return pinNumber;
}
public void setPinNumber(int pinNumber) {
this.pinNumber = pinNumber;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
}
payment.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>


<hibernate-mapping>
<class name="Payment" table=" payment" >
<id name="paymentId" column="pid">
"generator class="increment"/>
</id>
<property name="amount" column="amount"/>
<joined-subclass name="CreditCard" table="creditcard">
<key column="paymentId"/>;
<property name="cardNumber" column="creditNumber"/>
<property name="cardType" column="creditType"/>
</joined-subclass>
<joined-subclass name="DebitCard" table="debitcard">
<key column="paymentId"/>
<property name="pinNumber"/>
<property name="cardName"/>
</joined-subclass>
</class>

</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class"<oracle.jdbc.driver.OracleDriver</property>
<mapping resource="payment.hbm.xml"/>
</session-factory"
</hibernate-configuration>
Client.java
import org.hibernate.*;
import org.hibernate.cfg.*;
public class Client
{
public static void main(String args[])
{
SessionFactory factory=new Configuration().configure().buildSessionFactory();
Session session=factory.openSession();
Payment payment=new Payment();
payment.setPaymentId(5);
payment.setAmount(30000);
CreditCard creditcard=new CreditCard();
creditcard.setCardNumber(45);
creditcard.setCardType("visa");
DebitCard debitcard=new DebitCard();
debitcard.setPinNumber(6432);
debitcard.setCardName("ANDHRA BANK");
Transaction transaction=session.beginTransaction();
session.save(payment);
session.save(creditcard);
session.save(debitcard);
transaction.commit();
session.close();
System.out.println("Payment details all are inserted using Table Per Subclass");
}

}
(Or)
10. Develop a web application to store Employee details of small scale industry using MVC
design pattern with the following details:
 create an employee form with required fields
 create a controller jsp to use Model component
 create a Model component
 create a view component which will generate result to the client.
Solution:

Index.html – 1M
Java Bean (Employee) – 2M
Controller (Servlet) – 3M
View (JSP) – 3M

index.html
<html>
<head>
<title>MVC Demo</title>
</head>
<body>
<form method="post" action="empdetails">
<table align="center" style="height:150px">
<tr>
<td><b>Enter Employee ID</b></td>
<td><input type="number" name="id" placeholder="Enter Emp ID" required></td>
</tr>
<tr>
<td><b>Enter Employee Name</b></td>
<td><input type="text" name="name" placeholder="Enter Emp Name" required></td>
</tr>
<tr>
<td><b>Select Gender</b></td>
<td>Male<input type="radio" name="gender" value="male"
required>&nbsp;&nbsp;Female<input type="radio" name="gender" value="female"
required></td>
</tr>
<tr>
<td align="center"><input type="submit" value="Submit"></td>
<td align="center"><input type="reset" value="Clear"></td>
</tr>
</table>
</form>
</body>
</html>
Employee.java:

Package Demo;
Public class Employee
{
Private int id;
Private String name;
Private String gender;

//Getter & Setter Methods Here

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app>
<servlet>
<servlet-name>GetEmpDetails</servlet-name>
<servlet-class>GetEmpDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetEmpDetails</servlet-name>
<url-pattern>/empdetails</url-pattern>
</servlet-mapping>
</web-app

GetEmpDetails.java

Import Demo.Employee
Import javax.servlet.http.*;
Public class GetEmpDetails extends HttpServlet
{
Public void service(HttpServletRequest req,HttpServletResponse res) throws Exception
{
Int id = Integer.parseInt(req.getParameter(“id”));
String name = req.getParameter(“name”);
String gender = req.getParameter(“gender”);

Employee emp = new Employee();


emp.setId(id);
emp.setName(name);
emp.setGender(gender);
req.setAttribute(“empbean”,emp);
RequestDispatcher rd = req.getRequestDispatcher(“ViewEmpDetails.jsp”);
rd.forward(req,res)
}
}

ViewEmpDetails.jsp

<%@page import="Demo.Employee"%>

<%
Employee myempbean = (Employee)
request.getAttribute("empbean");

out.println(myempbean.getId());
out.println("<br>");
out.println(myempbean.getName());
out.println("<br>");
out.println(myempbean.getGender());
%>
11. Gowtham is developing an application for one of the educational organization. He is
using Hibernate framework to retrieve student data of that organization. So please help
him to develop that application to fetch(retrieving) data and supporting xml files.

POJO Class – 2M
Mapping File – 2M
Configuration File – 3M
Display Records – 2M

Employee.java (POJO Class)

public class Student

{
private int id;
private String name;
private String dept;
//getter and setter methods here
}
Employee.hbm.xml (Mapping File)

<?xml version="1.0" encoding="UTF-8"?>


<hibernate-mapping>
<class name="Student" table="student">
<id name="id"></id>
<property name="name"></property>
<property name="dept"></property>
</class>
</hibernate-mapping>

hibernate.cfg.xml (Configuration File)

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.user">system</property>
<property name="connection.password">admin</property>

<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hbm2ddl.auto">create</property>

<mapping resource="Student.hbm.xml"></mapping>

</session-factory>
</hibernate-configuration>
ViewRecord.java

import org.hibernate.*;

import org.hibernate.cfg.*;

public class ViewRecord


{
public static void main(String args[])
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Object obj = session.load(Employee.class, new Integer(101));
Student s = (Student)obj;
System.out.println(s.getId()+","+s.getName()+","+s.getDept());
Transaction txt = session.beginTransaction();
txt.commit();
session.close();
sf.close();
}
}

(Or)
12. A professor wants to test his student whether he knows about a concept called Spring setter
injection with List Collection by giving following details.
 Create a spring Bean which is having a dependency called List type.
 Configure the spring bean with list of students in spring configuration file
 write the client program to access the spring bean

POJO Class – 2M
Configuration File – 4M
Client Program – 3M

Solution:
-----------
Student.java
import java.util.*;
public class Student
{
private int id;
private String name;
private int age;
private List<String> skills;
public Student(int id,String name,int age,List<String> skills)
{
this.id=id;
this.name=name;
this.age=age;
this.skills=skills;
}
public void display()
{
System.out.println("***Student Details");
System.out.println("ID:"+id);
System.out.println("Name:"+name);
System.out.println("Age:"+age);
System.out.println("***Skills***");
for( String skill : skills)
{
System.out.println(skill);
}
}
}
applicationConext.xml
<beans>
<bean id="studentbean" class="Student">
<constructor-arg value="100"/>
<constructor-arg value="RAM"/>
<constructor-arg value="20"/>
<constructor-arg>
<list>
<value>C</value>
<value>CPP</value>
<value>JAVA</value>
</list>
</constructor-arg>
</bean>
</beans>

ClientController.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class ClientController
{
public static void main(String args[])
{

ApplicationContext applicationContext = new


FileSystemXmlApplicationContext("src/applicationContext.xml");
Studentstudent = (Student) applicationContext.getBean("studentbean");
student.display();
}
}

You might also like