现在我们有了环境、项目结构和依赖配置,接下来进入核心开发阶段。以“库存查询接口”为例,完整演示Java新建Web项目后端开发流程。
步骤1:创建实体类(Model)
定义库存数据结构:
package com.example.demoslice.model;
import jakarta.persistence.;
import lombok.Data;
@Entity
@Table(name = "inventory")
@Data
public class Inventory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int quantity;
private String location;
}
? 为什么用Lombok?:`@Data` 自动生成getter/setter/toString/equals/hashCode,避免200+行样板代码。这是现代Java开发的标配。
步骤2:创建Repository(DAO层)
package com.example.demoslice.dao;
import com.example.demoslice.model.Inventory;
import org.springframework.data.jpa.repository.JpaRepository;
public interface InventoryRepository extends JpaRepository<Inventory, Long> {
// 自定义查询方法
java.util.List<Inventory> findByQuantityLessThan(int threshold);
}
步骤3:创建Service层
package com.example.demoslice.service;
import com.example.demoslice.dao.InventoryRepository;
import com.example.demoslice.model.Inventory;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class InventoryService {
private final InventoryRepository inventoryRepository;
public InventoryService(InventoryRepository inventoryRepository) {
this.inventoryRepository = inventoryRepository;
}
public List<Inventory> getAllItems() {
return inventoryRepository.findAll();
}
public Optional<Inventory> getItemById(Long id) {
return inventoryRepository.findById(id);
}
public Inventory addItem(Inventory item) {
return inventoryRepository.save(item);
}
public void deleteItem(Long id) {
inventoryRepository.deleteById(id);
}
public List<Inventory> getLowStockItems(int threshold) {
return inventoryRepository.findByQuantityLessThan(threshold);
}
}
步骤4:创建Controller层
package com.example.demoslice.controller;
import com.example.demoslice.model.Inventory;
import com.example.demoslice.service.InventoryService;
import org.springframework.web.bind.annotation.;
import java.util.List;
@RestController
@RequestMapping("/api/inventory")
public class InventoryController {
private final InventoryService inventoryService;
public InventoryController(InventoryService inventoryService) {
this.inventoryService = inventoryService;
}
@GetMapping
public List<Inventory> getAllItems() {
return inventoryService.getAllItems();
}
@GetMapping("/{id}")
public Inventory getItemById(@PathVariable Long id) {
return inventoryService.getItemById(id)
.orElseThrow(() -> new ResourceNotFoundException("库存项不存在: " + id));
}
@PostMapping
public Inventory addItem(@RequestBody Inventory item) {
return inventoryService.addItem(item);
}
@DeleteMapping("/{id}")
public void deleteItem(@PathVariable Long id) {
inventoryService.deleteItem(id);
}
}
步骤5:配置数据库连接
在 src/main/resources/application.yml 中添加:
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
username: root
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
dialect: org.hibernate.dialect.MySQL8Dialect
启动项目并测试接口
运行主类 DemoSliceApplication,在浏览器访问:
http://localhost:8080/api/inventory
若返回空数组 [],说明接口已通!
使用Postman添加测试数据:
再次访问GET接口,应返回刚才添加的数据。
常见开发问题排查
问题:启动时报“Failed to configure a DataSource”
原因:未配置数据库或JPA自动配置失败
解决方案:
- 检查application.yml中的数据库配置是否正确
- 确认MySQL服务已启动
- 在主类上添加
@EnableJpaRepositories 和 @EntityScan
- 临时禁用JPA:在application.yml添加
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
通过以上步骤,你已成功完成Java新建Web项目的核心开发流程。下一步,我们将深入安全认证设计。