[JAVA] DB access using repository with SpringData.

Convenient interface to automatically create access to DB

JPA repository is a convenient interface that automatically implements CRUD to DB. Once the environment is set, the DB access function can be implemented with a considerably small amount of code, but it is quite difficult to set the environment, so I summarized it.

Introduce SpringData library

Refer to the article below until the JDBC template works for the time being.

SpringDataJPA Access 1 SpringDataJPA Access 2

Create a repository interface

Create the repository body.

MyPesononalDataDaoRepository.java


package com.tsugaruinfo.repository;

@Repository
public interface MyPesononalDataDaoRepository
	extends JpaRepository<Mypersonaldata, Integer> {

}

It's just an interface. There is no need to implement the contents.

Register repository in DI

Register the repository in the bean configuration file.

appllicatio-config.xml


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



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


Two points

1. Add namespace

Added tx and jpa to namespace

application-config.xml


	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"

In the schema

application-config.xml


		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"

To make JPA and Transaction beans available. This is because Transaction is used by JPA without permission when creating a repository.

2. Add repository package and TransactionManager

This is the main DI registration Register the jpa repository package and a bean called transactionManager.

appliction-config.xml


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

Please change "com.tsugaruinfo.repository" to your own package when you actually use it. The repository is now registered in the DI container.

Inject with @Autowired

This time it is an implementation in Servlet. (Well, as in the textbook ...)

BeanAutowiredFilterServlet.java


public class BeanAutowiringFilterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	@Override
	public void init() throws ServletException {
		super.init();
		SpringBeanAutowiringSupport
			.processInjectionBasedOnCurrentContext(this);
	}

This ** SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this); ** command is the key to using the @Autowired annotation. The moment this command is executed, the Bean registered in DI is injected into the annotated variable.

I think that the variable to be injected is a field of the class, so it may be good to execute it in the constructor. This time, set up a parent class and execute it with the initialization method of the Servlet.

With Spring Boot It seems to run automatically with the annotation @SpringBootApplication

Inject and materialize

MyPersonalDataServlet.java


@WebServlet("/person")
public class MyPersonalDataServlet extends BeanAutowiringFilterServlet {
	private static final long serialVersionUID = 1L;
       

	@Autowired
	MyPesononalDataDaoRepository repository;

Injected into a Servlet field. JPA and DI container will materialize without new.

Run immediately

Let's run it in a Servlet. Get all the contents of DB

MyPersonalDataServlet.java


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		List<Mypersonaldata> list = repository.findAll();

		request.setAttribute("entities", list);

		response.getWriter().append("Served at: ").append(request.getContextPath());

		request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
	}

index.jsp


<!DOCTYPE html>

<%@ page import="java.util.List" %>
<%@ page import="com.tsugaruinfo.model.Mypersonaldata" %>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>
	<head>
		<meta charset="utf-8">
		<title>JPA Sample1</title>
	</head> 
	<body>
		<h1>Welcome to JPA Sample!</h1>
		
		<form method="post" action="person">
		<table>
			<tr><td>Name:Input<input type ="text" name="name"></td></tr>
			<tr><td>Mail:Input<input type ="text" name="mail"></td></tr>
			<tr><td>Age:Input<input type ="text" name="age"></td></tr>
			<tr><td><input type ="submit" value="add to"></td></tr>
		</table>
		</form>
		<c:url value="/showMessage.html" var="messageUrl" />
		<a href="${messageUrl}">Click to enter</a>
		<ol>
		 
			<% for(Object entity : (List)request.getAttribute("entities")){ %>
				<li><%=entity %></li>
			<% } %>
		</ol>
	</body>
</html>

result

image.png

I was able to confirm that the repository is working properly.

Recommended Posts

DB access using repository with SpringData.
DB access using Exposed
Using Pair with OpenJDK
Try DB connection with Java
Spring with Kotorin --8 Repository layer
DB programming using EclipseLink part1
Access Apache Kafka with Micronaut
Connect to DB with Java
Using Mapper with Java (Spring)
Error with db: migrate: reset
Using PlantUml with Honkit [Docker]