Spring boot get valid entity from other table, and problem with ID increment sharing

Viewed 141

I have two different tables, Pizza and User. First of all, when I create the first entity from for example the user, ID is 1. After that, when I want to create a Pizza, the ID of it will be 2. They sharing the ID somehow. How can I fix that?

And my other question, I have a third table, named Orders. I managed to ask on Order creating for the valid User and Pizza ID, but I just wanna know, what would be the best solution for it? I just created the Pizza and User Service object in the Order Controller as well, and refered from there. But I don't know how bad is it.

Thank you for the answers!

@Entity(name = "pizza")
@Table(name = "pizza")
public class Pizza {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @NotNull
    private String type;
@Entity(name = "users")
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @NotNull
    private String email;
    @NotNull
    private String address;
@Entity(name = "orders")
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @NotNull
    private int user_id;
    @NotNull
    private int pizza_id;
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private PizzaService pizzaService;
2 Answers

try to use identity generation type instead of auto:

@GeneratedValue(strategy = GenerationType.IDENTITY)

for your first question I think you should change :

 @GeneratedValue(strategy = GenerationType.AUTO)

to

@GeneratedValue(strategy = GenerationType.IDENTITY)

for your second question I think that you have to use relationship annotation between your entities : like:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ID_USER")
Private User user;
Related