I am beginner in spring boot and web development and trying to do one-to-many association mapping using Onetomany and joincolumn annotation.
In my application 2 entity classes are there User and ProductDetail and i am trying to do One-to-many association between them.I am expecting user-id as foreign key in ProductDetail table.
There is no error while running my program and when i am passing the JSON statement as input to testcase my application in postman,but when i am seeing my MySql database to see if mapping occured or not, user id is not mapped as a foreign key in ProductDetail table.
I am posting the Entity classes and other classes below.....
Please help i am really stuck please let me know what i am going wrong(I know i am missing very small thing which i am unable to figure out on my own)
User class:-
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
public class User {
@Id
@GeneratedValue
int id;
String name;
String gender;
String emailId;
@OneToMany(targetEntity = ProductDetail.class,cascade = CascadeType.ALL)
@JoinColumn(name="up_fk",referencedColumnName = "id")
private List<ProductDetail> userpurchase;
}
ProductDetail class:-
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
public class ProductDetail
{
@Id
private int productid;
private String productname;
private int cost;
}
Controller class:-
@RestController
@RequestMapping("/Ecommerce")
public class UserController
{
@Autowired
private ProductService productservice;
@Autowired
private ProductRepository productRepository;
@Autowired
private UserRepository userRepository;
@GetMapping("/products")
public List<ProductDetail> ShowProducts()
{
return productservice.getProducts();
}
@PostMapping("/PlaceOrder")
public User placeOrder(@RequestBody OrderRequest request)
{
return userRepository.save(request.getUser());
}
}
OrderRequest:- class which only contains User object from which we extract user object and it will contain list of products..
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class OrderRequest
{
private User user;
}
application.properties file:-
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ecommerceapi
spring.datasource.username=root
spring.datasource.password=deep
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto =update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect