Spring JPA - Removing all child entities instead of one - java

I have a Spring Boot app that uses Spring JPA which performs actions on a parent/child, OneToMany database relationship. I have been perfoming save and get requests without issue for a while however I now have a need to remove a child entity from the child database table, however when I test my code I find it removes all child entities from the DB AND the parent entity which is not the behaviour I am looking for.
Below are the entity classes, Zoo is the parent, and Animal is the child. They should have a oneToMany relation.
The parent entity.
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "ZOOS")
public class Zoo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true)
private Integer id;
#ManyToOne
#JoinColumn(name="name")
private String name;
#OneToMany(mappedBy = "zoo", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#Fetch(value = FetchMode.SUBSELECT)
#JsonManagedReference
private List<Animal> animal;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Animal> getAnimal() {
return animal;
}
public void setAnimal(List<Animal> animal) {
this.animal = animal;
}
}
The child entity
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
#Entity
#Table(name = "ANIMALS")
public class Animal {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true)
private Integer id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "zooId")
#JsonBackReference
private Zoo zoo;
#Column(name = "species", nullable = false)
private String species;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Zoo getZoo() {
return zoo;
}
public void setZoo(Zoo zoo) {
this.zoo = zoo;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
}
The repo for the Animal (child) entity
import org.springframework.data.jpa.repository.JpaRepository;
import uk.co.example.api.entities.Animal;
public interface AnimalRepository extends JpaRepository<Animal, Integer> {
}
The java method being called to delete the animal entity
#Autowired
AnimalRepository animalRepo;
public void deleteAnimal(Integer animalId) {
animalRepo.deleteById(animalId);
}
The method should remove one animal from the Animal db table, however in practice it is removing ALL animals with the same zooId and the zoo from the Zoo db table.
I have researched and tried changing the CascadeType.ALL on the ManyToOne annotation in the Animal entity class to PERSIST and I've tried removing the cascade parameter altogether, in both cases I found I would get no errors in my app but no animal records would be removed at all. The tables would be in the same state as before the method was run.
I have also tried using 'orphanRemoval = true' on the OneToMany annotation on the Zoo entity class however this doesn't seem to have any impact when testing.
#OneToMany(mappedBy = "zoo", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
#Fetch(value = FetchMode.SUBSELECT)
#JsonManagedReference
private List<Animal> animal;
Any help will be appreciated.

The relationship from Animal to Zoo is wrong
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "zooId")
#JsonBackReference
private Zoo zoo;
With CascateType.ALL if you delete an Animal also, the Zoo will be deleted, and this will issue to delete all animals.
You should remove the cascading because it in most cases doesn't make sense

Related

Use of #OneToMany or #ManyToMany targeting an unmapped class SpringBoot

I am currently learning Spring Boot development with Postgresql.
Everything was going fine up until today when I tried to add one more OneToMany relation in current entity which resulted in Hibernate exception:
Use of #OneToMany or #ManyToMany targeting an unmapped class: com.github.hryniuklukas.Basic_WMS.model.Document.palletList[com.github.hryniuklukas.Basic_WMS.model.Pallet]
Unfortunately current answers on SO give me no hint.
Child class:
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
#NoArgsConstructor
#MappedSuperclass
#Entity
#Table(name = "pallet")
#Getter
#Setter
public class Pallet {
private #Id #GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
private String palletCode;
private LocalDate date;
private boolean isInWarehouse;
public Pallet(String palletCode, LocalDate date){
this.palletCode=palletCode;
this.date = date;
this.isInWarehouse = true;
}
#ManyToOne(fetch = FetchType.LAZY)
private PalletSpace palletSpace;
#ManyToOne(fetch = FetchType.LAZY)
private Document outboundDocument;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pallet )) return false;
return id != null && id.equals(((Pallet) o).getId());
}
public void setPalletStatusAsSent(){
this.isInWarehouse = false;
}
#Override
public int hashCode() {
return getClass().hashCode();
}
}
Parent 1:
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#NoArgsConstructor
#Getter
#Setter
#Entity(name = "PalletSpace")
#Table(name = "pallet_space")
public class PalletSpace {
private #Id #GeneratedValue (strategy = GenerationType.IDENTITY) Long id;
private String spaceCode;
#OneToMany(
mappedBy = "palletSpace",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Pallet> palletList = new ArrayList<>();
public PalletSpace(String spaceCode){
this.spaceCode = spaceCode;
}
public void addPallet(Pallet pallet){
palletList.add(pallet);
pallet.setPalletSpace(this);
}
public void removePallet(Pallet pallet){
palletList.remove(pallet);
pallet.setPalletSpace(null);
}
}
Parent 2:
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#NoArgsConstructor
#Getter
#Setter
#Slf4j
#Entity
#Table(name = "document")
public class Document {
private #Id #GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
#OneToMany(
mappedBy = "outboundDocument",
cascade = CascadeType.PERSIST
)
private List<Pallet> palletList = new ArrayList<>();
public void addPalletToDocument(Pallet pallet) {
palletList.add(pallet);
pallet.setOutboundDocument(this);
}
public List<Pallet> getConnectedPalletList() {
return this.palletList;
}
public void removePalletFromDocument(Pallet pallet) {
palletList.remove(pallet);
pallet.setOutboundDocument(null);
}
public void executeDocument() {
palletList.forEach(Pallet::setPalletStatusAsSent);
}
}
Pallet in relation to palletspace worked fine, adding Document to the mix results in exception.
JPA Buddy seems to catch the relations just as it should, showing reference tree correctly, Spring doesnt start thou.
Application properties:
spring.datasource.url=jdbc:postgresql://localhost:5050/postgres
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
Try removing #MappedSuperclass from Pallet, since it shouldn't be mixed with #Entity

