如何在SpringMVC的@joincolumn中插入数据

发布于 2025-02-12 15:58:43 字数 5111 浏览 0 评论 0原文

我有两个表customerdetailsproduct,我想从cocers表中添加它> @joincolumn(order_id) customerdetails表中的列。

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

@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
public interface CdRepo extends JpaRepository<CustomerDetails, Long>
{
            
}

使用getCustid()我现在获得了

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

客户的ID ,

@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);
            
    }   
}

当前

@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;
    }

我想将该ID插入@joincolumn(order_id)

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.

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

@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

@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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫性小仙女 2025-02-19 15:58:43

如果我正确理解,则要将产品分配给用户(例如客户)。
对于@OnetoOne关系,您不需要private customerdetails cd;在产品类中。尽管我不知道为什么您会以这种方式实施这种事情!

通常,如果您想将两件事分配在一起,假设您想将产品分配给用户,以便该产品适合该用户,则应从存储库或任何地方找到product obj产品和用户都必须具有DB生成的ID),然后将其分配给user.product

产品服务

@Service
public class ProductService  {

  @Autowired
  private ProductRepo productRepository;

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

}

客户服务

@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);
        
  }  

}

控制器

@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;
}

在每个实体中编写Getters和Setter,或使用Lombok注释@Data
通常,当我想用​​用户和产品部署电子商务时。我使用用户购物车产品模型。

上面代码的问题是,如果将该产品分配给用户,则仅适用于该用户。如果其他用户想要相同的产品,则必须为其创建所有这些产品。解决方案将使用产品作为系列或模型。

想象一下您想创建一个网站以出售咖啡包的情况。您只有两种类型的包装可供出售。您可以为这些软件包创建一个类似的产品,并为每个软件包创建数量。然后在购物车模型中创建@onetomany与产品中的关系。它将创建一个JOIN表,以将任何可能的产品ID存储在此处使用CART ID。之后,在您的购物车实体中创建@manytoone关系,@onetomany在您的用户实体中。现在,每个购物车仅适用于特定用户,而不适合产品。

一些友好的建议:

  • 不要用逻辑填充控制器。让服务层处理。
  • 对于每个实体,创建一个带有实体名称的软件包,然后创建3个类;实体本身,响应Pojo并要求Pojo。
  • 将getters和setters用于您的Entites。您可以使用Lombok。它将通过产生情况来处理这种情况。
  • 使用转换器组件创建和转换为实体本身,并将实体转换为响应实体。
  • 避免尽可能多地与数据库进行交互。将对象放在变量中,例如dbcustomer用于执行操作。

If I've understood correctly, you want to assign a product to a user (e.g Customer).
For a @OneToOne relation you don't need 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 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.
Usually when I want to deploy an ecommerce with user and product. I use user, cart, product model.

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. Then create a @OneToMany relationship in your cart model to products. It will create a join table to store any possible product id there with cart id. After that, create a @ManyToOne relationship in your cart entity and @OneToMany in your user entity. 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; the entity itself, response POJO and request POJO.
  • Use getters and setters for your entites. You can use lombok for that matter. 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文