Tuesday, 6 October 2020

How to Use Native Query in Hibernate


Hibernate Native Query 

Hibernate Native query used to execute SQL query using hibernate . session.createNativeQuery(String sqlQuery) above method used to execute SQL query .

FootWear.java

package in.jk.hibernate5.nativequery;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="hibernate5_footwear")
public class FootWear {
@Id
@Column(name="product_id")
private int productId;
@Column(name="product_name")
private String productName;
@Column(name="company")
private String company;
@Column(name="price")
private int price;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}



HibernateUtils.java

package in.jk.hibernate5;

import java.util.HashMap;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;

public class HibernateUtils {

private static StandardServiceRegistry standardServiceRegistry = null;
private static SessionFactory sessionFactory = null;

// SessionFactory using java config
public static SessionFactory buildSessionFactory() {

         
        StandardServiceRegistryBuilder serviceRegistryBuilder = null;
new StandardServiceRegistryBuilder();
Map<String, String> hibernateProperties = new HashMap<String, String>();

hibernateProperties.put(Environment.DRIVER, "org.postgresql.Driver");
hibernateProperties.put(Environment.URL, "jdbc:postgresql://localhost:5432/postgres");
hibernateProperties.put(Environment.USER, "postgres");
hibernateProperties.put(Environment.PASS, "jk123");
hibernateProperties.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
hibernateProperties.put(Environment.SHOW_SQL, "true");
hibernateProperties.put(Environment.HBM2DDL_AUTO, "update");

serviceRegistryBuilder.applySettings(hibernateProperties);
standardServiceRegistry = serviceRegistryBuilder.build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);

// Hibernate Native Query Use
metadataSources.addAnnotatedClass(in.jk.hibernate5.nativequery.MensWear.class);

Metadata metadata = metadataSources.getMetadataBuilder().build();
                sessionFactory = metadata.getSessionFactoryBuilder().build();
                return sessionFactory;

}

       public static SessionFactory getSessionFactory() {

return sessionFactory;

}

}


Pom.xml

<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">
<modelVersion>4.0.0</modelVersion>
<groupId>Hibernate5withJava</groupId>
<artifactId>Hibernate5withJava</artifactId>
<version>0.0.1-SNAPSHOT</version>
        <dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>
               </dependencies>

        <build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<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>
</project>

NativeQueryHibernate5Application .java

package in.jk.hibernate5.nativequery;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import in.jk.hibernate5.HibernateUtils;

public class NativeQueryHibernate5Application {

private static SessionFactory sessionFactory;

public static void main(String[] args) {

sessionFactory = HibernateUtils.buildSessionFactory();
NativeQueryHibernate5Application.addfootWear();

NativeQueryHibernate5Application.findfootWear();

}

private static void addfootWear() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

FootWear footWear1 = new FootWear();
footWear1.setProductId(1);
footWear1.setProductName("Sole Fury   ");
footWear1.setCompany("Rebook");
footWear1.setPrice(9999);

FootWear footWear2 = new FootWear();
footWear2.setProductId(2);
footWear2.setProductName("Hexafect 5.0 ");
footWear2.setCompany("Rebook");
footWear2.setPrice(7999);

FootWear footWear3 = new FootWear();
footWear3.setProductId(3);
footWear3.setProductName("Hexafect 4.0 ");
footWear3.setCompany("Rebook");
footWear3.setPrice(6999);

session.persist(footWear1);
session.persist(footWear2);
session.persist(footWear3);

transaction.commit();
session.close();

System.out.println("Footwear Added Succussfully ...");

}

private static void findfootWear() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

String sqlQuery = "select product_id,product_name,company,price from hibernate5_footwear order by product_id asc";
Query<Object[]> query = session.createNativeQuery(sqlQuery);

List<Object[]> list = query.getResultList();

System.out.println("Foot Wear List :: ");
System.out.print("Product Id     Name          Company  Price ");
System.out.println();

for (Object[] objects : list) {

System.out.println(objects[0] + "             " + objects[1] + "  " + objects[2] + "   " + objects[3]);

}

transaction.commit();
session.close();
System.out.println();
System.out.println("Foot Wear Data Fetch Succussfully ...");

}

}

Output in Console ...

INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into hibernate5_footwear (company, price, product_name, product_id) values (?, ?, ?, ?)
Hibernate: insert into hibernate5_footwear (company, price, product_name, product_id) values (?, ?, ?, ?)
Hibernate: insert into hibernate5_footwear (company, price, product_name, product_id) values (?, ?, ?, ?)
Footwear Added Succussfully ...
Hibernate: select product_id,product_name,company,price from hibernate5_footwear order by product_id asc
Foot Wear List :: 
Product Id     Name          Company  Price 
100           Sole Fury      Rebook   9999
200           Hexafect 5.0   Rebook   7999
300           Hexafect 4.0   Rebook   6999

Foot Wear Data Fetch Succussfully ...


No comments:

Post a Comment