简体   繁体   English

如何在 SpringMvc 的 @JoinColumn 中插入数据

[英]How do I insert data in a @JoinColumn in SpringMvc

I have two tables CustomerDetails and Product , I want to fetch customerid from customer table and add it to @joincolumn(order_id) column in same CustomerDetails table.我有两个表CustomerDetailsProduct ,我想从customer表中获取customerid并将其添加到同一CustomerDetails表中的@joincolumn(order_id)列。

CustomerDetails.java CustomerDetails.java

@Entity
@Table(name = "CustomerDetails")
public class CustomerDetails {

    @Id
    @GeneratedValue
    @Column(name="CUSTOMER_ID")
    private Long custid;

    @Column(name="CUSTOMER_NAME")
    private String customerName;
    
    @Column(name="EMAIL")
    private String email;
    
    @Column(name="ADDRESS")
    private String address;
    
    @Column(name="PHONENO")
    private String phoneno;
    
    public CustomerDetails() {
    }

    @Override
    public String toString() {
        return "CustomerDetails [custid=" + custid + ", customername=" + customerName + ", email=" + email
                + ", address=" + address + ", phoneno=" + phoneno + "]";
    }

    public CustomerDetails(String customername, String email, String address, String phoneno) {
        super();
        this.customerName = customername;
        this.email = email;
        this.address = address;
        this.phoneno = phoneno;
    }   
    public Long getCustid() {
        return custid;
    }

    public void setCustid(Long custid) {
        this.custid = custid;
    }

    public String getName() {
        return customerName;
    }

    public void setName(String name) {
        this.customerName = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return address;
    }

    public void setPassword(String password) {
        this.address = password;
    }

    public String getPhoneno() {
        return phoneno;
    }

    public void setPhoneno(String phoneno) {
        this.phoneno = phoneno;
    }   
}

Product.java产品.java

@Entity
@Table(name="Product")
public class Product {
    
    @Id
    @GeneratedValue
    @Column(name="PRODUCT_ID")
    private Long productId;
    
    @Column(name="PRODUCT_NAME")
    private String productName;
    
    @Column(name="PRODUCT_BRAND")
    private String productBrand;
    
    @Column(name="PRODUCT_PRICE")
    private double productPrice;
    
    @OneToOne
    private CustomerDetails cd;
   
    public Product(Long productId, String productName, String productBrand, double productPrice, CustomerDetails cd) {
        super();
        this.productId = productId;
        this.productName = productName;
        this.productBrand = productBrand;
        this.productPrice = productPrice;
        this.cd = cd;
    }
    
    public Product(String productName, String productType, double productPrice) {
        super();
        this.productName = productName;
        this.productBrand = productType;
        this.productPrice = productPrice;
    }
    
    public Long getProductId() {
        return productId;
    }
    public void setProductId(Long productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductBrand() {
        return productBrand;
    }
    public void setProductBrand(String productType) {
        this.productBrand = productType;
    }
    public double getProductPrice() {
        return productPrice;
    }
    public void setProductPrice(double productPrice) {
        this.productPrice = productPrice;
    }
    
    public CustomerDetails getCd() {
        return cd;
    }

    public void setCd(CustomerDetails cd) {
        this.cd = cd;
    }
    public Product() {
        //super();
    }
    @Override
    public String toString() {
        return "Product [productId=" + productId + ", productName=" + productName + ", productType=" + productBrand
                + ", productPrice=" + productPrice + "]";
    }
 
}

CustomerDetails repository CustomerDetails 存储库

@Repository
public interface CdRepo extends JpaRepository<CustomerDetails, Long>
{
            
}

Product repository产品存储库

@Repository
public interface ProductRepo extends JpaRepository<Product, Long>
{
        
}

CustomerService客户服务

@Service
@Transactional
public class CustomerService  {
    
    private final CdRepo cdRepo;
    
    @Autowired
    public CustomerService(CdRepo cdRepo) {
        
        this.cdRepo = cdRepo;
        
    }
    public void saveCustomer(CustomerDetails cd) 
    {
        cdRepo.save(cd);
            
    }   
}

controller控制器

@RequestMapping(value = {"/addCustomerDetails"}, method = RequestMethod.POST)
    public ModelAndView addCustomerDetails(CustomerDetails cd) 
    {
        
        customerService.saveCustomer(cd);
        System.out.println(cd.getCustid());
        ModelAndView model = new ModelAndView();
        model.setViewName("homepage");
        return model;
    }

In controller using getCustid() I'm getting current customer's id now I want to insert that id into @joinColumn(order_id)在使用getCustid()的控制器中,我现在正在获取当前客户的 ID,我想将该 ID 插入到@joinColumn(order_id)

If I've understood correctly, you want to assign a product to a user (eg Customer).如果我理解正确,您想将产品分配给用户(例如客户)。 For a @OneToOne relation you don't need private CustomerDetails cd;对于@OneToOne关系,您不需要private CustomerDetails cd; in product class.在产品类。 Although I don't know why are you implementing such thing in that way at all!虽然我不知道你为什么要以那种方式实施这样的事情!

Generally If you want to assign two things together, let's say you want to assign a product to a user so that the product would be for that user, you should find the product obj from repository or any where (both product and user must have an id generated by db) and then assign it to user.product .一般来说,如果您想将两件事情一起分配,假设您想将产品分配给用户,以便该产品适用于该用户,您应该从存储库或任何地方找到product obj(产品和用户都必须有db 生成的 id),然后将其分配给user.product

product service产品服务

@Service
public class ProductService  {

