0% found this document useful (0 votes)
19 views19 pages

AJ (MCA 2nd) 2

Struts is an open-source web application framework by Apache that utilizes the MVC architecture to separate business logic from presentation logic, making it easier to develop large-scale J2EE applications. It features a composite view for layout management, custom tag libraries, and supports input validation and internationalization. The document outlines the framework's implementation steps, including configuration, JSP creation, form beans, DAO classes, and action classes for user registration with database connectivity.

Uploaded by

Anu Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views19 pages

AJ (MCA 2nd) 2

Struts is an open-source web application framework by Apache that utilizes the MVC architecture to separate business logic from presentation logic, making it easier to develop large-scale J2EE applications. It features a composite view for layout management, custom tag libraries, and supports input validation and internationalization. The document outlines the framework's implementation steps, including configuration, JSP creation, form beans, DAO classes, and action classes for user registration with database connectivity.

Uploaded by

Anu Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

STRUTS: Struts is an open-source web application framework developed by Apache Software

Foundation, it is used to create a web application based on servlet and JSP. It depends on the MVC
(Model View Controller) framework. Struts are thoroughly useful in building J2EE (Java 2 Platform,
Enterprise Edition) applications because struts take advantage of J2EE design patterns. Struts follows
these J2EE design patterns including MVC and JSP custom tag libraries. In struts, the composite view
manages the layout of its sub-views and can implement a template, making persistent look and feel
easier to achieve and customize across the entire application. A composite view is made up by using
other reusable sub-views such that a small change that happens in a sub-view is automatically
updated in every composite view. Struts consist of a set of custom tag libraries. Struts also support
utility classes.
The main purpose of the struts framework is to provision separation of concerns between the business
logic and the presentation logic (view), making it easier to manage and develop large-scale web
applications.
Features of Struts
Struts have the following features:
 Struts encourages good design practices and modeling because the framework is designed
with “time-proven” design patterns.
 Struts is almost simple, so easy to learn and use.
 It supports many convenient features such as input validation and internationalization.
 It takes much of the complexity out as instead of building your own MVC framework, you
can use struts.
 Struts is very well integrated with J2EE.
 Struts has large user community.
 It is flexible and extensible; it is easy for the existing web applications to adapt the struts
framework.
 Struts provide good tag libraries.
 It allows capturing input form data into JavaBean objects called Action forms.
 It also hands over standard error handling both programmatically and declaratively.
Working of Struts:

Step-by-Step Implementation of Struts


Step 1: Initialization Phase
 In initial phase, the controller rectifies a configuration file.
 This configuration file is like the manual for initialization and is used to deploy the controller
layer objects.
Step 2: Composition of Configuration file
 Config file’s core is formed by all the objects defined inside it.
 These objects include action mapping which plays in defining the behavior of application.
 Furthermore, it also contains the definition of these action mappings.
 Action mappings are the key aspects in instructing the servlet controllers for handling the
HTTP Requests.
Step 3: Routing of HTTP Requests & process flow
 Initially, the requests are directed towards the action and then JSP.
 JSP does further processing and rendering the view page.
Step 4: Action object request handling
 Action objects handle all the requests of client.
 These objects have access to the servlet controller of our application, and they can execute
specific actions defined inside controllers.
The action object can indirectly forward one or more shared objects, these shared objects can be
JavaBeans, and are typically shared in shared context which is established using Java Servlets.

Basic Architecture of MVC: Model View Controller or MVC as it is popularly called, is a software
design pattern for developing web applications. A Model View Controller pattern is made up of the
following three parts −
 Model − The lowest level of the pattern which is responsible for maintaining data.
 View − This is responsible for displaying all or a portion of the data to the user.
 Controller − Software Code that controls the interactions between the Model and View.
MVC is popular as it isolates the application logic from the user interface layer and supports
separation of concerns. Here the Controller receives all requests for the application and then works
with the Model to prepare any data needed by the View. The View then uses the data prepared by the
Controller to generate a final presentable response. The MVC abstraction can be graphically
represented as follows.

The Model
The model is responsible for managing the data of the application. It responds to the request from the
view and it also responds to instructions from the controller to update itself.
The View
It means presentation of data in a particular format, triggered by a controller's decision to present the
data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with
AJAX technology.

The Controller
The controller is responsible for responding to the user input and perform interactions on the data
model objects. The controller receives the input, it validates the input and then performs the business
operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC
methodology within Struts2.

Deploying the application in struts with database connectivity:


