Spring Boot @Repository教程显示了如何在 Spring 应用中使用@Repository注解。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
@Repository
@Repository是 Spring 注解,指示装饰的类是存储库。 存储库是一种用于封装存储,检索和搜索行为的机制,该机制模仿对象的集合。 它是@Component注解的一种特殊功能,允许通过类路径扫描自动检测实现类。
@ComponentScan确保找到用@Component和其派生词包括@Repository装饰的类并将其注册为 Spring Bean。 @ComponentScan自动包含在@SpringBootApplication中。
Spring Boot @Repository示例
以下应用演示了@Repository的用法。 它向用户显示 HTML 表中的国家/地区列表。 在本应用中,我们使用 Spring Boot 版本 2.1.0。
pom.xmlsrc├───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
<?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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zetcode</groupId><artifactId>repositoryex</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.0.RELEASE</version></parent><dependencies><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
这是 Maven 构建文件。 h2依赖项包括 H2 数据库驱动程序。
Spring Boot 启动器是一组方便的依赖项描述符,可以极大地简化 Maven 配置。 spring-boot-starter-parent具有 Spring Boot 应用的一些常用配置。 spring-boot-devtools包含一些 Spring Boot 开发者工具。 spring-boot-starter-web支持经典和 RESTFul Web 应用。 spring-boot-starter-web-freemarker是使用 Freemarker 模板引擎构建 Web 应用的入门工具。 它使用 Tomcat 作为默认的嵌入式容器。 spring-boot-starter-data-jpa是将 Spring Data JPA 与 Hibernate 结合使用的入门工具。
spring-boot-maven-plugin在 Maven 中提供了 Spring Boot 支持,使我们可以打包可执行的 JAR 或 WAR 档案。 它的spring-boot:run目标运行 Spring Boot 应用。
resources/application.yml
server:port: 8086servlet:context-path: /SpringBootRepositoryspring:main:banner-mode: "off"jpa:database: h2hibernate:dialect: org.hibernate.dialect.H2Dialectddl-auto: create-droplogging:level:org:springframework: ERROR
在application.yml文件中,我们编写了 Spring Boot 应用的各种配置设置。 port设置服务器端口和context-path上下文路径(应用名称)。 完成这些设置后,我们可以通过localhost:8086/SpringBootRepository/访问该应用。 使用banner-mode属性,我们可以关闭 Spring 横幅。
JPA database值指定要操作的目标数据库。 在本例中,我们指定了 Hibernate 方言org.hibernate.dialect.H2Dialect。 ddl-auto是数据定义语言模式; create-drop选项将自动创建和删除数据库模式。
H2 数据库在内存中运行。 另外,我们将 spring 框架的日志记录级别设置为ERROR。 在application.yml文件位于中src/main/resources目录。
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);
模式是由 Hibernate 自动创建的。 之后,将执行import.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;}@Overridepublic 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);}@Overridepublic int hashCode() {return Objects.hash(id, name, population);}@Overridepublic 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;@Repositorypublic interface CountryRepository extends CrudRepository<Country, Long> {}
CountryRepository用@Repository注解修饰。
通过从 Spring CrudRepository扩展,我们为数据库实现了一些方法,包括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;@Servicepublic class CountryService implements ICountryService {@Autowiredprivate CountryRepository repository;@Overridepublic List<Country> findAll() {var countries = (List<Country>) repository.findAll();return countries;}}
CountryService包含findAll()方法的实现。
@Autowiredprivate CountryRepository repository;
CountryRepository注入了@Autowired注解。
@Overridepublic List<Country> findAll() {var countries = (List<Country>) 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;@Controllerpublic class MyController {@AutowiredICountryService 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处理来自客户端的请求。
@Controllerpublic class MyController {
控制器带有@Controller注解。
@AutowiredICountryService countryService;
ICountryService注入到countryService字段中。
var countries = (List<Country>) countryService.findAll();
从服务对象中,我们使用findAll()方法检索所有国家。
var params = new HashMap<String, Object>();params.put("countries", countries);return new ModelAndView("showCountries", params);
处理和国家列表一起发送到showCountries.ftl模板文件。 我们已经在 Maven POM 文件中提供了 Freemarker 依赖项; 因此,Spring Boot 会找出视图的扩展名。
resources/static/index.html
<!DOCTYPE html><html><head><title>Home page</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><p><a href="showCountries">Show countries</a></p></body></html>
这是主页。 它包含一个获取所有国家的链接。
resources/templates/showCountries.ftl
<!DOCTYPE html><html><head><title>Show countries</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><h2>List of countries</h2><table><tr><th>Id</th><th>Name</th><th>Population</th></tr><#list countries as country><tr><td>${country.id}</td><td>${country.name}</td><td>${country.population}</td></tr></#list></table></body></html>
这是showCountries.ftl模板文件。 使用#list指令,我们显示列表中的所有项目。
com/zetcode/Application.java
package com.zetcode;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
Application是设置 Spring Boot 应用的入口。 @SpringBootApplication注解启用自动配置和组件扫描。 它是@Configuration,@EnableAutoConfiguration和@ComponentScan注解的便捷注解。
$ mvn -q spring-boot:run
我们运行该应用。
在本教程中,我们展示了如何在 Spring 应用中使用@Repository注解。 您可能也对相关教程感兴趣: Spring Boot @Controller教程, Spring Boot @RequestParam教程和 Java 教程,或列出全部 Spring Boot 教程。
