EJB+Hibernate
1.Create table inside sevice->java DB->new Database->name "myDB"->app->app
create table"Person"
id-int-PK
name-varchar(20),
age-int
ok->connct
2.Create Java EE application
ejb->give a name->java 6.9.1->glasfish 3.1
3.ejb->new->newpkge->give name->other->entity class from databse->select table->if not new datasouce->select database->
jindi/dbname->ok->select pkg->finish.
4.delete all rather than attributes/getters/setters/only to string.
-----------------------------------------------------------------------------------------------------------------------
package er;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
public Person() {
}
public Person(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "er.Person[ id=" + id + " ]";
}
}
-----------------------------------------------------------------------------------------------------------------
2.Go to war file souce pakage to create hibernate packages
3.Create Configuration file
souce pakge->new->other->hibernate->hibernate config wizard->give create db name->table.
Configurations->show.sql->true
Misalinius->thread.
4.Create Mapping file
sose pakge->new->other->hibernate->mapping wizard->type class name 1st later->p->select the class name with the pakage name "Person(pakge)"->ok->Select table->finish
go in side the
<hibernate-mapping>
<class name="er.Person" table="PERSON">
<id column="ID" name="id">
<generator class="increment"/>
</id>
<property column="NAME" name="name"/>
<property column="AGE" name="age"/>
</class>
</class>
</hibernate-mapping>
Check class name,table name,columns,class attributes correct.
----------------------------------------------------------------------------------------------------
5.Go config->souce-------now mapping propety should there.
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/myDB</property>
<property name="hibernate.connection.username">app</property>
<property name="hibernate.connection.password">app</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
------------------------------------------------------------------------------------------------------------------------
5.Create Hibernate Util class
war->souce pakage->other->newhibernateutil->ok
need add relevent methods if not there.
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class NewHibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session openSession() {
return sessionFactory.openSession();
}
public static Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
/**
* closes the session factory
*/
public static void close() {
if (sessionFactory != null) {
sessionFactory.close();
}
}
}
----------------------------------------------------------------------------------------------------------------------
6.In side the jar add Hibernate 4.x libries
----------------------------------------------------------------------------------------------------------------------
7.Drag and drop config and mapping file inside the ejb->souce pakage
----------------------------------------------------------------------------------------------------------------------
8.add the util file inside current pakage which contains the classes.
----------------------------------------------------------------------------------------------------------------------
9.Add java class
Name it as Personmanger
package er;
import javax.ejb.Stateless;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @author MANISHA
*/
@Stateless
public class PersonManager {
public void createPerson(Person person) {
Transaction tx = null;
//util class name has method getCurrentSession.
Session session = NewHibernateUtil.getCurrentSession();
try {
tx = session.beginTransaction();
session.save(person);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
// tx.rollback();
}
catch (HibernateException e1) {
System.out.println("Error rolling back transaction");
}
// throw again the first exception
throw e;
}
}
}
}
------------------------------------------------------------------------------------------------------------------------
10.Go to war
New other new pakage-> Servelet->Main
Go inside the main servelet
@WebServlet(name = "Main", urlPatterns = {"/Main"})
public class Main extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Main</title>");
out.println("</head>");
out.println("<body>");
out.println("<a href='Show'>Book Details</a>");
out.println("</body>");
out.println("</html>");
}
}
-----------------------------------------------------------------------------------------------------------------
Click on the project->propeties->run->Set path-> /Main
-----------------------------------------------------------------------------------------------------------------
Create another Servlet->Name it as Show
Inside the Show class r8 Click ->Insert code->Call entprisebean->ejb->Select the class
package er;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author MANISHA
*/
@WebServlet(name = "Show", urlPatterns = {"/Show"})
public class Show extends HttpServlet {
int Id=0;
int Age=0.0;
String name=null;
int state=0;
@EJB
private PersonManager personManager;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
if (request.getParameter("id") != null) {
Id = Integer.parseInt(request.getParameter("id").toString());
}
if (request.getParameter("age") != null) {
Age = Integer.parseInt(request.getParameter("age").toString());
}
name = request.getParameter("name");
if ((Id != 0) && (Age != 0) && (name != null) ) {
try {
try {
Person b = new Person();
b.setId(Id);
b.setName(name);
b.setAge(Age);
personManager.createPerson(b);
state=0;
} catch (Exception e) {
//catch (EJBException ex) {
state=1;
}
//Give a servelet name if add move this servelet
response.sendRedirect("ListNews");
} catch (Exception e) {
//catch (EJBException ex) {
ex.printStackTrace();
}
}
---------------------------------------------------------------------------------------------------------------------
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Show</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Add New person</h2>");
out.println("<br/>");
out.println("<form>");
out.println("Id: <br/>");
out.println("<input type='text' name='id' id='id'><br/>");
out.println("<br/>");
out.println("Name: <br/>");
out.println("<input type='text' name='name' id='name'><br/>");
out.println("Age: <br/>");
out.println("<input type='text' name='age' id='age' ><br/>");
out.println("<br/>");
out.println("<input type='submit' value='Add Book'><br/>");
out.println("</form>");
out.println("<br/>");
out.println("<a href='ListBooks'>Back</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
------------------------------------------------------------------------------------------------------------------
Run the application
http://localhost:8080/hiperEJB-war/Main
No comments:
Post a Comment