I'm trying to use #OneToMany relationship in Springboot Jpa

I am trying to use the #OneToMany relationship in my project but got the error: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: com.digitalProfile.digitalProfile.entity.Education.faculty.
I am using JDK 11
My Education.java model looks like this :
package com.digitalProfile.digitalProfile.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="Education")
public class Education extends BaseEntity {
private String name;
private String establishDateNepali;
private String establishDateEnglish;
#OneToOne
private OwnedType ownedType;
private double area;
private int teacherCount;
private int studentCount;
private int staffCount;
#OneToOne
private AcademicLevel academicLevel;
#OneToMany(mappedBy = "education", fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Faculty faculty;
private String province;
private String district;
private String munvdc;
private String ward;
private String gauntole;
private String streetname;
private String city;
//getter setter
and Faculty.java look like this :
package com.digitalProfile.digitalProfile.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table
public class Faculty extends BaseEntity{
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "education_id", nullable = false)
private Education education;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and base entity:
package com.digitalProfile.digitalProfile.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
#MappedSuperclass
public class BaseEntity {
#Id
#Column(nullable = false, unique = true)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Temporal(TemporalType.TIMESTAMP)
#CreationTimestamp
#Column(updatable = false)
private Date dateCreated;
#Temporal(TemporalType.TIMESTAMP)
#UpdateTimestamp
private Date dateUpdated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
}
You currently have defined your Education class to have a single reference variable to Faculty:
public class Education extends BaseEntity {
private Faculty faculty;
}
But if you want to have a OneToMany relationship From Education To Faculty that means that one Education object needs to have references to multiple Faculty objects. So you need to change your data structure so that your Education class can hold multiple references to Faculty objects.
This is usually done by defining the field as a Collection like List:
public class Education extends BaseEntity {
private List<Faculty> faculties;
}
If you are saying Education can have multiple faculties, then it should be defined as
#OneToMany(mappedBy = "education", fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Faculty> faculties;

Java Spring TransientPropertyValueException with #OneToMany

I have the following classes:
A Product class:
package com.springtraining.hibernate.invoice;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
#NoArgsConstructor
#Getter
#Entity
#Table(name="PRODUCTS")
public class Product {
#Id
#GeneratedValue
#NotNull
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#OneToMany(
targetEntity = Item.class,
mappedBy = "product",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY
)
private List<Item> items = new ArrayList<>();
public Product(String name) {
this.name = name;
}
}
package com.springtraining.hibernate.invoice.dao;
import com.springtraining.hibernate.invoice.Product;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
#Repository
#Transactional
public interface ProductDao extends CrudRepository<Product, Integer> {
}
Now, an Item class:
package com.springtraining.hibernate.invoice;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
#NoArgsConstructor
#Getter
#Entity
#Table(name="ITEMS")
public class Item {
#Id
#GeneratedValue
#NotNull
#Column(name = "ID")
private int id;
#JoinColumn(name = "PRODUCT_ID", referencedColumnName = "id")
#ManyToOne
private Product product;
#NotNull
#Column(name = "PRICE")
private BigDecimal price;
#NotNull
#Column(name = "QUANTITY")
private int quantity;
#NotNull
#Column(name = "VALUE")
private BigDecimal value;
#JoinColumn(name="INVOICE_ID", referencedColumnName = "id")
#ManyToOne
private Invoice invoice;
public Item(Product product, String price, int quantity) {
this.product = product;
this.product.getItems().add(this);
this.price = new BigDecimal(price);
this.quantity = quantity;
this.value = this.price.multiply(new BigDecimal(quantity));
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
invoice.getItems().add(this);
}
}
package com.springtraining.hibernate.invoice.dao;
import com.springtraining.hibernate.invoice.Item;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
#Repository
#Transactional
public interface ItemDao extends CrudRepository<Item, Integer> {
}
And an Invoice class:
package com.springtraining.hibernate.invoice;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
#NoArgsConstructor
#Getter
#Entity
#Table(name="INVOICES")
public class Invoice {
#Id
#GeneratedValue
#NotNull
#Column(name = "ID")
private int id;
#NotNull
#Column(name = "NUMBER")
private String number;
#OneToMany(
targetEntity = Item.class,
mappedBy = "invoice",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY
)
private List<Item> items = new ArrayList<>();
public Invoice(String number) {
this.number = number;
}
}
package com.springtraining.hibernate.invoice.dao;
import com.springtraining.hibernate.invoice.Invoice;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
#Repository
#Transactional
public interface InvoiceDao extends CrudRepository<Invoice, Integer> {
}
Now, when I am running a unit test with these classes, I get the following error:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.springtraining.hibernate.invoice.Item.product -> com.springtraining.hibernate.invoice.Product; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.springtraining.hibernate.invoice.Item.product -> com.springtraining.hibernate.invoice.Product
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.springtraining.hibernate.invoice.Item.product -> com.springtraining.hibernate.invoice.Product; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.springtraining.hibernate.invoice.Item.product -> com.springtraining.hibernate.invoice.Product
The unit test code looks like such:
package com.springtraining.hibernate.invoice.dao;
import com.springtraining.hibernate.invoice.Invoice;
import com.springtraining.hibernate.invoice.Item;
import com.springtraining.hibernate.invoice.Product;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
#RunWith(SpringRunner.class)
#SpringBootTest
public class InvoiceDaoTestSuite {
#Autowired
private InvoiceDao invoiceDao;
#Test
public void testInvoiceDaoSave() {
// Given
Product product1 = new Product("prod1");
Product product2 = new Product("prod2");
Item item1 = new Item(product1, "100", 10);
Item item2 = new Item(product1, "200", 10);
Item item3 = new Item(product2, "50", 2);
Item item4 = new Item(product2, "250", 25);
Invoice invoice1 = new Invoice("HK-47");
item2.setInvoice(invoice1);
item3.setInvoice(invoice1);
Invoice invoice2 = new Invoice("HK-48");
item1.setInvoice(invoice2);
item4.setInvoice(invoice2);
// When
invoiceDao.save(invoice1);
invoiceDao.save(invoice2);
int invoice1_id = invoice1.getId();
int invoice2_id = invoice2.getId();
// Then
Assert.assertNotEquals(0, invoice1_id);
Assert.assertNotEquals(0, invoice2_id);
Assert.assertTrue(invoice1.getItems().containsAll(Arrays.asList(item2, item3)));
Assert.assertTrue(invoice2.getItems().containsAll(Arrays.asList(item1, item4)));
Assert.assertTrue(product1.getItems().containsAll(Arrays.asList(item1, item2)));
Assert.assertTrue(product1.getItems().containsAll(Arrays.asList(item3, item4)));
// Clean-up
try {
invoiceDao.deleteById(invoice1_id);
invoiceDao.deleteById(invoice2_id);
} catch (Exception e) {
// Do nothing
}
}
}
I have been looking at this code for a few hours now, and I still do not get it, where I have missed something. Saving Invoice entity, should automatically instantiate Item and Product objects associated with it as well.
Anyone?
In public class Item, add #ManyToOne cascade = CascadeType.ALL property, like so:
#JoinColumn(name = "PRODUCT_ID", referencedColumnName = "id")
#ManyToOne(cascade = CascadeType.ALL)
private Product product;
#JoinColumn(name = "INVOICE_ID", referencedColumnName = "id")
#ManyToOne(cascade = CascadeType.ALL)
private Invoice invoice;
When you create a new entity, using the keyword new, it is in the Transient state. To persist/save it to the DB, you first need to add it to the Persistence Context. CascadeType.ALL includes CascadeType.PERSIST, which will instruct Hibernate to persist the product and invoice entities.
Also, remove the #NotNull on your entity fields annotated by #Id. It is not required, since your field is a primary key and instead of this
invoiceDao.save(invoice1);
invoiceDao.save(invoice2);
int invoice1_id = invoice1.getId();
int invoice2_id = invoice2.getId();
You can do:
int invoice1_id = invoiceDao.save(invoice1).getId();
int invoice2_id = invoiceDao.save(invoice2).getId();

