用Java Spring写一个连接数据库的外卖网站
时间: 2023-07-20 11:07:20 浏览: 219
JAVA开发的外卖系统源代码+数据库
好的,下面是一个简单的外卖网站的 Java Spring 连接数据库的示例代码。
首先,需要创建一个数据库,可以使用 MySQL 或者其他关系型数据库。
1. 创建数据库表
我们假设有三个表:用户表(users)、商家表(merchants)、订单表(orders),分别用于存储用户、商家和订单信息。
```sql
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
phone VARCHAR(20) NOT NULL,
address VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE merchants (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
phone VARCHAR(20) NOT NULL,
address VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE orders (
id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
merchant_id INT NOT NULL,
item VARCHAR(50) NOT NULL,
price DECIMAL(10,2) NOT NULL,
time TIMESTAMP NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (merchant_id) REFERENCES merchants(id)
);
```
2. 创建 Java Spring 项目
使用 Maven 或 Gradle 创建一个新的 Java Spring 项目。
3. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
```
4. 配置数据库连接
在 application.properties 文件中添加以下配置:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/food_delivery
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
```
其中,`jdbc:mysql://localhost:3306/food_delivery` 表示连接到名为 `food_delivery` 的数据库,`root` 是用户名,`root` 是密码。
5. 创建实体类
创建三个实体类:User、Merchant 和 Order,用于映射到数据库中的表。
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String phone;
@Column(nullable = false)
private String address;
// getter and setter methods
}
@Entity
@Table(name = "merchants")
public class Merchant {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String phone;
@Column(nullable = false)
private String address;
// getter and setter methods
}
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "merchant_id", nullable = false)
private Merchant merchant;
@Column(nullable = false)
private String item;
@Column(nullable = false)
private BigDecimal price;
@Column(nullable = false)
private LocalDateTime time;
// getter and setter methods
}
```
6. 创建 DAO
创建三个 DAO 接口:UserRepository、MerchantRepository 和 OrderRepository,用于操作数据库中的表。
```java
public interface UserRepository extends JpaRepository<User, Long> {
}
public interface MerchantRepository extends JpaRepository<Merchant, Long> {
}
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByUser(User user);
List<Order> findByMerchant(Merchant merchant);
}
```
7. 创建 Service
创建三个 Service 接口:UserService、MerchantService 和 OrderService,用于实现业务逻辑。
```java
public interface UserService {
void save(User user);
User findById(Long id);
List<User> findAll();
}
public interface MerchantService {
void save(Merchant merchant);
Merchant findById(Long id);
List<Merchant> findAll();
}
public interface OrderService {
void save(Order order);
Order findById(Long id);
List<Order> findAll();
List<Order> findByUser(User user);
List<Order> findByMerchant(Merchant merchant);
}
```
然后,创建 UserServiceImpl、MerchantServiceImpl 和 OrderServiceImpl 类,分别实现上述接口。
```java
@Service
@Transactional
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void save(User user) {
userRepository.save(user);
}
@Override
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
}
@Service
@Transactional
public class MerchantServiceImpl implements MerchantService {
private final MerchantRepository merchantRepository;
public MerchantServiceImpl(MerchantRepository merchantRepository) {
this.merchantRepository = merchantRepository;
}
@Override
public void save(Merchant merchant) {
merchantRepository.save(merchant);
}
@Override
public Merchant findById(Long id) {
return merchantRepository.findById(id).orElse(null);
}
@Override
public List<Merchant> findAll() {
return merchantRepository.findAll();
}
}
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
private final OrderRepository orderRepository;
public OrderServiceImpl(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Override
public void save(Order order) {
orderRepository.save(order);
}
@Override
public Order findById(Long id) {
return orderRepository.findById(id).orElse(null);
}
@Override
public List<Order> findAll() {
return orderRepository.findAll();
}
@Override
public List<Order> findByUser(User user) {
return orderRepository.findByUser(user);
}
@Override
public List<Order> findByMerchant(Merchant merchant) {
return orderRepository.findByMerchant(merchant);
}
}
```
8. 创建 Controller
创建三个 Controller 类:UserController、MerchantController 和 OrderController,用于处理 HTTP 请求。
```java
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
userService.save(user);
return ResponseEntity.ok(user);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
@GetMapping
public ResponseEntity<List<User>> getUsers() {
List<User> users = userService.findAll();
return ResponseEntity.ok(users);
}
}
@RestController
@RequestMapping("/merchants")
public class MerchantController {
private final MerchantService merchantService;
public MerchantController(MerchantService merchantService) {
this.merchantService = merchantService;
}
@PostMapping
public ResponseEntity<Merchant> createMerchant(@RequestBody Merchant merchant) {
merchantService.save(merchant);
return ResponseEntity.ok(merchant);
}
@GetMapping("/{id}")
public ResponseEntity<Merchant> getMerchant(@PathVariable Long id) {
Merchant merchant = merchantService.findById(id);
return ResponseEntity.ok(merchant);
}
@GetMapping
public ResponseEntity<List<Merchant>> getMerchants() {
List<Merchant> merchants = merchantService.findAll();
return ResponseEntity.ok(merchants);
}
}
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@PostMapping
public ResponseEntity<Order> createOrder(@RequestBody Order order) {
orderService.save(order);
return ResponseEntity.ok(order);
}
@GetMapping("/{id}")
public ResponseEntity<Order> getOrder(@PathVariable Long id) {
Order order = orderService.findById(id);
return ResponseEntity.ok(order);
}
@GetMapping
public ResponseEntity<List<Order>> getOrders() {
List<Order> orders = orderService.findAll();
return ResponseEntity.ok(orders);
}
@GetMapping("/user/{userId}")
public ResponseEntity<List<Order>> getOrdersByUser(@PathVariable Long userId) {
User user = new User();
user.setId(userId);
List<Order> orders = orderService.findByUser(user);
return ResponseEntity.ok(orders);
}
@GetMapping("/merchant/{merchantId}")
public ResponseEntity<List<Order>> getOrdersByMerchant(@PathVariable Long merchantId) {
Merchant merchant = new Merchant();
merchant.setId(merchantId);
List<Order> orders = orderService.findByMerchant(merchant);
return ResponseEntity.ok(orders);
}
}
```
9. 测试
启动应用程序,并使用 Postman 或其他 HTTP 客户端测试 API。
例如,使用以下请求创建一个用户:
```
POST http://localhost:8080/users
Content-Type: application/json
{
"name": "张三",
"phone": "13800138000",
"address": "北京市海淀区"
}
```
使用以下请求获取所有商家:
```
GET http://localhost:8080/merchants
```
使用以下请求获取某个用户的所有订单:
```
GET http://localhost:8080/orders/user/1
```
阅读全文