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

The difficulty of setting is quite high.

Continued from last time

For the time being, I used Spring to connect to the DB. From here, we will use a full-fledged DB operation framework called 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 ** ← So far **
  1. In addition, what is required for JPA ** ← From here ** ・ Spring Data JPA library ・ Entity class -Persistence.xml file (Java EJB function) -Bean configuration file (xml) -Execution class with main method

Add library

Add library as usual. When you use new features in Spring, you usually edit the library.

pom.xml


		<!-- Spring Data JPA -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
		</dependency>
		
		<!-- Spring ORM -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>

After saving ** Maven → update Project **

Entity class

Click here for how to create an entity class from a table. wrap up Right click and convert from configuration to JPA project. When it becomes a JPA project, an entity will be automatically generated from the table.

https://qiita.com/shibafu/items/39f3f5d6e63dda16bb12

It's really hard to see,

image.png

When the Entity is created, add an annotation such as @Id and pick up the error. You may want to use ** lombok ** and omit the getter setter in @Data

Auto-implemented entity class

image.png

Creating persistence.xml

Create a META-INF folder in src / main / resources and a persistance.xml file in it. It seems to be a Java-EE function called ** persistence file ** (If you created it with JPA, it is created in src / main / java, so move it)

Sketch src/main/resources/   |   |---META-INF   |    |   |    |--persistance.xml   |---bean.xml   |---database.properties

persitance.xml


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
   xmlns="http://xmlns.jcp.org/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
		http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
   
	<persistence-unit name="persistance-unit">
		
		<!--HibernatePersistance definition-->
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<class>model.Mypersonaldata</class>
		
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
			
			<property name="hibernate.hbm2ddl.auto" value="create" />
			
				<!--Driver properties-->
				<property name="javax.persistance.jdbc.driver"
					value="${jdbc.driverClassname}" />
				<property name="javax.persistance.jdbc.url"
					value="${jdbc.url}" />
				<property name="javax.persistance.jdbc.user"
					value="${jdbc.username}" />
				<property name="javax.persistance.jdbc.password"
					value="${jdbc.password}" />	
		</properties>
	</persistence-unit>
</persistence>

image.png

Creating a bean configuration file

Finally, create a bean configuration file. Namespace xmlns = http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/spring-jpa.xsd Add Register the entity manager with the DI container.

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/data/jpa
	 http://www.springframework.org/schema/data/spring-jpa.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>

	<!--EntityManager settings-->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="generateDdl" value="true" />
			</bean>
		</property>
	</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>

	
		<!--JPA Repository settings-->
	<jpa:repositories base-package="com.TsugaruInfo.repository" />
	
     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>


Let's run

Let's put the entity manager in the main class and perform JPA functions!

App.java



public class App{
	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);
	
		context = new ClassPathXmlApplicationContext("bean.xml");
		
		LocalContainerEntityManagerFactoryBean factory =
				context.getBean(LocalContainerEntityManagerFactoryBean.class);
		manager = factory.getNativeEntityManagerFactory().createEntityManager();
		
		Mypersonaldata data = manager.find(Mypersonaldata.class, 1);
		
			System.out.println(data);
	
	}
}

Run this from Java Application

image.png

At the bottom, you can see the data read from postgresql.

Summary.

Well, with Spring-Boot, this procedure is all done automatically, I couldn't keep the basics down and it stopped working, so for reference.

Recommended Posts

Until the use of Spring Data and JPA Part 2
Until the use of Spring Data and JPA Part 1
[spring] Let's use Spring Data JPA
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
Spring Data JPA Entity cross-reference and its notes
[For beginners] DI ~ The basics of DI and DI in Spring ~
Compatibility of Spring JDBC and MyBatis with Spring Data JDBC (provisional)
Make the where clause variable in Spring Data JPA
The story of raising Spring Boot from 1.5 series to 2.1 series part2
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-
[Spring Data JPA] Custom ID is assigned in a unique sequence at the time of registration.
Part 4: Customize the behavior of OAuth 2.0 Login supported by Spring Security 5
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]
(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 operation of next () and nextLine ()
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
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