For the sample project, below mentioned tools got used
- Java 8
- Eclipse IDE for development
- Hibernate ORM, Spring framework with Spring Data JPA
- MySQL database, MySQL Connector Java as JDBC driver.
Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven
Project Structure:
As this is getting prepared as a maven project, all dependencies are specified in pom.xml
pom.xml
XML
< modelVersion >4.0.0</ modelVersion >
< groupId >com.gfg</ groupId >
< artifactId >SpringDataJPAConsoleSample</ artifactId >
< version >0.0.1-SNAPSHOT</ version >
< properties >
< maven.compiler.source >1.8</ maven.compiler.source >
< maven.compiler.target >1.8</ maven.compiler.target >
</ properties >
< dependencies >
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-context</ artifactId >
< version >5.1.4.RELEASE</ version >
</ dependency >
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-orm</ artifactId >
< version >5.1.4.RELEASE</ version >
</ dependency >
< dependency >
< groupId >org.hibernate</ groupId >
< artifactId >hibernate-core</ artifactId >
< version >5.4.1.Final</ version >
</ dependency >
< dependency >
< groupId >org.springframework.data</ groupId >
< artifactId >spring-data-jpa</ artifactId >
< version >2.1.4.RELEASE</ version >
</ dependency >
< dependency >
< groupId >mysql</ groupId >
< artifactId >mysql-connector-java</ artifactId >
< version >8.0.14</ version >
</ dependency >
</ dependencies >
</ project >
|
As we are connecting with MySQL, we need to create the database and table for use in the project
create database geeksforgeeks; # Creation
use geeksforgeeks #Make the database active
CREATE TABLE `Contest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`contestName` varchar(45) NOT NULL,
`contestDescription` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
Database connection properties are set in src/main/resources/persistence.xml
persistence.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?>
version = "2.1" >
< persistence-unit name = "GeeksDB" >
< properties >
< property name = "javax.persistence.jdbc.user" value = "***" />
< property name = "javax.persistence.jdbc.password" value = "***" />
< property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver" />
< property name = "hibernate.show_sql" value = "true" />
< property name = "hibernate.format_sql" value = "true" />
</ properties >
</ persistence-unit >
</ persistence >
|
Configuration of EntityManagerFactory and TransactionManager
ContestAppConfig.java
Java
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
@Configuration
@EnableJpaRepositories (basePackages = { "com.gfg.jpa" })
public class ContestAppConfig {
@Bean
public LocalEntityManagerFactoryBean entityManagerFactory() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName( "GeeksDB" );
return factoryBean;
}
@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
|
Let’s implement the model class.
Contest.java
Java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Contest {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
private String contestName;
private String contestDescription;
protected Contest() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this .id = id;
}
public String getContestName() {
return contestName;
}
public void setContestName(String contestName) {
this .contestName = contestName;
}
public String getContestDescription() {
return contestDescription;
}
public void setContestDescription(String contestDescription) {
this .contestDescription = contestDescription;
}
@Override
public String toString() {
return "Contest [contestName=" + contestName + ", contestDescription=" + contestDescription + "]" ;
}
}
|
ContestRepository.java
Instead of writing a generic DAO class, a simple interface like below is enough. It extends CrudRepository defined by Spring Data JPA. Common CRUD operations like save(), findAll(), findById(), delete(), count() etc., are defined by the interface.
Java
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface ContestRepository extends CrudRepository<Contest, Long> {
List<Contest> findByContestName(String contestName);
}
|
ContestService.java
Java
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service ( "contestService" )
public class ContestService {
@Autowired
private ContestRepository contestRepository;
public void test() {
Contest geekContest = new Contest();
geekContest.setContestName( "PremierLeague" );
geekContest.setContestDescription( "Inviting Geeks To submit articles in plenty" );
contestRepository.save(geekContest);
Optional<Contest> result = contestRepository.findById(1L);
result.ifPresent(contest -> System.out.println(contest));
List<Contest> contests = contestRepository.findByContestName( "PremierLeague" );
contests.forEach(contest -> System.out.println(contest));
Iterable<Contest> iterator = contestRepository.findAll();
iterator.forEach(contest -> System.out.println(contest));
long countOfContest = contestRepository.count();
System.out.println( "Number of contest held: " + countOfContest);
}
}
|
We can test the same via a test file
ContestTest.java
Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ContestTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.scan( "com.gfg.jpa" );
appContext.refresh();
ContestService contestService = (ContestService) appContext.getBean( "contestService" );
contestService.test();
appContext.close();
}
}
|
We can run the test file as an ordinary Java application
Output:
As we have tested via contestname as well, in the first output, we saw that one contest got inserted and the same is getting used to test while testing via contestname
We can check the DB data also
Note: id field is auto-generated.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
31 Oct, 2022
Like Article
Save Article