Home > database >  How to save an object that contains a list of integers in a postgres database
How to save an object that contains a list of integers in a postgres database

Time:11-23

i have an object called Cart i want to save it in the database with an array/list of integers that rappresents Product's id.

This is my Cart class at the moment:

public class Cart {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;

@Column(name = "customer_fk")
private Integer customerFk;

@Column(name = "product_list")
private List<Integer> productList;

}

i saw that postgres has the integer[] datatype

I'm using spring.jpa.hibernate.ddl-auto=create to create the database

How do i tell to spring and jpa to save that list as an integer in the DB? (if i can) Is this a good solution?

I actually found a solution that works, using Strings, but im too curious to see if find a way to do it with arrays

CodePudding user response:

The canonical approach here would be to maintain a table of products and then map carts to products in a one to many relationship. You could try:

@Entity
@Table(name = "Cart")
public class Cart {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Integer id;

    @Column(name = "customer_fk")
    private Integer customerFk;

    @Column(name = "product_list")
    @OneToMany(mappedBy="cart", cascade = CascadeType.ALL)
    private List<Product> productList;
}

@Entity
@Table(name = "Product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Integer id;
 
    @ManyToOne
    @JoinColumn(name = "FK_Cart")
    private Cart cart;
 
    // more fields, getters and setters
}

This is not a complete implementation, but the idea is that each product ID should exist in a dedicated products table, and each cart entity should track its product references via a foreign key relationship.

  • Related