Loading
 
What's Next: View All Tutorial →

Spring boot + Hibernate + JPA + MySQL Integration

  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...

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



 

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-jpa</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>

	<name>spring-boot-jpa</name>
	<description>Demo project for Spring Boot</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-web</artifactId>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</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.java

package com.demo.spring;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.demo.spring")
public class Application {

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

		//EmpService object can be taken via application context or through @Autowired via CommandLineRunner interface
		EmpService empService = context.getBean(EmpService.class);

		
	}
}
 

Emp.java - Entity Bean

package com.demo.spring;

import javax.persistence.Column;
import javax.persistence.Entity;
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 - @Repository class for service implementation

 
package com.demo.spring;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

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

@Repository
@Transactional
public class EmpService {

	@PersistenceContext
	EntityManager emf;

	public String save(Emp e) {
		emf.persist(e);
		return "success";
	}

	public int delete(int empId) {

		int deletedCount = emf.createQuery("DELETE FROM Emp where empId=?").setParameter(0, empId).executeUpdate();
		return deletedCount;
	}

	public Emp findById(int empId) {
		Emp e = emf.find(Emp.class, empId);
		return e;
	}

	
	public List<Emp> getEmpList() {

		Query query = emf.createQuery("select e from Emp e");
		return query.getResultList();

	}
}
@Transactional

@PersistenceContext
	EntityManager emf;

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

# ===============================
# JPA / HIBERNATE
# ===============================
 
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

 

DemoRunner.java  

package com.demo.spring;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DemoRunner implements CommandLineRunner {

	@Autowired
	EmpService empService;

	@Override
	public void run(String... args) throws Exception {
		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(103);

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

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

}
 

Output:

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]
05-09-2018 10:21:19.113 [main] INFO  org.hibernate.hql.internal.QueryTranslatorFactoryInitiator.initiateService - 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=Rekha, city=Mumbai, salary=23000.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]]
05-09-2018 10:21:19.189 [main] WARN  org.hibernate.hql.internal.ast.HqlSqlWalker.generatePositionalParameter - [DEPRECATION] Encountered positional parameter near line 1, column 45 in HQL: [DELETE FROM com.demo.spring.Emp where empId=?].  Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.
Hibernate: delete from emp where empno=?
Deleted count0
Hibernate: insert into emp (address, name, salary, empno) values (?, ?, ?, ?)
Awaiting for Administrator approval




← Back to list


Related Post




×