What is JPA
JPA (Java Persistence API) is a Java persistence specification officially proposed by Sun. It provides Java developers with an object/association mapping tool to manage relational data in Java applications. His appearance is mainly to simplify existing persistent development efforts and integrate ORM technology
Spring Data JPA is a JPA application framework encapsulated by Spring based on ORM framework and JPA specifications, which allows developers to access and operate data using minimalist code. It provides common functions including additions, deletions, modifications and searches, and is easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency!
Use JdbcTemplate to access database in Spring Boot
Data source configuration
First, in order to connect to the database, you need to introduce jdbc support, and the following configuration is introduced in pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency>
Embedded database support
Embedded databases are commonly used in development and testing environments. Spring-Boot provides automatic configuration embedded databases including H2, HSQL, and Derby, which you do not need to provide any connection configuration to use.
Such as h2's dependency
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope></dependency>
MySQL database support
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version></dependency>
Edit configuration information
Configure data source information in src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver
Use JdbcTemplate to operate the database
Spring's JdbcTemplate is automatically configured, you can use @Autowired to inject it into your own bean.
Implementation of data access operations defined in DemoService through JdbcTemplate
@Servicepublic class DemoSerivce { @Autowired private JdbcTemplate jdbcTemplate; public void create(String name, Integer age) { jdbcTemplate.update("insert into DEMO(NAME, AGE) values(?, ?)", name, age); } public void deleteByName(String name) { jdbcTemplate.update("delete from DEMOwhere NAME = ?", name); } public Integer getAllDemo() { return jdbcTemplate.queryForObject("select count(1) from DEMO", Integer.class); } public void deleteAllDemo() { jdbcTemplate.update("delete from DEMO"); }}Create unit test cases for UserService to verify the correctness of database operations by creating, deleting, and querying.
Test cases need to increase dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency>
Test code
@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Main.class)public class ApplicationTests { @Autowired private DemoSerivce demoSerivce; @Before public void setUp() { // Prepare, clear the table demoSerivce.deleteAllDemo(); } @Test public void test() throws Exception { // Insert 5 demoSerivce.create("a", 1); demoSerivce.create("b", 2); demoSerivce.create("c", 3); demoSerivce.create("d", 4); demoSerivce.create("e", 5); Assert.assertEquals(5, demoSerivce.getAllDemo().intValue()); demoSerivce.deleteByName("a"); demoSerivce.deleteByName("e"); // Looking at the database, there should be 5 Assert.assertEquals(3, demoSerivce.getAllDemo().intValue()); }}Using Spring-data-jpa in Spring Boot
In order to solve these large amounts of boring data operation statements, the first thing we think of is to use an ORM framework, such as: Hibernate. After integrating Hibernate, we finally map data changes to the database table in the way of manipulating Java entities.
In order to solve the basic "addition, deletion, modification and search" operation of abstracting each Java entity, we usually encapsulate a template in a generic way to abstract and simplify it, but this is still not very convenient. We need to write an interface inherited from the generic template in a specific entity, and then write an implementation of the interface. Although some basic data access can be reused well, there will be a bunch of interfaces and implementations for each entity in the code structure.
Due to the implementation of templates, the layers of these specific entities have become very "thin". Some specific entities' implementations may be completely a simple proxy for templates, and often such implementation classes may appear on many entities. The emergence of Spring-data-jpa can make such an already "thin" data access layer become a way to write a layer of interfaces.
How to use
Add dependencies
<dependency <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
Edit configuration information
Configure data source information in src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.hbm2ddl.auto is a configuration property of hibernate. Its main function is to automatically create, update, and verify the database table structure. Several configurations of this parameter are as follows
Create an entity
@Entitypublic class DemoEntity { @Id @GeneratedValue private long id; private String title; private String content; public DemoEntity() { } public DemoEntity(String title, String content) { this.title = title; this.content = content; } // get set omitted}Create a DAO
public interface DemoRepository extends JpaRepository<DemoEntity, Long> { DemoEntity findByTitle(String title); DemoEntity findByTitleAndContent(String title, String content);// @Query("select u from DemoEntity u where u.content=:content") @Query("from DemoEntity u where u.content=:content") DemoEntity sqlFind(@Param("content") String content);}Do not write table names in SQL, but entity names, it will automatically convert them into table names.
Create a query by parsing the method name
The above findByTitle(String title) and findByTitleAndContent(String title, String content) are not written, but the framework will automatically create SQL according to the name of the above pair.
Unit Testing
@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Main.class)public class UnitTest { @Autowired DemoRepository demoRepository; @Test public void test() { for(int i=0;i<10;i++) { demoRepository.save(new DemoEntity("title"+i, "content"+i)); } Assert.assertEquals(10, demoRepository.findAll().size()); } @Test public void testfindbytitle() { DemoEntity res = demoRepository.findByTitle("title8"); Assert.assertEquals("title8", res.getTitle()); } @Test public void testfindbytitleandcontent() { DemoEntity res = demoRepository.findByTitleAndContent("title9", "content9"); Assert.assertEquals("title9", res.getTitle()); Assert.assertEquals("content9", res.getContent()); } @Test public void testsqlFind() { DemoEntity res = demoRepository.sqlFind("content7"); Assert.assertEquals("content7", res.getContent()); }}Summarize
The above is the editor’s introduction to the use of Spring-data-jpa in Spring boot to facilitate and quickly access the database. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!