Step 1 : Create table USER_DETAILS in MYSQL
create table USER_DETAILS
(FIRST_NAME varchar(50),
LAST_NAME varchar(50),
USER_NAME varchar(50),
PASSWORD varchar(50),
EMAIL varchar(50),
PHONE varchar(15));

Step 2 : Create Dynamic Web Project


Open Eclipse and click on File -> New -> Project and select Dynamic Web Project in the New
Project wizard screen as shown below.

After selecting Dynamic Web Project, press Next, in next screen provide the name of the project.
Enter the name of the project as StrutsDBExample and click on Finish as shown below.
Step 3 : Add jar files to the classpath of Project
Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder.Following jar files
should be added to the project build path for successful deployment of struts project :

Copy all the tld files to WEB-INF folder and make the entry of these tld files in web.xml file.
Now we have to configure ActionServlet of struts with web.xml.The first page that will be called in
the login application is the login.jsp page. This configuration should be done
in web.xml as <welcome-file-list> .
Following xml shows how to configure struts in web.xml.
web.xml

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"


"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>

<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

<taglib>
<taglib-uri>/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>

</web-app>

Step 4 : Create JSPs for UI of the application :


login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-html" prefix="html" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
</head>
<body bgcolor="silver">
<br></br>
<body>
<html:html>
<div style="color:red">
<html:errors />
</div>
<html:form action="/register" method="get">

Enter your First Name:


