简介

实际开发过程中,我们对数据库大多都是CRUD(增删改查),就普通的单表来说,大多sql语句都是类似的,我们需要做大量重复的数据库操作来完成业务逻辑

看完本章你将会知道

如何对一个数据库进行操作,查询出一个数据,进行简单的CRUD

配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.boot</groupId>
    <artifactId>demo-jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo-jpa</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/boot?characterEncoding=utf-8&useSSL=false
  jpa:
    show-sql: true

sql脚本

CREATE TABLE `tab_jpa` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `msg` varchar(255) DEFAULT NULL,
  `remark` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;

HelloJpa

项目结构

image.png

TabJpa

package com.boot.dataObject;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name="tab_jpa")
public class TabJpa {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String msg;
    private String remark;
}

TabJpaRpository

package com.boot.repository;

import com.boot.dataObject.TabJpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface TabJpaRpository extends JpaRepository<TabJpa,Integer> {
	@Query("from TabJpa t where t.msg=:msg")
    TabJpa findTabJpa(@Param("msg") String msg);
}

TabJpaService

package com.boot.service;

import com.boot.dataObject.TabJpa;

import java.util.List;

public interface TabJpaService {
    /**
     * 新增or更新
     */
    TabJpa save(TabJpa model);

    /**
     * 删除
     */
    void deleteById(Integer id);


    /**
     * Load查询
     */
    TabJpa findById(Integer id);



    /**
     *  查询
     */
    List<TabJpa> findAll( );
	
	  /**
     *  hql查询
     */
    TabJpa findTabJpa(@Param("msg") String msg);

}

TabJpaServiceImpl

package com.boot.service.impl;

import com.boot.dataObject.TabJpa;
import com.boot.repository.TabJpaRpository;
import com.boot.service.TabJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TabJpaServiceImpl implements TabJpaService {
    @Autowired
    private TabJpaRpository tabJpaRpository;

    @Override
    public TabJpa save(TabJpa model) {
        return tabJpaRpository.save(model);
    }

    @Override
    public void deleteById(Integer id) {
        TabJpa tabJpa = this.findById(id);
        tabJpaRpository.delete(tabJpa);
    }

    @Override
    public TabJpa findById(Integer id) {
        return tabJpaRpository.findById(id).get();
    }

    @Override
    public List<TabJpa> findAll() {
        return tabJpaRpository.findAll();
    }
	@Override
    public TabJpa findTabJpa(String msg) {
        return tabJpaRpository.findTabJpa(msg);
    }
}

DemoJpaApplication

package com.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoJpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoJpaApplication.class, args);
    }
}

DemoJpaApplicationTest

package com.boot;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoJpaApplicationTest {

    @Test
    public void main() {
        log.info("test");
    }
}

TabJpaServiceTest

package com.boot.service;

import com.boot.DemoJpaApplicationTest;
import com.boot.dataObject.TabJpa;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

@Slf4j
@Component
public class TabJpaServiceTest extends DemoJpaApplicationTest {
    @Autowired
    private TabJpaService tabJpaService;
    @Test
    public void save() {
        TabJpa model = new TabJpa();
        model.setMsg("firstJpa");
        model.setRemark(new Date().toString());
        TabJpa save = tabJpaService.save(model);
        log.info("save:{}",save);
    }

    @Test
    public void deleteById() {
        tabJpaService.deleteById(1);
    }

    @Test
    public void findById() {
        TabJpa jpa = tabJpaService.findById(1);
        log.info("jpa:{}",jpa);
    }

    @Test
    public void findAll() {
        List<TabJpa> all = tabJpaService.findAll();
        log.info("all:{}",all);
    }
	
	 @Test
    public void findTabJpa() {
        TabJpa jpa = tabJpaService.findTabJpa("a");
        log.info("jpa:{}",jpa);
    }
}

git地址

gitee

Last Updated: 6/13/2019, 7:10:41 PM