Hibernate 5.4 Configuration

 

Core Hibernate 5.4 Configuration

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>HibernateProj</groupId>
  <artifactId>HibernateProj</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.10.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>
  </dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    	<!-- <property name="hibernate.current_session_context_class">thread</property> -->
    	<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>
package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class MainClass {
  @SuppressWarnings("deprecation")
  public static void main(String[] args) {

    try{  
      Class.forName("com.mysql.cj.jdbc.Driver");  
      Connection con=DriverManager.getConnection(  
          "jdbc:mysql://localhost:3306/test","root","");  
      //here sonoo is database name, root is username and password  
      Statement stmt=con.createStatement();
//			stmt.executeUpdate("insert into emp VALUES (null, 'shailesh', 31, 'Nagpur')");
      ResultSet rs=stmt.executeQuery("select * from emp");  
      while(rs.next())
        System.out.println(rs.getString(1)+"  "+rs.getString(2)+"  "+rs.getString(3)+"  "+rs.getString(4));  
      con.close();  
    } catch(Exception e){ System.out.println(e);}  

    System.out.println("Hibernate connection established successfully...");

    Session session = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory().openSession();
    Query query = session.createNativeQuery("select * from emp");
    List<Student[]> list = query.list();
    System.out.println(list);

    for(Object[] obj : list) {
      Student std = new Student((Integer)obj[0], (String)obj[1], (Integer)obj[2], (String)obj[3]);
      System.out.println(std);
    }		
    ////////////////////////////////////////////////
    Query query2 = session.createNativeQuery("Select id, name, age, city from emp");
    query2.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    List<Student> students = query2.list();
    System.out.println(students);
    session.close();
    //==============================//
    Session session2 = new Configuration().configure("database.cfg.xml").buildSessionFactory().openSession();
    List list2 = session2.createNativeQuery("select * from testdmarc").list();
    System.out.println(list2);
  }
}

 

Reference:

https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#sql

https://tools.jboss.org/downloads/jbosstools/2019-09/4.13.0.Final.html#update_site

https://www.tutorialspoint.com/hibernate/hibernate_examples.htm

Hibernate Native SQL Query Example

Servlet File Upload

Ref:
https://www.codejava.net/java-ee/servlet/java-file-upload-example-with-servlet-30-api

https://www.baeldung.com/upload-file-servlet

Servlet 3 File Upload – @MultipartConfig, Part

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class MultiPartServlet
 */
@WebServlet("/multiPartServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, 	// 10 MB 
maxFileSize=1024*1024*50,      	// 50 MB
maxRequestSize=1024*1024*100)   	// 100 MB
public class MultiPartServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MultiPartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    
    PrintWriter out = response.getWriter();
  }

  private static final String SAVE_DIR = "uploadFiles";
  
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    // gets absolute path of the web application
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + SAVE_DIR;
         
        // creates the save directory if it does not exists
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
    
    
    for (Part part : request.getParts()) {
        String fileName = extractFileName(part);
//		    part.write(fileName);
        response.getWriter().println("/home/shailesh/eclipse-workspace/TestProject/WebContent/images/" + fileName);
        part.write("/home/shailesh/eclipse-workspace/TestProject/WebContent/images/" + fileName);
    }
    response.getWriter().println("Uploaded...");
    doGet(request, response);
  }
  
  private String extractFileName(Part part) {
      String contentDisp = part.getHeader("content-disposition");
      String[] items = contentDisp.split(";");
      for (String s : items) {
          if (s.trim().startsWith("filename")) {
              return s.substring(s.indexOf("=") + 2, s.length()-1);
          }
      }
      return "";
  }

}

 

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>TestProject</groupId>
  <artifactId>TestProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  <dependency>
    	<groupId>org.springframework</groupId>
   	 	<artifactId>spring-webmvc</artifactId>
    	<version>5.2.1.RELEASE</version>
  </dependency>
  
  <!-- Apache Commons FileUpload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>

    <!-- Apache Commons IO -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>
  
  </dependencies>
</project>
<form method="post" action="multiPartServlet" enctype="multipart/form-data">
  Choose a file: <input type="file" name="multiPartServlet" />
    <input type="submit" value="Upload" />
</form>