[JAVA] Until the use of Spring Data and JPA Part 1

The difficulty of setting is quite high.

I think it's a unique way of writing Spring Framework, but I do and wear Java such as property files and xml files. I think it's quite a beginner killing, so I summarized the use of JPA.

Divide goals

    1. What you need just to connect with SQL -Hibernate EntityManager library ・ Spring JDBC library ・ Database driver PostgreSQL or H2 ·Property file -Bean configuration file (xml) JavaConfig is not used this time. Maybe it's going to get confusing
  1. In addition, what is required for JPA ・ Spring Data JPA library ・ Entity class -Persistence.xml file (Java EJB function) -Bean configuration file (xml) -Execution class with main method

Check the console to see if the query arrived in the database. Use on the web later.

Connection with DB

Library and driver settings

pom settings.

Add to pom and add dependencies. I'm using Spring IO pratform, so I won't describe the version!

pom.xml



		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
		</dependency>

		<!-- jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		
		<!-- postgresql database -->
		<dependency>
   			 <groupId>org.postgresql</groupId>
    		<artifactId>postgresql</artifactId>
		</dependency>


After drawing, right click ** Maven → updateProject **

Creating a property file

I will give Spring information about the PostgreSQL driver. Create a property file of ** database.properties ** in src / main / resource.

database.properties


jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/sample
jdbc.username=postgres
jdbc.password=password

If it's PostgreSQL, it looks like this, according to the DB you use.

Creating a bean configuration file

Register the DataSource and JdbcTemplate in the DI container. Create ** bean.xml ** in src / main / resource

You read the value from the property file and register it in the bean.

bean.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">


	<!--Settings for embedded database>
	<jdbc:embedded-database id="dataSource" type="H2">
		<jdbc:script location="classpath:script.sql"/>
	</jdbc:embedded-database-->

	<!--Setting database properties-->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	  	<property name="location" value="database.properties" />
	</bean>

	<!--Settings for DB connection-->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<!--Creating a JDBC template bean-->
	<bean class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg ref="dataSource" />
	</bean>

Try to actually connect

Let's take this out of DI and run it Access the database with ** execute ** and ** queryForList ** of JdbcTemplate!

App.java


@Component
@ComponentScan
public class App {
	//private static JdbcTemplate jdbcTemplate;
	private static ApplicationContext context;
	private static JdbcTemplate jdbcTemplate;
	
	public static void main(String args[]) {
		
		//Creating a template using annotations
		//context = new AnnotationConfigApplicationContext(DataSourceConfig.class);
		//JdbcTemplate jdbcTemplate = (JdbcTemplate)context.getBean(JdbcTemplate.class);
		//Get context
		context = new ClassPathXmlApplicationContext("bean.xml");
		jdbcTemplate = context.getBean(JdbcTemplate.class);
	
		List<Map<String, Object>> list = jdbcTemplate
				.queryForList("SELECT * FROM mytable");
		
		for(Map<String, Object> obj : list) {
			System.out.println(obj);
		}
	
	}

}

Do this and watch

image.png

At the bottom you can see that the columns have been retrieved from the database.

Continued to Part 2

Recommended Posts

Until the use of Spring Data and JPA Part 2
Until the use of Spring Data and JPA Part 1
Check the behavior of getOne, findById, and query methods in Spring Boot + Spring Data JPA
[Spring Data JPA] Can And condition be used in the automatically implemented method of delete?
See the behavior of entity update with Spring Boot + Spring Data JPA
[Java] The confusing part of String and StringBuilder
[For beginners] DI ~ The basics of DI and DI in Spring ~
Make the where clause variable in Spring Data JPA
The story of raising Spring Boot from 1.5 series to 2.1 series part2
Qualify only part of the text
Spring Data JPA: Write a query in Pure SQL in @Query of Repository
How to use Spring Data JDBC
Memo of JSUG Study Group 2018 Part 2-Efforts for working specifications in the Spring and API era-
[How to install Spring Data Jpa]
Part 4: Customize the behavior of OAuth 2.0 Login supported by Spring Security 5
Proper use of redirect_to and render
This and that of the JDK
Filter the fluctuations of raw data
Item 59: Know and use the libraries
Proper use of Mockito and PowerMock
Spring validation was important in the order of Form and BindingResult
Spring Data JPA SQL log output
Filter the result of BindingResult [Spring]
Creating REST APIs with Spring JPA Data with REST and Lombok incredibly easy.
Determine the device type of smartphones, tablets, and PCs with Spring Mobile
[Spring Boot] Post files and other data at the same time [Axios]
Add @ManyToOne as part of the composite primary key in Hibernate JPA
(Determine in 1 minute) About the proper use of empty ?, blank? And present?
How to change the maximum and maximum number of POST data in Spark
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)
The story of encountering Spring custom annotation
OR search with Spring Data Jpa Specification
Spring with Kotorin --2 RestController and Data Class
After 3 months of Java and Spring training
Exists using Specification in Spring Data JPA
part of the syntax of ruby ​​on rails
Folding and unfolding the contents of the Recyclerview
About the initial display of Spring Framework
Item 72: Favor the use of standard exceptions
What is the data structure of ActionText?
Proper use of interface and abstract class
About the mechanism of the Web and HTTP
Investigate the behavior of JPA transaction timeout
The contents of the data saved by CarrierWave.
[Java] [Spring] Test the behavior of the logger
Acquisition of JSON data and rotation of values
I received the data of the journey (diary application) in Java and visualized it # 001
Part 2: Understand (roughly) the process flow of OAuth 2.0 Login supported by Spring Security 5
Get the class name and method name of Controller executed by HandlerInterceptor of Spring Boot
Sample code for search using QBE (Query by Example) of Spring Data JPA
Part 3: Understand (deeply) the process flow of OAuth 2.0 Login supported by Spring Security 5
Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement
[Order method] Set the order of data in Rails
Check the version of the JDK installed and the version of the JDK enabled
Think about the combination of Servlet and Ajax
Until data acquisition with Spring Boot + MyBatis + PostgreSQL
About the official start guide of Spring Framework
Add empty data to the top of the list
[Ruby on Rails] Until the introduction of RSpec
Compare the speed of the for statement and the extended for statement.
Spring Data JPA save select-insert is only insert