Spring Data, MySQL and not working unique value - mysql

I'm having troubles getting into Spring Data
I got entity Product which has Category (I'm guessing relation type is right? Product has one Category, Category has many products)
#Entity
public class Product implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "category_id")
private Category category;
}
#Entity
class Category implements Serializable {
public Category() {
}
public Category(String name){
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private Long id;
#Column(unique = true)
private String name;
#OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Product> products;
}
Now I try to add new Product via Postman, calling my RestController
#PostMapping("/add")
public Product addProduct(#Valid #RequestBody Product product){
return repository.save(product);
}
With 2 following requests
{
"name" : "pork",
"category" : "meat"
}
{
"name" : "chicken",
"category" : "meat"
}
In the result I got 2 following responses
{
"id": 1,
"name": "pork",
"category": {
"id": 1,
"name": "meat",
"products": null
}
}
{
"id": 2,
"name": "chicken",
"category": {
"id": 2,
"name": "meat",
"products": null
}
}
And on database I actually got 2 categories named "meat" (even tho it should be unique. What's more, do I actually need Set<Product> in my Category class? TBH, Category has no intrest in that at all.

There are a few problems with your code.
You are directly using entity as the rest API model. Suggest to create a separate ProductModel with only fields that client has access to.
You mixing category creation together inside product creation, but your category in the request only contains name. To the backend, unless you check whether such a category exists, it's always treated as a new category.
Before you call repository.save, you need let category knows what's the product inside. In your current code, only product know its category.

You don't need Set products in your Category class (and it's recommended to use only #ManyToOne).

Related

How to implement a JPA birectional relation for entities that works from both sides

Another question regarding bi-directional relationship with JPA entities:
Suppose I have the following two classes:
#Entity
public class Product
{
#Id
private Long productID;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonManagedReference
#JoinColumn(name = "fk_supplier")
private Supplier supplier;
private String description;
public Supplier getSupplier()
{
return supplier;
}
}
And
#Entity
public class Supplier
{
#Id
private Long supplierID;
#OneToMany(mappedBy = "supplier")
#JsonBackReference
private Set<Product> products = new HashSet<>();
private String name;
public Set<Product> getProducts()
{
return products;
}
}
With those definitions, I get the results back that I want if I query for a product. For example like this:
{
"productID": 1,
"supplier": {
"supplierID": 1,
"name": "Acer"
},
"description": "Gaming chair"
}
But if I do it the other way round, thus querying a supplier, I only get this back:
{
"supplierID": 1,
"name": "Acer"
}
Here I am missing the products.
How can this be achieved?
OneToMany is inherently lazy so if you want to load Supplier and all products you need to eagerly fetch the products
#OneToMany(fetch = FetchType.EAGER)
// or
#Query("select s from Supplier s left join fetch s.products where s.supplierID = 1)
Also as you have a circular dependency between supplier and product you have used #JsonBackReference on the products collection which will prevent the products being serialised to json, hence your response
If you want to return Supplier with list of products or a product with the supplier and prevent circular dependency issues remove #JsonBackReference and #JsonManagedReference reference and use #JsonIgnoreProperties instead
#JsonIgnoreProperties("products")
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "fk_supplier")
private Supplier supplier;
#JsonIgnoreProperties("supplier")
#OneToMany(mappedBy = "supplier", fetch = FetchType.EAGER)
private Set<Product> products = new HashSet<>();

Post JSON with #ManyToOne Relationship in Spring Boot

I have written a test application in spring boot. Employees have a relation to a department. CRUD works, but I'm not sure I'm doing it the correct way.
When I will create a new employee I have to send the following post request
"id": 3,
"firstname": "John",
"lastname": "Doe",
"salary": 50000,
"department": {
"id": 2,
"name": "Sales"
}
}
This is the employee class:
#Entity
public class Employee {
#Id
#GeneratedValue
private Long id;
private String firstname;
private String lastname;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "department_id", referencedColumnName="id")
private Department department;
private int salary;
This is the create method in the EmployeeController:
#PostMapping("/employees")
public Employee create(#RequestBody Employee employee) {
return employeeService.add(employee);
}
The department entries already exists.
Is it possible to create an employee without filling the complete relation
(department)?
I would like to add the department id only. But if I do this, the name field in the json data is empty (get request)
id 3
firstname "John"
lastname "Doe"
department
id 2
name null
salary 50000
Is there any better approach?
You are taking an Entity as a request body which is not the correct approach. You can take Some VO as Request Object and then convert to Entity inside a service.
For E.g
EmployeeVO{
private String firstname;
private String lastname;
List<Integer> departments;
}
Also, you can use Jackson annotations like
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(JsonInclude.Include.NON_NULL) to ignore unknown attributes and include not null attributes.

JPA serialize enttiy

