0

I need to put and get data from MySql with spring boot (Hibernate, Jackson)

Sample JSON:

[
    {
        "name": "Product1",
        "colors": [
            {
                "color": [
                    "#dddd33",
                    "#676767"
                ]
            },
            {
                "color": [
                    "#FFdDFF"
                ]
            }
        ]
    }
]

Same JSON I want to receive but added "id". What should I do to achieve this?

Object:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("colors")
    @OneToMany(mappedBy = "product_id")
    private Set<Color> colors;
}

@Entity
public class Color {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private Long product_id;

    @JsonProperty("color")
    @CollectionTable(name = "color", joinColumns = @JoinColumn(name = "color_id"))
    @Column(name = "color")
    @ElementCollection
    @OrderBy
    private List<String> color;
}

This not work I get error java.sql.SQLException: Field 'id' doesn't have a default value

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
Pavlo Kravchenko
  • 345
  • 5
  • 20
  • 1
    The issue is with your SQL tables most likely- can you post your table creation scripts? – Rob Scully May 24 '19 at 15:20
  • The fact is that Hibernate creates tables automatically. – Pavlo Kravchenko May 24 '19 at 18:09
  • You can always generate `CREATE SCRIPT` from already created table in `MySQL`. [How to generate a create table script for an existing table in phpmyadmin?](https://stackoverflow.com/questions/11739014/how-to-generate-a-create-table-script-for-an-existing-table-in-phpmyadmin). Also take a look on: [Why should not use the AUTO JPA GenerationType with MySQL and Hibernate](https://vladmihalcea.com/why-should-not-use-the-auto-jpa-generationtype-with-mysql-and-hibernate/) – Michał Ziober May 24 '19 at 21:46

0 Answers0