Advertisement
andrzejiwaniuk

hibernate maven web servlet

Jan 14th, 2016
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.20 KB | None | 0 0
  1. /*********************************************************
  2. Hibernate configuration  files:
  3. hibernate-oracle.cfg.xml
  4. /*********************************************************
  5.  
  6. <?xml version="1.0" encoding="utf-8"?>
  7. <!DOCTYPE hibernate-configuration SYSTEM
  8. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  9. <hibernate-configuration>
  10.     <session-factory>
  11.        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  12.                   <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>
  13.                   <property name="hibernate.connection.username">system</property>
  14.                   <property name="hibernate.connection.password">andrzej</property>
  15.                   <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  16.                   <property name="hibernate.default_schema">SYSTEM</property>
  17.                  <property name="show_sql">true</property>
  18.         <!-- List of XML mapping files -->
  19.         <mapping class="app2.Employee"/>
  20.     </session-factory>
  21. </hibernate-configuration>
  22.  
  23.  
  24. /*********************************************************
  25. Hibernate configuration  files:
  26. hibernate-mysql.cfg.xml
  27.  
  28. /*********************************************************
  29.  
  30. <?xml version="1.0" encoding="utf-8"?>
  31. <!DOCTYPE hibernate-configuration SYSTEM
  32. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  33. <hibernate-configuration>
  34.     <session-factory>
  35.         <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property>
  36.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  37.         <!-- Assume test is the database name -->
  38.         <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/test </property>
  39.         <property name="hibernate.connection.username"> root </property>
  40.         <property name="hibernate.connection.password"> andrzej </property>
  41.         <!-- List of XML mapping files -->
  42.         <mapping resource="Employee.hbm.xml"/>
  43.     </session-factory>
  44. </hibernate-configuration>
  45.  
  46.  
  47. /*********************************************************
  48. Reading hibernate configuration files from Java source code:
  49.  
  50. /*********************************************************
  51.  
  52. package app2;
  53.  
  54. import org.slf4j.Logger;
  55. import org.slf4j.LoggerFactory;
  56.  
  57. import java.util.List;
  58. import java.util.Date;
  59. import java.util.Iterator;
  60.  
  61. import org.hibernate.Criteria;
  62. import org.hibernate.HibernateException;
  63. import org.hibernate.Query;
  64. import org.hibernate.SQLQuery;
  65. import org.hibernate.Session;
  66. import org.hibernate.Transaction;
  67. import org.hibernate.SessionFactory;
  68. import org.hibernate.cfg.AnnotationConfiguration;
  69. import org.hibernate.cfg.Configuration;
  70.  
  71. import java.util.*;
  72. import java.util.logging.Level;
  73.  
  74. public class apps2 {
  75.                 private static SessionFactory factory;
  76.                
  77.                 public static void main(String[] args)
  78.                 {
  79.                                
  80.                                try{
  81.                                                //factory = new Configuration().configure().buildSessionFactory();
  82.                                                Configuration cfg1 = new AnnotationConfiguration();
  83.                                                //cfg1.configure("/hibernate-mysql.cfg.xml");
  84.                                                cfg1.configure("/hibernate-oracle.cfg.xml");
  85.                                                factory = cfg1.buildSessionFactory();
  86.                                                                                                              
  87.                                }catch (Throwable ex)
  88.                                {
  89.                                                System.err.println("Failed to create sessionFactory object." + ex);
  90.                                                throw new ExceptionInInitializerError(ex);
  91.                                }
  92.                                apps2 ME = new apps2();
  93.                                
  94.                                /* Add few employee records in database */
  95.                                Integer empID1 = ME.addEmployee("andrzej", "haslo", 100000);
  96.                                
  97.                                //ME.listEmployeesScalar();
  98.                                /* List down all the employees */
  99.                                //ME.listEmployees();
  100.                                
  101.                                /* Update employee's records */
  102.                                //ME.updateEmployee(2, 20000);
  103.                                
  104.                                /* Delete an employee from the database */
  105.                                
  106.                                /*for (int i = 12; i <= 19; i++)
  107.                                                ME.deleteEmployee(i);*/
  108.                                
  109.                                /* List down new list of the employees */
  110.                                //ME.listEmployees();
  111.                                
  112.                                //System.out.println("Witaj");
  113.                                /*Logger logger = LoggerFactory.getLogger(apps2.class);
  114.                     logger.info("Logger Andrzej");*/
  115.  
  116.                 }
  117.                 /* Method to CREATE an employee in the database */
  118.                 public Integer addEmployee(String fname, String lname, int        salary)
  119.                 {
  120.                                Session session = factory.openSession();
  121.                                Transaction tx = null;
  122.                                Integer employeeID = null;
  123.                                try{
  124.                                                tx = session.beginTransaction();
  125.                                                Employee employee = new Employee(fname, lname, salary);
  126.                                                employeeID = (Integer) session.save(employee);
  127.                                                tx.commit();
  128.                                }catch (HibernateException e)
  129.                                {
  130.                                                if (tx!=null)
  131.                                                                tx.rollback();
  132.                                                e.printStackTrace();
  133.                                }finally
  134.                                {
  135.                                                session.close();
  136.                                }
  137.                                return employeeID;
  138.                 }
  139.                 /* Method to READ all the employees */
  140.                 public void listEmployees( )
  141.                 {
  142.                                Session session = factory.openSession();
  143.                                Transaction tx = null;
  144.                                try{
  145.                                                tx = session.beginTransaction();
  146.                                                List employees = session.createQuery("FROM Employee").list();
  147.                                                for (Iterator iterator = employees.iterator(); iterator.hasNext();)
  148.                                                {
  149.                                                                Employee employee = (Employee) iterator.next();
  150.                                                                //System.out.print("First Name: " + employee.getFirstName());
  151.                                                                System.out.print(" Last Name: " + employee.getLastName());
  152.                                                                //System.out.println(" Salary: " + employee.getSalary());
  153.                                                                }
  154.                                                tx.commit();
  155.                                                }catch (HibernateException e)
  156.                                                {
  157.                                                                if (tx!=null) tx.rollback();
  158.                                                                e.printStackTrace();
  159.                                                }finally
  160.                                                {
  161.                                                                session.close();
  162.                                                }
  163.                                }
  164.                
  165.                 /* Method to READ all the employees using Scalar Query */
  166.                 public void listEmployeesScalar( )
  167.                 {
  168.                                Session session = factory.openSession();
  169.                                Transaction tx = null;
  170.                                try{
  171.                                                tx = session.beginTransaction();
  172.                                                String sql = "SELECT first_name, salary FROM EMPLOYEE";
  173.                                                SQLQuery query = session.createSQLQuery(sql);
  174.                                                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
  175.                                                List data = query.list();
  176.                                                for(Object object : data)
  177.                                                {
  178.                                                                Map row = (Map)object;
  179.                                                                System.out.print("First Name: " + row.get("first_name"));
  180.                                                                System.out.println(", Salary: " + row.get("salary"));
  181.                                                }
  182.                                                tx.commit();
  183.                                }catch (HibernateException e)
  184.                                {
  185.                                                if (tx!=null)
  186.                                                                tx.rollback();
  187.                                                e.printStackTrace();
  188.                                }finally {
  189.                                                session.close();
  190.                                }
  191.                 }
  192.                
  193.                 /* Method to UPDATE salary for an employee */
  194.                 public void updateEmployee(Integer EmployeeID, int salary )
  195.                 {
  196.                                Session session = factory.openSession();
  197.                                Transaction tx = null;
  198.                                try{
  199.                                                tx = session.beginTransaction();
  200.                                                Employee employee = (Employee)session.get(Employee.class, EmployeeID);
  201.                                                employee.setSalary( salary );
  202.                                                session.update(employee);
  203.                                                tx.commit();
  204.                                }catch (HibernateException e)
  205.                                {
  206.                                                if (tx!=null) tx.rollback();
  207.                                                e.printStackTrace();
  208.                                }finally
  209.                                {
  210.                                                session.close();
  211.                                }
  212.                 }
  213.                 /* Method to DELETE an employee from the records */
  214.                 public void deleteEmployee(Integer EmployeeID)
  215.                 {
  216.                                Session session = factory.openSession();
  217.                                Transaction tx = null;
  218.                                try{
  219.                                                tx = session.beginTransaction();
  220.                                                Employee employee = (Employee)session.get(Employee.class, EmployeeID);
  221.                                                session.delete(employee);
  222.                                                tx.commit();
  223.                                }catch (HibernateException e)
  224.                                {
  225.                                                if (tx!=null)
  226.                                                                tx.rollback();
  227.                                                e.printStackTrace();
  228.                                }finally
  229.                                {
  230.                                                session.close();
  231.                                                }
  232.                                }
  233.                
  234. }
  235.  
  236.  
  237. /*********************************************************
  238. Hibernate Mapping POJO class:
  239.  
  240. /*********************************************************
  241.  
  242. package app2;
  243. import javax.persistence.Column;
  244. import javax.persistence.Entity;
  245. import javax.persistence.GeneratedValue;
  246. import javax.persistence.Id;
  247. import javax.persistence.Table;
  248.  
  249. import org.hibernate.annotations.GenericGenerator;
  250.  
  251.  
  252. @Entity
  253. @Table(name = "Employee")
  254. public class Employee {
  255.                 private int id;
  256.                 private String firstName;
  257.                 private String lastName;
  258.                 private int salary;
  259.                
  260.                
  261.                 public Employee() {}
  262.                 public Employee(String fname, String lname, int salary)
  263.                 {
  264.                                this.firstName = fname;
  265.                                this.lastName = lname;
  266.                                this.salary = salary;
  267.                 }
  268.                 @Id
  269.                 @GenericGenerator(name="kaugen" , strategy="increment")
  270.                 @GeneratedValue(generator="kaugen")
  271.                 public int getId()
  272.                 {
  273.                                return id;
  274.                 }
  275.                 public void setId( int id )
  276.                 {
  277.                                this.id = id;
  278.                 }
  279.                 @Column(name = "first_name")
  280.                 public String getFirstName()
  281.                 {
  282.                                return firstName;
  283.                 }
  284.                 public void setFirstName( String first_name )
  285.                 {
  286.                                this.firstName = first_name;
  287.                 }
  288.                 @Column(name = "last_name")
  289.                 public String getLastName()
  290.                 {
  291.                                return lastName;
  292.                 }
  293.                 public void setLastName( String last_name )
  294.                 {
  295.                                this.lastName = last_name;
  296.                 }
  297.                 @Column(name = "salary")
  298.                 public int getSalary()
  299.                 {
  300.                                return salary;
  301.                 }
  302.                 public void setSalary( int salary )
  303.                 {
  304.                                this.salary = salary;
  305.                 }
  306.                
  307. }
  308.  
  309. /********************************************
  310. POM.xml
  311. /********************************************
  312. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  313.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  314.   <modelVersion>4.0.0</modelVersion>
  315.   <groupId>com.mycompany.app</groupId>
  316.   <artifactId>my-app</artifactId>
  317.   <packaging>jar</packaging>
  318.   <version>1.0-SNAPSHOT</version>
  319.   <name>my-app</name>
  320.   <url>http://maven.apache.org</url>
  321.   <dependencies>
  322.     <dependency>
  323.       <groupId>junit</groupId>
  324.       <artifactId>junit</artifactId>
  325.       <version>3.8.1</version>
  326.       <scope>test</scope>
  327.     </dependency>
  328.                <dependency>
  329.                                <groupId>org.hibernate</groupId>
  330.                                <artifactId>hibernate-core</artifactId>
  331.                                <version>5.0.1.Final</version>
  332.                 </dependency>
  333.                 <dependency>
  334.                                <groupId>org.hibernate</groupId>
  335.                                <artifactId>hibernate-annotations</artifactId>
  336.                                <version>3.5.6-Final</version>
  337.                 </dependency>
  338.    
  339.   </dependencies>
  340. </project>
  341.  
  342.  
  343. /********************************************
  344. FirstServlet.java
  345. /********************************************
  346.  
  347. package webservlet;
  348.  
  349. import java.io.IOException;
  350. import java.io.PrintWriter;
  351.  
  352. import javax.servlet.RequestDispatcher;
  353. import javax.servlet.ServletException;
  354. import javax.servlet.annotation.WebServlet;
  355. import javax.servlet.http.HttpServlet;
  356. import javax.servlet.http.HttpServletRequest;
  357. import javax.servlet.http.HttpServletResponse;
  358.  
  359. @WebServlet("/WitajSwiecie1")
  360. public class FirstServlet extends HttpServlet{
  361.                
  362.                
  363.                 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  364.                                PrintWriter out = response.getWriter();
  365.         out.println("Welcome !!");
  366.         RequestDispatcher RequetsDispatcherObj =request.getRequestDispatcher("/index.html");
  367.         RequetsDispatcherObj.forward(request, response);
  368.        
  369.                 }
  370. }
  371.  
  372.  
  373.  
  374. /********************************************
  375. Index.html
  376. /********************************************
  377. <html>
  378.     <head>
  379.                                <link rel="stylesheet" type="text/css" href="style.css">
  380.                 </head>
  381.    
  382.     <body>
  383.     <h1>Welcome</h1>
  384.     <br/>
  385.     <form action="odpowiedz.jsp" method="GET">
  386.          <b>Imie: </b><input type="text" name="first_name">
  387.     <br />
  388.          <b>Nazwisko: </b><input type="text" name="last_name" />
  389.     <br />
  390.     <input type="submit" value="Submit" />
  391.     <input type="checkbox" name="a" checked="checked" /> A
  392.     <input type="checkbox" name="b"  /> B
  393.     <input type="checkbox" name="c" checked="checked" /> C
  394.     </form>
  395.     </body>
  396. </html>
  397.  
  398.  
  399. /********************************************
  400. Pom.xml (for Maven)
  401. /********************************************
  402. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  403.   <modelVersion>4.0.0</modelVersion>
  404.   <groupId>co.uk.tedo</groupId>
  405.   <artifactId>firstwebservlet</artifactId>
  406.   <version>0.0.1-SNAPSHOT</version>
  407.   <packaging>war</packaging>
  408.     <dependencies>
  409.     <dependency>
  410.       <groupId>junit</groupId>
  411.       <artifactId>junit</artifactId>
  412.       <version>4.0</version>
  413.       <type>jar</type>
  414.       <scope>test</scope>
  415.       <optional>true</optional>
  416.     </dependency>
  417.     <dependency>
  418.                                <groupId>javax.servlet</groupId>
  419.                                <artifactId>javax.servlet-api</artifactId>
  420.                                <version>3.1.0</version>
  421.                 </dependency>
  422.                
  423.   </dependencies>
  424. </project>
  425.  
  426. /********************************************
  427. Style.css file
  428. /********************************************
  429.  
  430. b {
  431.     font-weight: bold;
  432.     color: #7F462C;
  433. }
  434.  
  435. body {
  436.     font-family: Verdana, Arial, sans-serif;
  437.     font-size: smaller;
  438.     padding: 50px;
  439.     color: #555;
  440.     background-color: #b0c4de;
  441. }
  442.  
  443. h1 {
  444.     text-align: left;
  445.     letter-spacing: 6px;
  446.     font-size: 1.4em;
  447.     color: #be7429;
  448.     font-weight: normal;
  449.     width: 450px;
  450. }
  451.  
  452. table {
  453.     width: 580px;
  454.     padding: 10px;
  455.     background-color: #c5e7e0;
  456. }
  457.  
  458. th {
  459.     text-align: left;
  460.     border-bottom: 1px solid;
  461. }
  462.  
  463. td {
  464.     padding: 10px;
  465. }
  466.  
  467. a:link {
  468.    color: #be7429;
  469.    font-weight: normal;
  470.    text-decoration: none;
  471. }
  472.  
  473. a:link:hover {
  474.    color: #be7429;
  475.    font-weight: normal;
  476.    text-decoration: underline;
  477. }
  478.  
  479. /********************************************
  480. Web.xml file
  481. /********************************************
  482.  
  483. <?xml version="1.0" encoding="ISO-8859-1" ?>
  484.  
  485. <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  486.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  487.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  488.     version="2.4">
  489.  
  490.     <display-name>webservlet1</display-name>
  491. </web-app>
  492.  
  493.  
  494. /********************************************
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement