@Repository

初学spring boot,遇到的第一个坎就是好多注解都不知道作用,即使照猫画虎把代码敲出来运行成功,也没有些许成就感。原因其实很简单,我觉得自己还没真的学会。接下来就是找资料,理解原理与过程,不求理解的深度,起码也得把自己说服了。本文档是从英语文档翻译过来,外加了一些自己的理解,其中表述错误的地方还望留言指正。

源文档链接:http://zetcode.com/springboot/repository/


@Repository

@Repository注解修饰哪个类,则表明这个类具有对对象进行CRUD(增删改查)的功能,而且@Repository@Component注解的一个派生品,所以被@Repository注解的类可以自动的被@ComponentScan 通过路径扫描给找到。(这也在一定程度上解释了,为什么被@Repository注解的类也能@Autowired


Spring Boot @Repository 例子

下面这个例子将会讲述@Repository的用法,这个例子展示的是HTML表中的国家/地区列表。该程序使用的Spring boot 2.1.0版本。

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           ├───controller
│   │           │       MyController.java
│   │           ├───model
│   │           │       Country.java
│   │           ├───repository
│   │           │       CountryRepository.java
│   │           └───service
│   │                   CountryService.java
│   │                   ICountryService.java
│   └───resources
│       │   application.yml
│       │   import.sql
│       ├───static
│       │       index.html
│       └───templates
│               showCountries.ftl
└───test
    └───java

这是工程架构。

pom.xml


<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.0modelVersion>

    <groupId>com.zetcodegroupId>
    <artifactId>repositoryexartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>
    properties>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.0.RELEASEversion>
    parent>

    <dependencies>

        <dependency>
            <groupId>com.h2databasegroupId>
            <artifactId>h2artifactId>
            <scope>runtimescope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-freemarkerartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>

    dependencies>

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

project>

这是Maven build文件,h2依赖包括H2数据库驱动。
Spring boot starters是一系列非常方便的依赖描述符,它大大简化了maven的配置。spring-boot-start-parent包含spring boot application的常用配置;spring-boot-devtools包含spring boot的开发工具;spring-boot-starter-web支持classic和RESTFul的web应用程序启动;spring-boot-starter-web-freemarker是构建基于Freemarker模板引擎的web应用程序的启动器,它采用Tomcat作为默认的嵌入式容器。spring-boot-starter-data-jpa是基于Hibernate的Spring Data JPA的启动器。

resources/application.yml

server:
  port: 8086
  servlet:
    context-path: /SpringBootRepository

spring:
  main:
    banner-mode: "off"
  jpa:
    database: h2
    hibernate:
      dialect: org.hibernate.dialect.H2Dialect
      ddl-auto: create-drop

logging:
  level:
    org:
      springframework: ERROR

application.yml文件中,我们编写了spring boot应用程序的各种配置,服务器的端口和上下文的路径。完成这些设置后,我们通过localhost:8086/SpringBootRepository/访问应用程序。在该文件配置中关闭了banner-mode

resources/import.sql

INSERT INTO countries(name, population) VALUES('China', 1382050000);
INSERT INTO countries(name, population) VALUES('India', 1313210000);
INSERT INTO countries(name, population) VALUES('USA', 324666000);
INSERT INTO countries(name, population) VALUES('Indonesia', 260581000);
INSERT INTO countries(name, population) VALUES('Brazil', 207221000);
INSERT INTO countries(name, population) VALUES('Pakistan', 196626000);
INSERT INTO countries(name, population) VALUES('Nigeria', 186988000);
INSERT INTO countries(name, population) VALUES('Bangladesh', 162099000);
INSERT INTO countries(name, population) VALUES('Nigeria', 186988000);
INSERT INTO countries(name, population) VALUES('Russia', 146838000);
INSERT INTO countries(name, population) VALUES('Japan', 126830000);
INSERT INTO countries(name, population) VALUES('Mexico', 122273000);
INSERT INTO countries(name, population) VALUES('Philippines', 103738000);
INSERT INTO countries(name, population) VALUES('Ethiopia', 101853000);
INSERT INTO countries(name, population) VALUES('Vietnam', 92700000);
INSERT INTO countries(name, population) VALUES('Egypt', 92641000);
INSERT INTO countries(name, population) VALUES('Germany', 82800000);
INSERT INTO countries(name, population) VALUES('the Congo', 82243000);
INSERT INTO countries(name, population) VALUES('Iran', 82800000);
INSERT INTO countries(name, population) VALUES('Turkey', 79814000);
INSERT INTO countries(name, population) VALUES('Thailand', 68147000);
INSERT INTO countries(name, population) VALUES('France', 66984000);
INSERT INTO countries(name, population) VALUES('United Kingdom', 60589000);
INSERT INTO countries(name, population) VALUES('South Africa', 55908000);
INSERT INTO countries(name, population) VALUES('Myanmar', 51446000);
INSERT INTO countries(name, population) VALUES('South Korea', 68147000);
INSERT INTO countries(name, population) VALUES('Colombia', 49129000);
INSERT INTO countries(name, population) VALUES('Kenya', 47251000);
INSERT INTO countries(name, population) VALUES('Spain', 46812000);
INSERT INTO countries(name, population) VALUES('Argentina', 43850000);
INSERT INTO countries(name, population) VALUES('Ukraine', 42603000);
INSERT INTO countries(name, population) VALUES('Sudan', 41176000);
INSERT INTO countries(name, population) VALUES('Algeria', 40400000);
INSERT INTO countries(name, population) VALUES('Poland', 38439000);

创建完数据库和表后,执行上这个sql脚本用其中的数据填充表。

com/zetcode/model/Country.java

package com.zetcode.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;

@Entity
@Table(name = "countries")
public class Country {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private int population;

    public Country() {
    }

    public Country(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Country country = (Country) o;
        return population == country.population &&
                Objects.equals(id, country.id) &&
                Objects.equals(name, country.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, population);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Country{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", population=").append(population);
        sb.append('}');
        return sb.toString();
    }
}

Country是一个实例,每一个实力必须包含这两个注解@Entity@Id。以前,我们必须将ddl-auto选项设置成create-drop表明Hibernate将从这个实例中构建表。

@Entity
@Table(name = "countries")
public class Country {

@Entity注解指明该类是一个实例并且将会映射成一个数据库表。@Table注解指定了这个数据库表的名字。

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Id指定了这个实例的主键,@GeneratedValue规定了这个主键的值得生成策略。

com/zetcode/repository/CountryRepository.java

package com.zetcode.repository;

import com.zetcode.bean.Country;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CountryRepository extends CrudRepository<Country, Long> {

}

CountryRepository@Repository注解,通过继承springCrudRepository,CountryRepository拥有了对数据进行CRUD的方法,包括findAll()

com/zetcode/service/ICountryService.java

package com.zetcode.service;

import com.zetcode.bean.Country;
import java.util.List;

public interface ICountryService {

    public List<Country> findAll();
}

ICountryService接口中定义了一个findall()方法。

com/zetcode/service/CountryService.java

package com.zetcode.service;

import com.zetcode.model.Country;
import com.zetcode.repository.CountryRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CountryService implements ICountryService {

    @Autowired
    private CountryRepository repository;

    @Override
    public List<Country> findAll() {

        var countries = (List<Country>) repository.findAll();
        return countries;
    }
}

CountryService继承ICountryService并实现findAll()方法。

@Autowired
private CountryRepository repository;

@Autowired注解CountryRepository

@Override
public List findAll() {
    var countries = (List) repository.findAll();
    return countries;
}

findAll()方法的返回值是数据库表中所有国家的列表。

com/zetcode/controller/MyController.java

package com.zetcode.controller;

import com.zetcode.model.Country;
import com.zetcode.service.ICountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

@Controller
public class MyController {

    @Autowired
    ICountryService countryService;

    @RequestMapping("/showCountries")
    public ModelAndView findCities() {

        var countries = (List<Country>) countryService.findAll();

        var params = new HashMap<String, Object>();
        params.put("countries", countries);

        return new ModelAndView("showCountries", params);
    }
}

MyController接收一个来自客户端的请求。

@Controller
public class MyController {

MyController这个controller被@controller注解。

@Autowired
ICountryService countryService;

ICountryService被注入成员变量countryService中。

var countries = (List<Country>) countryService.findAll();

我们用findAll()方法取回了所有的国家。

Application.java

package com.zetcode;

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

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

Application是启动Spring boot应用程序的入口。@SpringBootApplication注解支持自动配置和组件扫描。它可以代替@Configuration@ EnableAutoConfiguration@ComponentScan三个注解的功能。

你可能感兴趣的:(java,Spring,Boot学习笔记)