<html:text property="firstName" size="50" /><br><br>
Enter your Last Name:
<html:text property="lastName" size="50" /><br><br>
Enter your username:
<html:text property="userName" size="50" /><br><br>
Enter your password:
<html:text property="password" size="30" /><br><br>
Enter your Email:
<html:text property="email" size="30" /><br><br>
Enter your Phone No:
<html:text property="phone" size="15" /><br><br>
<html:submit>Submit</html:submit>
<br><br>
</html:form>
</html:html>
</body>
</html>
In login.jsp, We used Struts HTML Tags to create login page. The form has six text field to get the
user details. The form has one submit button,when this button is clicked it will call register action.
success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success page</title>
</head>
<body bgcolor="silver">
<table><tr>
sucessfully added</tr><br><br>
<%=session.getAttribute("firstName") %><br><br>
<%=session.getAttribute("lastName") %><br><br>
<%=session.getAttribute("userName") %><br><br>
<%=session.getAttribute("email") %><br><br>
<%=session.getAttribute("phone") %><br><br>
</table>
</body>
</html>
User will navigate to success.jsp page after successful registration.
Step 5 : Create Form Beans :
Create a package com.jwt.struts.form and in that package create a java class UserRegisterForm and
copy following code into this class.
UserRegisterForm.java
package com.jwt.struts.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class UserRegisterForm extends ActionForm {

private static final long serialVersionUID = 1L;


private String firstName;
private String lastName;
private String userName;
private String password;
private String email;
private String phone;

public ActionErrors validate(ActionMapping mapping,


HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (firstName == null || firstName.length() < 1) {
errors.add("firstName", new ActionMessage(
"error.firstName.required"));

}
if (lastName == null || lastName.length() < 1) {
errors.add("lastName", new ActionMessage("error.lastName.required"));

}
if (userName == null || userName.length() < 1) {
errors.add("userName", new ActionMessage("error.userName.required"));

}
if (password == null || password.length() < 1) {
errors.add("password", new ActionMessage("error.password.required"));

}
if (email == null || email.length() < 1) {
errors.add("email", new ActionMessage("error.email.required"));

}
if (phone == null || phone.length() < 1) {
errors.add("phone", new ActionMessage("error.phone.required"));

}
return errors;
}

public String getUserName() {


return userName;
}

public void setUserName(String userName) {


this.userName = userName;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getPhone() {


return phone;
}

public void setPhone(String phone) {


this.phone = phone;
}

}
Inside the validate method, we will check whether all field is entered, If not the corresponding error
message is displayed to the user. The error messages are configured in
the ApplicationResource.properties file.
The validate method in the LoginForm class is called when the Form is submitted. If any errors are
found then the control is returned back to the input page where the errors are displayed to the user.
The input page is configured in the action tag of struts-configuration file. <html:errors/> tag is used to
display the errors in the jsp page.

Step 6 : Create DAO Class :


Create a package com.jwt.struts.dao and in that package create a java class UserRegisterDAO and
copy following code into this class. This is a simple database access class.In this class we have
defined one business method insertData() which will insert user details into database.
This class gets information from the object of UserRegisterAction class and stores these information
into USER_DETAILS table.
UserRegisterDao.java

package com.jwt.struts.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UserRegisterDAO {


public void insertData(String firstName, String lastName, String userName,
String password, String email, String phone) throws Exception {
System.out.println("jdbc connection");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/strutsdb", "root", "mukesh");

try {

try {
Statement st = con.createStatement();
int value = st
.executeUpdate("INSERT INTO
USER_DETAILS(FIRST_NAME,LAST_NAME,USER_NAME,PASSWORD,EMAIL,PHONE) "
+ "VALUES('"
+ firstName
+ "','"
+ lastName
+ "','"
+ userName
+ "','"
+ password
+ "','"
+ email + "','" + phone + "')");
System.out.println("1 row affected" + value);
} catch (SQLException ex) {
System.out.println("SQL statement is not executed!" + ex);
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 7 : Create Action Class :


Create a package com.jwt.struts.action and in this package create a java class UserRegisterAction and
copy following code into this class
UserRegisterAction.java

package com.jwt.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jwt.struts.dao.UserRegisterDAO;
import com.jwt.struts.form.UserRegisterForm;

public class UserRegisterAction extends Action {


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession ses = request.getSession(true);

UserRegisterForm registerForm = (UserRegisterForm) form;


String firstName = registerForm.getFirstName();
String lastName = registerForm.getLastName();
String userName = registerForm.getUserName();
String password = registerForm.getPassword();
String email = registerForm.getEmail();
String phone = registerForm.getPhone();
UserRegisterDAO dao = new UserRegisterDAO();
dao.insertData(firstName, lastName, userName, password, email, phone);
ses.setAttribute("firstName", firstName);
ses.setAttribute("lastName", lastName);
ses.setAttribute("userName", userName);
ses.setAttribute("email", email);
ses.setAttribute("phone", phone);
if (firstName.equals("") || lastName.equals("") || userName.equals("")
|| password.equals("") || email.equals("") || phone.equals("")) {
return mapping.findForward("error");
}
return mapping.findForward("success");

}
}
The execute() method contains the business logic of the application. Here first we typecast
the ActionForm object to UserRegisterForm, so that we can access the form variables using the getter
and setter methods. If all fields are saved to database then we forward the user to the success.jsp page.
These configuration has been done in struts-config.xml file which is given below.
Step 8 : Create struts-config.xml file :
Create struts-config.xml file inside WEB-INF folder of the project.
struts-config.xml

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

<!DOCTYPE struts-config PUBLIC


"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
<form-beans>
<form-bean name="registerForm" type="com.jwt.struts.form.UserRegisterForm" />
</form-beans>

<action-mappings>
<action input="/login.jsp" name="registerForm" path="/register"
type="com.jwt.struts.action.UserRegisterAction">
<forward name="success" path="/success.jsp" />
</action>
</action-mappings>

<message-resources parameter="com/jwt/struts/action/ApplicationResource" />

</struts-config>

Step 9 : Create properties file :


The ApplicationResource.properties file contains the error messages. The key
"error.userName.required" is used in the validate function to add a new error. Since the error
messages are configured in a separate properties file they can be changed any time without making
any changes to the java files or the jsp pages.So no need to restart server if we are changing any
values to these keys.
ApplicationResource.properties
error.userName.required = User Name is required.
error.password.required = Password is required.
error.firstName.required = First Name is Required.
error.lastName.required = Last Name is Required.
error.email.required = email is Required.
error.phone.required = Phone is Required.

Hibernate: Hibernate is the most used Object/Relational persistence and query service and It is
licensed under the open-source GNU Lesser General Public License (LGPL). Hibernate not only see
the mapping from Java classes to database tables but also provides data query and recovery facilities.
Hibernate is free to download.
This Hibernate Tutorial is tailored for both beginners and experienced professionals, It helps you to
use Hibernate to create database-based web applications in simple and easy steps and learn
fundamental and advanced concepts of Hibernate including setting up Hibernate, mapping Java
classes to database tables, performing basic and advanced database operations, utilizing Hibernate
Query Language (HQL), and more.

Hibernate Framework: Hibernate is a Java framework, licensed under the open-source GNU Lesser
General Public License (LGPL), and is available for free download. Developed in 2001 by Gavin
King, Hibernate was introduced as a groundbreaking alternative to the EJB2-style entity bean
approach. By mapping Java objects to database tables, it streamlines data persistence and retrieval
without the need for complex SQL queries. With features like automatic transaction management and
caching, Hibernate simplifies and optimizes database interactions, making it an indispensable
framework for efficient data management in Java applications.
JDBC
JDBC (Java Database Connectivity) provides a set of Java APIs to access the relational databases
from the Java program. Java APIs enable programs to execute SQL statements and interact with any
SQL database.
JDBC gives a flexible architecture to write a database-independent web application that can execute
on different platforms and interact with different DBMS without any change.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access and It is a programming
technique that maps the object to the data stored in the database.

ORM Tool
The ORM tool internally uses the JDBC API to interact with the database.
JPA
 Java Persistence API (JPA) is a Java specification that provides specific functionality and is a
standard for ORM tools.
 javax.persistence package contains the JPA classes and interfaces.

CREATING POJO FILES: POJO, short for Plain Old Java Object, is a standard Java object
with minimal restrictions imposed by the Java Language Specification. It operates without
requiring any specific classpath. These objects serve as intermediaries for communication
between different layers or components within distributed systems, encapsulating data and
related behavior. Typically, POJOs feature private member variables alongside public getter
and setter methods, with additional methods for data manipulation if needed.
Example
// Student POJO class to represent entity Student
public class Student
{
// default field
String name;

// public field
public String id;

// private field
private double score;

//arg-constructor to initialize fields


public Student(String name, String id, double score)
{
this.name = name;
this.id = id;
this.score = score;
}

// getter method for name


public String getName()
{
return name;
}

// getter method for id


public String getId()
{
return id;
}

// getter method for score


public double getScore()
{
return score;
}
}

Explanation of the example:


In the above example, we can observe that there are no restrictions on the access modifiers for
the fields; they could be declared as public, private, or protected. Also, it is not mandatory to
include any constructor in it. Thus, we can observe that the above example is a classic case of
the POJO class in Java.
Properties of POJO
The following are some essential properties of the POJO class in Java:
 The POJO class in Java should always be public.
 The POJO class in Java should always have a public default constructor.
 The POJO class in Java may contain the arguments constructor.
 The objects of the POJO class in Java should contain public Getters and Setters so that other
Java programs can access object values.
 The access modifiers for the objects in the POJO class of java could be public, private,
or protected.
 The instance variables for the objects in the POJO class of Java should be private for better
security.
 The POJO class in Java must not extend predefined classes.
 The POJO class in Java must not implement prespecified interfaces.
 The POJO class in Java must not have any prespecified annotation.
Working of the POJO Class
The POJO class in Java is an object class. It encapsulates the Business logic. Upon viewing in
a Model View Controller architecture, the controller would interact with the business logic,
which would contact the POJO class in Java to access the data. Business logic refers to the
overall set of rules determining how the data will be stored or manipulated in a business or
application domain.
Below is the pictorial representation of the working of the POJO class in Java:

In the above example, the database entity represents the POJO, i.e. the POJO class has the
same members as the database entity.
Using POJO Class in Java Program
To use a POJO class in a Java program, you need to follow the below steps:
 Create a POJO class: Define a POJO class with private fields, public getters, and setters.
 Instantiate the POJO class: Create an object of the POJO class using the new operator.
 Set values: Set the values of the POJO class fields using the setter methods.
 Get values: Retrieve the values of the POJO class fields using the getter methods.
Here is an example of how to use a POJO class in a Java program:
// Define a POJO class named "Person"
public class Person {
private String name;
private int age;

public Person() {
// Default constructor
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
// Use the POJO class in a Java program
public class Main {
public static void main(String[] args) {
// Create a Person object
Person person = new Person();

// Set the values of the Person object


person.setName("Jack");
person.setAge(30);

// Get the values of the Person object


System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Hibernate Lifecycle: Hibernate Lifecycle or in other words, we can say that we will learn
about the lifecycle of the mapped instances of the entity/object classes in hibernate. In
Hibernate, we can either create a new object of an entity and store it into the database, or we
can fetch the existing data of an entity from the database. These entity is connected with the
lifecycle and each object of entity passes through the various stages of the lifecycle.
There are mainly four states of the Hibernate Lifecycle :
1. Transient State
2. Persistent State
3. Detached State
4. Removed State

Hibernate Lifecycle
As depicted from the above media one can co-relate how they are plotted in order to plot
better in our mind. Now we will be discussing the states to better interpret hibernate lifecycle.
It is as follows:
State 1: Transient State
The transient state is the first state of an entity object. When we instantiate an object of
a POJO class using the new operator then the object is in the transient state. This object is not
connected with any hibernate session. As it is not connected to any Hibernate Session, So this
state is not connected to any database table. So, if we make any changes in the data of the
POJO Class then the database table is not altered. Transient objects are independent of
Hibernate, and they exist in the heap memory.

Changing new object to Transient State


There are two layouts in which transient state will occur as follows:
1. When objects are generated by an application but are not connected to any session.
2. The objects are generated by a closed session.
Here, we are creating a new object for the Employee class. Below is the code which shows the
initialization of the Employee object :
//Here, The object arrives in the transient state.
Employee e = new Employee();
e.setId(21);
e.setFirstName("Neha");
e.setMiddleName("Shri");
e.setLastName("Rudra");
State 2: Persistent State
Once the object is connected with the Hibernate Session then the object moves into the
Persistent State. So, there are two ways to convert the Transient State to the Persistent State :
1. Using the hibernated session, save the entity object into the database table.
2. Using the hibernated session, load the entity object into the database table.
In this state. each object represents one row in the database table. Therefore, if we make any
changes in the data then hibernate will detect these changes and make changes in the database
table.

Converting Transient State to Persistent State


Following are the methods given for the persistent state:
 session.persist(e);
 session.save(e);
 session.saveOrUpdate(e);
 session.update(e);
 session.merge(e);
 session.lock(e);
Example:
// Transient State
Employee e = new Employee("Neha Shri Rudra", 21, 180103);

//Persistent State
session.save(e);
State 3: Detached State
For converting an object from Persistent State to Detached State, we either have to close the
session or we have to clear its cache. As the session is closed here or the cache is cleared, then
any changes made to the data will not affect the database table. Whenever needed, the
detached object can be reconnected to a new hibernate session. To reconnect the detached
object to a new hibernate session, we will use the following methods as follows:
 merge()
 update()
 load()
 refresh()
 save()
 update()
Following are the methods used for the detached state :
 session.detach(e);
 session.evict(e);
 session.clear();
 session.close();

Converting Persistent State to Detached State


Example
// Transient State
Employee e = new Employee("Neha Shri Rudra", 21, 180103);

// Persistent State
session.save(e);

// Detached State
session.close();
State 4: Removed State
In the hibernate lifecycle it is the last state. In the removed state, when the entity object is
deleted from the database then the entity object is known to be in the removed state. It is done
by calling the delete() operation. As the entity object is in the removed state, if any change
will be done in the data will not affect the database table.
Note: To make a removed entity object we will call session.delete().

Converting Persistent State to Removed State


Example
// Java Pseudo code to Illustrate Remove State

// Transient State
Employee e = new Employee();
Session s = sessionfactory.openSession();
e.setId(01);

// Persistent State
session.save(e)
// Removed State
session.delete(e);

DATABASE CONNECTIVITY IN HIBERNARE: To connect to DB using Hibernate


users have to make the next steps:
 Create an environment at the platform
 Add a database node to this environment
 Modify some configuration files in a web-app
 Execute queries
Let’s do it step by step:
1. Create environment with a database server (MySQL in our case):

2. Create a new user in a database:


How to create a new user - click here.
1 Database name : jelasticDb
2 Username : jelastic
3 Password : jelastic

For this example we’ve created table books with fields book_name and book_author inside
the jelasticDb database.
3. Modify the following configuration files of your web-application:
hibernate.cfg.xml

2
<hibernate-configuration>
3 <session-factory>
<property
4 name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property
5 name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
6 name="hibernate.connection.url">jdbc:mysql://mysql{node_id}.{your_env_name}.
{hoster_domain}:3306/jelasticDb</property>
7 <property name="hibernate.connection.username">jelastic</property>
<property name="hibernate.connection.password">jelastic</property>
8 <property name="hibernate.current_session_context_class">thread</property>
<mapping resource="com/Testdata.hbm.xml"/>
9 </session-factory>
1 </hibernate-configuration>
0
1
1
hibernate.revenge.xml
1 <hibernate-reverse-engineering>
2 <schema-selection match-catalog="jelasticDb"/>
3 <table-filter match-name="books"/>
4 </hibernate-reverse-engineering>

For the next step we’ve used reverse engineering mechanism and got 2 files in our web-
project:
 Books.java
 Books.hbm.xml
Also you need to create the HibernateUtil.java file but do not need to change it.
4. Create a simple Java method, which will add a new row to the books table in our database:

1
public void addBook(){
2
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
3
s.beginTransaction();
4
Books book = new Books("romeo and juliet","william shakespeare ");
5
s.save(book);
6
s.getTransaction().commit();
7
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy