gpt4 book ai didi

java - 如何向数据库表中添加两个表组合的条目

转载 作者:行者123 更新时间:2023-12-02 08:40:11 28 4
gpt4 key购买 nike

我有 UserCustomer 类,它们与关系 @OneToOne 一起使用。因此,Customer 有一个 POST 方法,执行时,我在 user 表中创建一个条目,然后在 customer 中创建一个条目 表。我不知道如何在表中连接它们,即在customer表中的user_id字段中,我不知道如何将 >我刚刚创建的用户的id

所有用户字段也属于客户

我使用Spring-MVC + Hibernate + Jpa + PostgreSQL

这是我使用 Spring 的第一个大型项目。

用户:

package com.tinychiefdelights.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.persistence.*;

@ApiModel
@Data
@Entity
@Table(name = "pg_user", schema = "public")
public class User {

public User() { // Пустой конструктор для Hibernate

}

public User(String name, String lastName, String role,
String login, String password) { // Базовый конструктор

this.name = name;
this.lastName = lastName;
this.role = role;
this.login = login;
this.password = password;
}


// Поля
private @Id
@GeneratedValue
Long id;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

@Column(name = "role")
private String role;

@Column(name = "name")
private String name;

@Column(name = "last_name")
private String lastName;
}

客户:

package com.tinychiefdelights.model;

import com.fasterxml.jackson.annotation.*;
import com.tinychiefdelights.repository.CustomerRepository;
import lombok.Data;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import javax.persistence.*;
import java.util.List;

@Data
@Entity
@Table(name = "customer", schema = "public")
public class Customer {

public Customer() { // Пустой конструктор для Hibernate

}


// Поля

// name, lastName, login, password берем от класса User через связи;

private @Id
@GeneratedValue
Long id;

@Column(name = "wallet")
private double wallet;


//Relationships
//
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "id") // Join without Customer in User class
@NotFound(action = NotFoundAction.IGNORE)
private User user;

//Лист заказов
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
@JsonIgnore // Таким образом я предотвратил рекурсию
private List<Order> orderList;
}

客户服务:

package com.tinychiefdelights.service;

import com.tinychiefdelights.model.Customer;
import com.tinychiefdelights.model.User;
import com.tinychiefdelights.repository.CustomerRepository;
import com.tinychiefdelights.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerService extends UserService {


private CustomerRepository customerRepository;

private UserRepository userRepository;


@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}

@Autowired
public void setCustomerRepository(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}



// Методы
//
public Customer addCustomer(User newUser, Customer newCustomer){
userRepository.save(newUser);
return customerRepository.save(newCustomer);
}

客户 Controller :

package com.tinychiefdelights.controller;

import com.tinychiefdelights.exceptions.NotFoundException;
import com.tinychiefdelights.model.Customer;
import com.tinychiefdelights.model.User;
import com.tinychiefdelights.repository.CustomerRepository;
import com.tinychiefdelights.service.CustomerService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(value = "Работа с Заказчиком", tags = {"Заказчик"})
@RestController
public class CustomerController {

//Constructor
//
@Autowired
public CustomerController(CustomerRepository customerRepository, CustomerService customerService) {
this.customerRepository = customerRepository;
this.customerService = customerService;
}


// Fields
//Injects into constructor
//
private final CustomerRepository customerRepository;

private CustomerService customerService;



// Aggregate Root
@GetMapping("/customers")
List<Customer> all(){
return customerRepository.findByUserRole("customer");
}

@PostMapping("/customers")
Customer addCustomer(User newUser, @RequestBody Customer newCustomer){
return customerService.addCustomer(newUser, newCustomer);
}

enter image description here

enter image description here

enter image description here

最佳答案

您需要同步实体之间的关联:

public Customer addCustomer(User newUser, Customer newCustomer) {
newCustomer.setUser(newUser);
return customerRepository.save(newCustomer);
}

并将更改级联到用户:

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "id")
@NotFound(action = NotFoundAction.IGNORE)
private User user;

关于java - 如何向数据库表中添加两个表组合的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61427088/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com