Loading
 
What's Next: View All Tutorial →

Spring Boot Hibernate 5 Integration using SessionFactory

A simple program with Spring Boot  Hibernate 5 Integration using SessionFactory   Maven Dependency <?xml version="1.0" encoding="UTF-8"?> <project x...

Published Date: 06/09/2018  Last Modified Date: 06/09/2018    New Post



A simple program with Spring Boot  Hibernate 5 Integration using SessionFactory
 

Maven Dependency

<?xml version="1.0" encoding="UTF-8"?>
<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>com.demo</groupId>
    <artifactId>spring-boot-hibernate-sessionfactory</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-hibernate-sessionfactory</name>
    <description>Demo project for Spring Boot Hibernate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
		

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
           
        </plugins>
    </build>


</project>
 

application.properties

# ===============================
# Spring datasource connection
# ===============================

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/springdb?useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.name=dataSource


 

DBConfiguration.java

package com.demo.spring;

import java.util.Properties;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DBConfiguration {

    @Autowired
    DataSource ds;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(ds);
        sessionFactory.setPackagesToScan("com.demo.spring.entity");
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.show_sql", "true");
        sessionFactory.setHibernateProperties(hibernateProperties);
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }
}
 

Emp.java - Bean Method

package com.demo.spring.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "EMP")
public class Emp {

    @Id
    @Column(name = "EMPNO")
    private int empId;

    private String name;

    @Column(name = "address")
    private String city;
    private double salary;

    public Emp() {

    }

    public Emp(int empId, String name, String city, double salary) {

        this.empId = empId;
        this.name = name;
        this.city = city;
        this.salary = salary;
    }

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Emp [empId=" + empId + ", name=" + name + ", city=" + city + ", salary=" + salary + "]";
    }

}
 

EmpService.java

package com.demo.spring;

import com.demo.spring.entity.Emp;
import java.util.List;

import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class EmpService {

    @Autowired
    private SessionFactory sessionFactory;

    public String save(Emp e) {
        Session s = sessionFactory.getCurrentSession();
        s.save(e);
        return "success";
    }

    public int delete(int empId) {
        Session s = sessionFactory.getCurrentSession();
        int deletedCount = s.createQuery("delete from Emp where empId=:empId").setParameter("empId", empId).executeUpdate();
        return deletedCount;
    }

    public Emp findById(int empId) {
        Session s = sessionFactory.getCurrentSession();
        Emp e = s.find(Emp.class, empId);
        return e;
    }

    public List<Emp> getEmpList() {
        Session s = sessionFactory.getCurrentSession();
        Query query = s.createQuery("select e from Emp e");
        return query.getResultList();

    }
}
 

Application.java

package com.demo.spring;

import com.demo.spring.entity.Emp;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication

public class Application {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);

        EmpService empService = context.getBean(EmpService.class);
        Emp e = empService.findById(101);
        System.out.println("Employee fetched" + e);

        List<Emp> empList = empService.getEmpList();
        System.out.println("Emp List" + empList);

        int result = empService.delete(102);

        System.out.println("Deleted count" + result);

        String saveResult = empService.save(new Emp(102, "Peter", "Indiana", 60000));
        System.out.println("Save result" + saveResult);
    }

}

Output:


2018-09-06 11:32:06.626  INFO 3716 --- [           main] com.demo.spring.Application              : Started Application in 2.905 seconds (JVM running for 3.567)
Hibernate: select emp0_.EMPNO as EMPNO1_0_0_, emp0_.address as address2_0_0_, emp0_.name as name3_0_0_, emp0_.salary as salary4_0_0_ from EMP emp0_ where emp0_.EMPNO=?
Employee fetchedEmp [empId=101, name=Shekhar, city=Hyderabad, salary=30000.0]
2018-09-06 11:32:06.762  INFO 3716 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select emp0_.EMPNO as EMPNO1_0_, emp0_.address as address2_0_, emp0_.name as name3_0_, emp0_.salary as salary4_0_ from EMP emp0_
Emp List[Emp [empId=100, name=Amitabh, city=Mumbai, salary=20000.0], Emp [empId=101, name=Shekhar, city=Hyderabad, salary=30000.0], Emp [empId=102, name=Peter, city=Indiana, salary=60000.0], Emp [empId=104, name=Ajay, city=Bangalore, salary=80000.0], Emp [empId=105, name=John, city=New York, salary=50000.0], Emp [empId=106, name=John, city=New York, salary=50000.0], Emp [empId=107, name=John, city=New York, salary=50000.0], Emp [empId=108, name=John, city=New York, salary=50000.0]]
Hibernate: delete from EMP where EMPNO=?
Deleted count1
Hibernate: insert into EMP (address, name, salary, EMPNO) values (?, ?, ?, ?)
Save resultsuccess
  

Source code:


https://github.com/Catchmycity/Springboot/tree/master/spring-boot-hibernate-sessionfactory
 
Awaiting for Administrator approval




← Back to list


Related Post




×