Why are the tables in my unidirectional #ManyToOne relationship not joining on Spring Data findAll() query?

I have a simple database with Universities and Students (see entities below)
University.java
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Getter
#Setter
#Table(name = "university")
public class University {
#Id
#GeneratedValue
#Column(name = "university_id")
private long id;
#Column(name = "university_name")
private String name;
public University() {
}
public University(String name) {
this.name = name;
}
}
Student.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Getter
#Setter
#Table(name = "student")
public class Student {
#Id
#GeneratedValue
#Column(name = "student_id")
private long id;
#Column(name = "student_name")
private String studentName;
#JoinColumn(name="university_name")
private String studentUniversityName;
#ManyToOne
private University university;
public Student() {
}
public Student(String name, String studentUniversityName) {
this.name = name;
this.studentUniversityName = studentUniversityName;
}
}
My entities should join on the university_name column. I wrote the following unit test to verify this behavior.
#Test
void test1() {
final String UNIVERSITY_NAME = "U of A";
universityRepository.save(new University(UNIVERSITY_NAME));
studentRepository.save(new Student("Joe", UNIVERSITY_NAME));
Student joe = studentRepository.findAll().get(0);
assertNotNull(joe.getUniversity()); // <------ FAILING
}
It is failing the assertNotNull(joe.getUniversity()) statement, which seems to indicate that the tables did not join. The strange thing to me, is that the next test passes (when I explicity set the University on Joe. (The contents of the database are the same either way, but findAll() for this test seems to properly trigger a join
#Test
void test2() {
final String UNIVERSITY_NAME = "U of A";
University uni = new University(UNIVERSITY_NAME);
universityRepository.save(uni);
Student joe1 = new Student("Joe", UNIVERSITY_NAME);
joe1.setUniversity(uni);
studentRepository.save(joe1);
Student student = studentRepository.findAll().get(0);
assertNotNull(student.getUniversity());
}
I don't want to set the university on Joe (like in the second test) before I save him, because sometimes I want to save students and universities at different times in the code. I want to be able to save Joe with a null university and populate the field in the call to findAll()
Can someone help me modify my entities so that the first test can pass?
it's better to use id for joining, for example:
#ManyToOne
#JoinColumn(name = "university_id")
private University university;
i hope working :)
try doing this
public class Student {
#Id
#GeneratedValue
#Column(name = "student_id")
private long id;
#Column(name = "student_name")
private String studentName;
private String studentUniversityName;
#ManyToOne
#JoinColumn(name="studentUniversityName" ,
referencedColumn="name")
private University university;
public Student() {
}
public Student(String name, String studentUniversityName) {
this.name = name;
this.studentUniversityName = studentUniversityName;
}
}
public class University {
#Id
#GeneratedValue
#Column(name = "university_id")
private long id;
#Column(name = "university_name")
private String name;
public University() {
}
public University(String name) {
this.name = name;
}
}