I have my data model that contains 3 tables: User, Profile, UserProfile.
public class User implements Serializable {
private Integer id;
......
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch =
FetchType.LAZY)
#JsonManagedReference
#JsonProperty("profiles")
private List<UserProfile> userProfiles = new ArrayList<UserProfile>();
}
public class Profile implements Serializable {
private Integer id;
......
#OneToMany(mappedBy="profile", cascade = CascadeType.ALL, fetch =
FetchType.LAZY)
#JsonBackReference
private List<UserProfile> userProfiles= new ArrayList<UserProfile>();
}
public class UserProfile implements Serializable {
private Integer id;
#ManyToOne
#JoinColumn(name = "idUser")
#JsonBackReference
private User user;
#ManyToOne
#JoinColumn(name = "idProfile")
#JsonManagedReference
private Profile profile;
}
And here’s my json feed back:
{
"id": 1,
.......
"profiles": [
{
"profile": {
"id": 1,
.....
},
{
"id": 2,
.....
}
}
]
}
I have two questions:
Is it possible to remove the profile attribute and have:
{
"id": 1,
.......
"profiles": [
{
"id": 1,
.....
},
{
": 2,
.....
}
]
}
In a manytomany relationship with an intermediate table that contains a primary key (id), 2 foreign key that are the ids of the 2 tables that have the manytomany relationship, is that how to do it?
For the 1st question, to hide profile attribute, there are 2 options:
1. If you don't need it in any json output, you can add a #JsonIgnore annotation to it;
2. If you need it elsewhere but don't want it here, you can use Projection. Check https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections and https://www.baeldung.com/spring-data-rest-projections-excerpts for reference on how to use projections.
Checked your code again. Your code has some problem.
You only need 2 entities: User and Profile. And just add #ManyToMany relationship to them.
Refer here for a complete sample on ManyToMany https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/

Duplicate entry instead of using existing entity

I'm getting MySQLIntegrityConstraintViolationException while trying to add new Product. Each Product has Category which has unique value name. I'm getting this exception when I try to add new Product with already existing Category. Example below:
POST 1
{
"name" : "apple",
"categoryName" : "fruit"
}
Response
{
"name": "apple",
"categoryName": "fruit",
"kcal": null
}
Post 2:
{
"name" : "banana",
"categoryName" : "fruit"
}
Response:
{
"timestamp": 1533451793052,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.DataIntegrityViolationException",
"message": "could not execute statement; SQL [n/a]; constraint [UK_8f25rdca1qev4kqtyrxwsx0k8]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/product/add"
}
Which is obviously not what I'd expect, instead I want banana to use same category as apple.
Ok, the code, first entities and dto's
#Entity
#Table(name = "tbl_product")
public class Product implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double kcal;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn
private Category category;
}
public class ProductDto {
private String name;
private String categoryName;
private Double kcal;
}
#Entity
#Table(name = "tbl_category")
public class Category implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true)
private String name;
public Category(){ }
public Category(String name){
this.name = name;
}
}
Post from controller
#PostMapping("/add")
public ProductDto addProduct(#Valid #RequestBody ProductDto productDto){
Product product = productRepository.save(dtoToEntityTranslator.translate(productDto));
return entityToDtoTranslator.translate(product);
}
And pretty straight-forward translators
public class DtoToEntityTranslator {
public Product translate(ProductDto productDto){
Product product = new Product();
product.setName(productDto.getName());
product.setCategory(new Category(productDto.getCategoryName()));
product.setKcal(productDto.getKcal());
return product;
}
}
public class EntityToDtoTranslator {
public ProductDto translate(Product product){
ProductDto productDto = new ProductDto();
productDto.setName(product.getName());
if(product.getCategory() != null) {
productDto.setCategoryName(product.getCategory().getName());
}
productDto.setKcal(product.getKcal());
return productDto;
}
}
Not sure if it's worth mention, my repository for Product
#Repository
public interface ProductRepository extends CrudRepository<Product, Long> {
}
The error is caused by this line
product.setCategory(new Category(productDto.getCategoryName()));
You are tolding Hibernate that this is a new Category because category name is not the Id for Category.
To solve this, you can get the Category with the provided and set to the Category.
Another way is that for existing Category, instead of sending the name to server, you can consider sending the category id.

How to access spring jpa references in json

I have two entitys, A and B. Lets say, that, A has some fields (name, location). B has some fields too + a #ManyToOne relationship to A.
Now if I run my app, I can see the entitys and their valus in ...myDomain/api and specific entitys in ...myDomain/api/A for example. Now if look at ...myDomain/api/B/1, I can see B-s values + under _links a reference to A. How can I get A to already be as a value in B, not a link.
End result should look smth like this:
{
"_embedded" : {
"B" : [ {
"id" : 1,
"someData" : "data",
"otherData" : "other",
"A" : {
"name": "myName",
"location": "myLoc"
} ]
UPDATE
#Entity
#Data //lombok
public class A extends SuperClass{
private String name;
private String location;
}
#Entity
#Data
public class B extends SuperClass {
private String someData;
private String otherData;
#ManyToOne(optional = false, cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private A a;
}
public class SuperClass implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected long id;
}
Both entitys have a simple repository interface which extend CrudRepository.
UPDATE II
Now if I add #RestResourece( exported = false ) tag after #ManyToOne tag, I get the A entity "exposed" and I can access the data. But now, doing a POST on my B entity, I can't access it anymore because B isn't found by Resource<B> anymore. Why is that so?