  @Autowired
  private ProductRepo productRepository;

  public Optional<Product> findProductById(Long id) {
     return this.productRepository.findByProductId(id);
  }  

}

customer service客户服务

@Service
@Transactional
public class CustomerService  {

  private final CdRepo cdRepo;

  @Autowired
  public CustomerService(CdRepo cdRepo) {
    this.cdRepo = cdRepo;
  }

  public CustomerDetails saveCustomer(CustomerDetails cd, Long productId) {
    CustomerDetails dbCustomer = customerService.saveCustomer(cd);
    // I'm getting the id from path variable, change it if you have other logics
    Optional<Product> dbProduct = this.productService.findProductById(productId);
    // I don't know how you handle run time errors so I can't write it, don't
    // forget to check the dbProduct in case it didn't exist :)
    
    // In case you did not created getters and setters in CustomerDetails,
    // use dbCustomer.product = dbProduct.get();
    dbCustomer.setProduct(dbProduct.get());

    // update our customer using JPA, after customer update JPA handles everything
    return this.cdRepo.save(dbCustomer);
        
  }  

}

controller控制器

@RequestMapping(value = {"/addCustomerDetails/{productId}"}, method = RequestMethod.POST)
public ModelAndView addCustomerDetails(CustomerDetails cd, @PathVariable Long productId ) 
{
    
    CustomerDetails dbCustomer = this.customerService.saveCustomer(cd, productId);
    // Use the dbCustomer in your logic ...
    ModelAndView model = new ModelAndView();
    model.setViewName("homepage");
    return model;
}

Write getters and setters in each entity or use Lombok annotation @Data .在每个实体中编写 getter 和 setter 或使用 Lombok 注释@Data Usually when I want to deploy an ecommerce with user and product.通常当我想用用户和产品部署电子商务时。 I use user , cart , product model.我使用usercartproduct模型。

The problem with the code above is that if you assign that product to a user, it's ONLY for that user.上面代码的问题在于,如果您将该产品分配给用户,则它仅适用于该用户。 if other users want the same product you have to create all of those products for them.如果其他用户想要相同的产品,您必须为他们创建所有这些产品。 Solution to that would be using product as a series or a model.解决方案是将产品用作系列或模型。

Imagine a situation that you want to create a website to sell coffee packages.想象一下,您想创建一个网站来销售咖啡包。 you only have two type of package to sell.你只有两种类型的包裹要卖。 you can create an entity like product for those packages with a quantity for each.您可以为这些包裹创建一个类似产品的实体,每个包裹都有一个quantity Then create a @OneToMany relationship in your cart model to products.然后在您的购物车模型中创建与产品的@OneToMany关系。 It will create a join table to store any possible product id there with cart id.它将创建一个连接表来存储任何可能的产品 id 和购物车 id。 After that, create a @ManyToOne relationship in your cart entity and @OneToMany in your user entity.之后,在您的购物车实体中创建@ManyToOne关系,并在您的用户实体中创建@OneToMany Now each cart is only for a specific user and not the products.现在每个购物车仅适用于特定用户而不是产品。

Some Friendly Advice:一些友好的建议:

  • Don't populate your controller with logic.不要用逻辑填充你的控制器。 Let service layer handle it.让服务层处理它。
  • For each entity, create a package with the name of the entity instead and create 3 classes;对于每个实体,使用实体名称创建一个包,并创建 3 个类; the entity itself, response POJO and request POJO.实体本身,响应 POJO 和请求 POJO。
  • Use getters and setters for your entites.为您的实体使用 getter 和 setter。 You can use lombok for that matter.你可以使用 lombok 来解​​决这个问题。 It will handle the situation by generating them.它将通过生成它们来处理这种情况。
  • Use convertor components to create and convert requested entity to the entity itself and also convert entity to response entity.使用转换器组件创建请求实体并将其转换为实体本身,并将实体转换为响应实体。
  • Avoid interacting with Data base as much as you can.尽可能避免与数据库交互。 hold the object in a variable like dbCustomer for doing operations.将对象保存在dbCustomer之类的变量中以进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM