Demo project for Spring Boot 【1】spring-boot-starter【2】Accessing Data with JPA

这篇博客介绍了一个使用Spring Boot和JPA访问数据库的示例项目。内容包括创建Spring Boot项目,添加相关依赖,配置数据库连接,定义实体类,创建Repository,服务层和控制器。特别地,详细解释了Customer类的JPA注解及其作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建一个Spring Boot项目来展示如何使用JPA访问数据涉及到几个关键步骤。以下是基于你给出的项目名称和关键点的一个简单指南:

  1. 项目设置:
    • 打开你的IDE(例如IntelliJ IDEA或Eclipse)。
    • 创建一个新的Spring Boot项目。
    • 选择合适的Spring Boot版本(例如2.x)。
  2. 添加依赖:
    • pom.xml文件中,添加以下依赖(以Maven为例):
    xml`<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>
        <!-- 其他依赖 -->
    </dependencies>`
    
  3. 配置数据库:
    • src/main/resources目录下,找到application.propertiesapplication.yml文件。
    • 配置数据库连接,例如:
    properties`spring.datasource.url=jdbc:mysql://localhost:3306/yourdb?useSSL=false&serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=rootpassword
    spring.jpa.hibernate.ddl-auto=update`
    
  4. 定义实体:
    • 创建一个Java类来表示你的数据库表。例如,如果你有一个User表,可以创建一个User类。
    java`@Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        // 其他字段和getter/setter方法...`
    
  5. 创建Repository:
    • 继承JpaRepository接口来创建你的数据访问对象。例如:
    java`public interface UserRepository extends JpaRepository<User, Long> { }`
    
  6. 创建服务层:
    • 创建一个服务类来封装与数据库的交互逻辑。例如:
    java`@Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;
        public List<User> getAllUsers() { return userRepository.findAll(); }`
    
  7. 创建控制器:
    • 创建一个控制器类来处理HTTP请求。例如:
    java`@RestController
    public class UserController {
        @Autowired
        private UserService userService;
        @GetMapping("/users")
        public List<User> getAllUsers() { return userService.getAllUsers(); }`
    
  8. 运行应用:
    • 运行你的Spring Boot应用。如果你使用Maven,可以在命令行中输入mvn spring-boot:run。如果一切顺利,你应该能够通过访问http://localhost:8080/users来看到所有的用户数据。
      Here you have a Customer class with three attributes: id, firstName, and lastName. You also have two constructors. The default constructor exists only for the sake of JPA. You do not use it directly, so it is designated as protected. The other constructor is the one you use to create instances of Customer to be saved to the database.
      The Customer class is annotated with @Entity, indicating that it is a JPA entity. (Because no @Table annotation exists, it is assumed that this entity is mapped to a table named Customer.)
      The Customer object’s id property is annotated with @Id so that JPA recognizes it as the object’s ID. The id property is also annotated with @GeneratedValue to indicate that the ID should be generated automatically.
      The other two properties, firstName and lastName, are left unannotated. It is assumed that they are mapped to columns that share the same names as the properties themselves.
      The convenient toString() method print outs the customer’s properties.

这里有一个Customer类,它有三个属性:id、firstName和lastName。您还有两个构造函数。默认构造函数的存在只是为了JPA。您不直接使用它,所以它被指定为受保护的。另一个构造函数是用于创建要保存到数据库中的Customer实例的构造函数。
Customer类用@Entity注释,表明它是一个JPA实体。(由于不存在@Table注释,因此假定此实体映射到名为Customer的表。)
Customer对象的id属性用@id注释,以便JPA将其识别为对象的id。id属性也用@GeneratedValue进行注释,以指示应该自动生成id。
其他两个属性,firstName和lastName没有注释。假设它们被映射到与属性本身同名的列。
方便的toString()方法打印出客户的属性。

在这里插入图片描述

package com.example.accessingdatajpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class AccessingDataJpaApplication {
   

  private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class);

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

  @Bean
  public CommandLineRunner demo(CustomerRepository repository) {
   
    return (args) -> {
   
      // save a few customers
      repository.save(new Customer("Jack", "Bauer"));
      repository.save(new Customer("Chloe", "O'Brian"));
      repository.save(new Customer("Kim", "Bauer"));
      repository.save(new Customer("David", "Palmer"));
      repository.save(new Customer("Michelle", "Dessler"));

      // fetch all customers
      log.info("Customers found with findAll():");
      log.info("-------------------------------");
      for (Customer customer : repository.findAll()) {
   
        log.info(customer.toString());
      }
      log.info("");

      // fetch an individual customer by ID
      Customer customer = repository.findById(1L);
      log.info("Customer found with findById(1L):");
      log.info("--------------------------------");
      log.info(customer.toString());
      log.info("");

      // fetch customers by last name
      log.info("Customer found with findByLastName('Bauer'):");
      log.info("--------------------------------------------");
      repository.findByLastName("Bauer").forEach(bauer -> {
   
        log.info(bauer.toString());
      });
      // for (Customer bauer : repository.findByLastName("Bauer")) {
   
      //  log.info(bauer.toString());
      // }
      log.info("");
    };
  }

}
package com.example.accessingdatajpa;

import 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值