Why mapped list is empty?

I am new with hibernate and jpa. I need a little help. I'm developing a restful service application with spring boot. Using mysql and hibernate.
When i call my service "ingredients" array will be empty like that.
Empty array
In database ingredient table and recipe table has one to many relationship so i tried to do same thing with JPA but i can't find correct way. When I try to get Recipe i can access but ingredient list is always empty.
My Database Design:
DB Design
Recipe Entity:
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#Entity()
#Table(name="recipe")
#Getter
#Setter
public class Recipe {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "recipe_id")
private int recipeId;
#Column(name ="name")
private String name;
#Column(name = "description")
private String description;
#Column(name = "picture_id")
private int pictureId;
#OneToMany(mappedBy = "recipe",fetch = FetchType.EAGER)
private List<Ingredient> ingredients = new ArrayList<>();
}
Ingredient Entitiy:
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
#Entity()
#Table(name = "ingredient")
#Getter
#Setter
public class Ingredient implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ingredient_id")
private int ingredientId;
#Column(name = "scale")
private String scale;
#ManyToOne
#JoinColumn(name = "recipe_id",nullable = false)
private Recipe recipe;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "material_id",nullable = false)
private Material material;
}
RecipeDAO:
import com.mutfak.dolapservice.dao.interfaces.IRecipeDAO;
import com.mutfak.dolapservice.entity.Recipe;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
#Transactional
#Repository
public class RecipeDAO implements IRecipeDAO {
#PersistenceContext
private EntityManager entityManager;
#SuppressWarnings("unchecked")
#Override
public List<Recipe> getRecipes() {
String query = "FROM Recipe ORDER BY recipe_id";
return (List<Recipe>) entityManager.createQuery(query).getResultList();
}
#Override
public Recipe getRecipeByMaterial(int materialId) {
return null;
}
#Override
public Recipe getRecipeById(int id) {
return null;
}
#Override
public void addRecipe(Recipe recipe) {
}
#Override
public void updateRecipe(Recipe recipe) {
}
#Override
public void deleteRecipe(int id) {
}
}
Finally I find solution. Lombok annotation's and JPA doesn't work correctly. JPA can't get List<> with Lombok.

Categories

Resources