one to many relationship how to save data in spring boot - mysql

below is my stores enitity
#Entity
#Table(name="stores")
public class Stores {
#Id
#GeneratedValue
private Long id;
#Column(name ="incharge_id")
private Integer inchargeId;
#Column(name = "store_name")
private String storeName;
#OneToMany(mappedBy = "stores",
fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Items> items;
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
for (Items item : items) {
item.setStores(this);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getInchargeId() {
return inchargeId;
}
public void setInchargeId(Integer inchargeId) {
this.inchargeId = inchargeId;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
}
Below is my item entity
package bt.gov.dit.inventoryservice.model;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name = "items")
public class Items {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
#Column(name="item_name")
private String itemName;
#ManyToOne
private Categories categories;
#ManyToOne(fetch = FetchType.LAZY)
//#JoinColumn(name = "book_category_id", referencedColumnName = "id")
#JoinColumn(name = "stores_id", nullable = false,referencedColumnName = "id")
private Stores stores;
#Column(name="insert_date")
private Date insertDate;
#Column(name="update_date")
private Date updateDate;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Categories getCategories() {
return categories;
}
public void setCategories(Categories categories) {
this.categories = categories;
}
public Stores getStores() {
return stores;
}
public void setStores(Stores stores) {
this.stores = stores;
stores.getItems().add(this);
}
public Date getInsertDate() {
return insertDate;
}
public void setInsertDate(Date insertDate) {
this.insertDate = insertDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
}
I have one-to-many relationship between them. One store can have many items. But I don't know how to insert items with stores . I have tried the default save of Jpa respoistory but in place of stores_id (which is the foreign key) it saves null. Can anyone tell me how to implement the service?

It will be something like below.
Stores stores = new Stores();
stores.setStoreName("store name");
// Set other fields of store entity
Item item1 = new Item();
item1.setItemName("item name 1");
// Set other fields of item entity
Item item2 = new Item();
item2.setItemName("item name 2");
// Set other fields of item entity
// Call setItems
// Call getItems in a Set class object like Set<Item> items;
stores.setItems(items);
storesService.save(stores); // it will save all items with foreign key.

Related

Deleted item keeps showing in JSON

I'm working on a simple todo app in which you can add dependencies between todo items which means you cannot change status to true(completed) if dependency item is not completed. The problem is when I delete an item which another item is dependent to, json still shows dependency between two items. I'll try to explain with an example; say you have item 1 and item 2. Item 1 is dependent to item 2 and you can't mark item 1 "completed" if item 2 is not completed. But if you delete item 2 then dependency between items is also gone. So after deleting item 2 I can change item 1's status to true but when I make a get request for item 1, json still shows dependency to item 2.
Here is my TodoItem class;
package com.erdemkara.todoapp.data.entity;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Set;
#Entity
#Table(name = "todo_items")
public class TodoItem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(nullable = false)
private String name;
private String description;
#Column(nullable = false)
private LocalDate deadline;
#Column(nullable = false)
private boolean status;
#Column(name = "todo_list_id", nullable = false)
private int todoListId;
#OneToMany(mappedBy = "todoItem", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonManagedReference
private Set<Dependency> dependencies;
public TodoItem()
{}
public TodoItem(int id, String name, String description, LocalDate deadline,
boolean status, int todoListId, Set<Dependency> dependencies)
{
this.id = id;
this.name = name;
this.description = description;
this.deadline = deadline;
this.status = status;
this.todoListId = todoListId;
this.dependencies = dependencies;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDeadline() {
return deadline;
}
public void setDeadline(LocalDate deadline) {
this.deadline = deadline;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
#JsonGetter("todo_list_id")
public int getTodoListId() {
return todoListId;
}
public void setTodoListId(int todoListId) {
this.todoListId = todoListId;
}
public Set<Dependency> getDependencies() {
return dependencies;
}
public void setDependencies(Set<Dependency> dependencies) {
this.dependencies = dependencies;
}
}
Dependency class;
package com.erdemkara.todoapp.data.entity;
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
#Entity
#Table(name = "dependencies")
public class Dependency {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonIgnore
private int id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "todo_item_id", nullable = false)
#JsonBackReference
private TodoItem todoItem;
#Column(name = "dependency_item_id", nullable = false)
private int dependencyItemId;
public Dependency()
{}
public Dependency(int id, TodoItem todoItem, int dependencyItemId)
{
this.id = id;
this.todoItem = todoItem;
this.dependencyItemId = dependencyItemId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public TodoItem getTodoItem() {
return todoItem;
}
public void setTodoItem(TodoItem todoItem) {
this.todoItem = todoItem;
}
public int getDependencyItemId() {
return dependencyItemId;
}
public void setDependencyItemId(int dependencyItemId) {
this.dependencyItemId = dependencyItemId;
}
}
Response for item 1 get request(item 1 is dependent to item 2 and 3);
{
"id": 1,
"name": "Item 1",
"description": "Study Collections",
"deadline": "2023-01-09",
"status": false,
"dependencies": [
{
"dependencyItemId": 3
},
{
"dependencyItemId": 2
}
],
"todo_list_id": 1
}
I get the same response before and after deleting item 2. But I want to get a response like this;
{
"id": 1,
"name": "Item 1",
"description": "Study Collections",
"deadline": "2023-01-09",
"status": false,
"dependencies": [
{
"dependencyItemId": 3
}
],
"todo_list_id": 1
}
How can I fix this?
EDIT: #Zychoo I use 2 different delete methods on Service layer. One is for deleting all dependencies for an item. The other one is to delete a specific dependency;
public void deleteDependencyByDependencyItemId(int todoItemId, int dependencyItemId) {
dependencyRepository.deleteByDependencyItemId(todoItemId, dependencyItemId);
}
public void deleteAllDependenciesByTodoItemId(int todoItemId) {
dependencyRepository.deleteAll(dependencyRepository.findAllByTodoItemId(todoItemId));
}
And this is the Repository Layer;
public interface IDependencyRepository extends CrudRepository<Dependency, Integer> {
#Modifying
#Transactional
#Query(value = "delete from dependencies d where d.todo_item_id=? and d.dependency_item_id =?", nativeQuery = true)
void deleteByDependencyItemId(int todoItemId, int dependencyItemId);
}
You could changed
public Set<Dependency> getDependencies() {
return dependencies;
}
to
public Set<Dependency> getDependencies() {
return dependencies.stream().filter(dependency -> "your condition for completion").collect(Collectors.toSet());
}
The ObjectMapper from spring-boot uses the getters to create a JSON. If your Dependency does not show up in the return value of your getter, it will not show up in the JSON response.
I reorganized delete method in TodoItem service layer from this:
public void deleteItemById(int id) {
todoItemRepository.deleteById(id);
}
to this:
public void deleteItemById(int id) {
todoItemRepository.deleteById(id);
dependencyService.deleteAllDependenciesByTodoItemId(id);
}
It deletes every dependency along with the item. Now it works as I expected. Thank you for the answers.

inserting a foreign key in child table it showing null everytime

I am inserting a foreign key in a child table using a #OnetoMany relationship between parent and medicine. One parent has many medicines and it shows me null.
I have done many searches for my problem and I have tried every possible solution, but it's not working.
Parent Class
#Entity
#Table(name = "patient_domain")
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "p_id")
private Integer p_id;
#Column(name = "doctor_name")
private String doctor_name;
#Column(name="name")
private String name;
#Column(name="hospital_clinic")
private String hospital_clinic;
#Column(name="date")
private Date date;
#OneToMany(mappedBy = "patient", cascade = CascadeType.ALL)
private List<Medicine> medicines;
Patient Bean class
package com.gamification.beans;
import com.gamification.entities.Medicine;
import java.util.Date;
import java.util.List;
public class PatientBean {
private Integer p_id;
private String name;
private String doctor_name;
private Date date;
private List<Medicine> medicines;
public List<Medicine> getMedicines() {
return medicines;
}
public void setMedicines(List<Medicine> medicines) {
this.medicines = medicines;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDoctor_name() {
return doctor_name;
}
public void setDoctor_name(String doctor_name) {
this.doctor_name = doctor_name;
}
public String getHospital_clinic() {
return hospital_clinic;
}
public void setHospital_clinic(String hospital_clinic) {
this.hospital_clinic = hospital_clinic;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
private String hospital_clinic;
}
Medicine Class
#Entity
#Table(name = "medicine_kit")
public class Medicine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "med_id")
private Integer med_id;
#Column(name="med_name")
private String med_name;
#Column(name="med_type")
private String med_type;
#Column(name="med_quantity")
private String med_quantity;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "patient_domain_p_id", nullable = false,
referencedColumnName = "p_id")
private Patient patient;
MedicineBean
public class MedicineBean {
private Integer med_id;
private String med_name;
private String med_type;
private String med_quantity;
private Integer patientid;
public Integer getPatientid() {
return patientid;
}
public void setPatientid(Integer patientid) {
this.patientid = patientid;
}
public Integer getMed_id() {
return med_id;
}
public void setMed_id(Integer med_id) {
this.med_id = med_id;
}
public String getMed_name() {
return med_name;
}
public void setMed_name(String med_name) {
this.med_name = med_name;
}
public String getMed_type() {
return med_type;
}
public void setMed_type(String med_type) {
this.med_type = med_type;
}
public String getMed_quantity() {
return med_quantity;
}
public void setMed_quantity(String med_quantity) {
this.med_quantity = med_quantity;
}
}
PatientController
#RequestMapping(method = {RequestMethod.POST})
public ResponseEntity<ApiResponse> createOrUpdateUser(#RequestBody PatientBean patientBean) throws Exception {
ApiResponse status = new ApiResponse();
status.setStatus(false);
status.setMessage("please select record");
try {
if(patientBean != null) {
Patient patient = new Patient();
List<Medicine> listmedicine=new ArrayList<Medicine>();
status.setStatus(true);
if(patientBean.getP_id() != null) {
patient.setP_id(patientBean.getP_id());
status.setMessage("Successfully record updated");
} else {
status.setMessage("Successfully record created");
}
patient.setName(patientBean.getName());
patient.setDoctor_name(patientBean.getDoctor_name());
patient.setHospital_clinic(patientBean.getHospital_clinic());
patient.setDate(CommonUtil.getCurrentTimestamp());
if(patient.getMedicines().size()>0)
{
for (int i=0;i<patient.getMedicines().size();i++)
{
Medicine medicine=new Medicine();
medicine.setMed_name(patientBean.getMedicines().get(i).getMed_name());
medicine.setMed_quantity(patientBean.getMedicines().get(i).getMed_quantity());
medicine.setMed_type(patientBean.getMedicines().get(i).getMed_type());
medicine.setPatient(patient);
listmedicine.add(medicine);
}
}
patient.setMedicines(listmedicine);
status.getResponseList().add(patient);
patienServiceImp.createPatient(patient);
}
return new ResponseEntity<ApiResponse>(status, HttpStatus.OK);
} catch (Exception e) {
status.setStatus(false);
status.setMessage("Something went wrong on server");
MyPrint.println(e.getMessage());
return new ResponseEntity<ApiResponse>(status, HttpStatus.OK);
}
}
solved, I got the mistake that i didn't set the medicine in the patient,
"patient.setMedicines(patientBean.getMedicines());" just add this one in my code and my code is working properly.

ManytoMany creating 2 tables

I have two classes cards and tags. I want a many to many relationship between them and store the cardId and tagId in one table. When i create the database from the code it creates 2 different table with one to many relationship. tag_cards and card_tags. What am i doing wrong here? I want one single table with many to many relationship.
import javax.faces.bean.ManagedBean;
import javax.persistence.*;
import java.util.Set;
#ManagedBean(name = "addToCardBean")
#javax.persistence.Table(name = "cards")
#Entity
public class Card implements java.io.Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
#Column(name="username",nullable = false)
private String username;
#Column(name="text",nullable = false)
private String text;
#Column(name="author")
private String author;
#Column(name="title")
private String title;
#Column (name="source")
private String source;
#Column(name="facebookID" ,columnDefinition="BigInt(20) default '0'")
private long facebookID;
#ElementCollection(targetClass = Tag.class)
private Set<Tag> tags;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getFacebookID() {
return facebookID;
}
public void setFacebookID(long facebookID) {
this.facebookID = facebookID;
}
#ManyToMany(mappedBy = "cards")
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
}
import javax.faces.bean.ManagedBean;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name="tag")
#ManagedBean(name="tagBean")
public class Tag implements java.io.Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;
#Column(name = "tagName", nullable = false)
private String tagName;
#ElementCollection(targetClass = Card.class)
private Set<Card> cards;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "cards_tags",
joinColumns = #JoinColumn(name = "id"),
inverseJoinColumns = #JoinColumn(name = "id")
)
public Set<Card> getCards() {
return cards;
}
public void setCards(Set<Card> cards) {
this.cards = cards;
}
}
You are facing this issue because you have used the annotations both at the field and method(getter) level i.e you have mixed both.
#Column(name = "tagName", nullable = false)
private String tagName;
and
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "cards_tags",
joinColumns = #JoinColumn(name = "id"),
inverseJoinColumns = #JoinColumn(name = "id")
)
public Set<Card> getCards() {
return cards;
}
You have to either use them only on field or only on method(getter). Do not mixup the two.
Why you are ending up with two tables is because the field annotations are getting considered and the many to many mapping is on the getter method which is not being considered.
One way is just use at field level. If annotating at field, change to the following(you need to modify the other entity class as well):
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "cards_tags",
joinColumns = #JoinColumn(name = "id"),
inverseJoinColumns = #JoinColumn(name = "id")
)
#ElementCollection(targetClass = Card.class)
private Set<Card> cards;
You need to make changes in both classes. Move the annotations from getter to field as described above. Or you have to make changes so that all annotations are on getter instead of field.
Additional links:
https://softwareengineering.stackexchange.com/questions/258541/where-to-put-jpa-annotations-field-or-getter
the difference between anotating a field and its getter method JPA

Hibernate Select query returns null foreign object

I have the following entities defined:
Restaurante:
#Entity
#Table(name = "restaurantes")
public class Restaurante implements Serializable {
private int id;
private Set<Menu> menus = new HashSet<>(0);
public Restaurante() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "restaurante_id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonIgnore
#OneToMany(mappedBy = "restaurante")
public Set<Menu> getMenus() {
return menus;
}
public void setMenus(Set<Menu> menus) {
this.menus = menus;
}
}
And menu:
#Entity
#Table(name = "menus")
public class Menu implements Serializable {
private int id;
private Restaurante restaurante;
public Menu() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "menu_id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "restaurante_id", nullable = false)
public Restaurante getRestaurante() {
return restaurante;
}
public void setRestaurante(Restaurante Restaurante) {
this.restaurante = restaurante;
}
}
And when I perform the following query:
public Menu getMenuById(Integer id) throws HibernateException, IndexOutOfBoundsException {
session = HibernateSessionService.getSessionFactory().openSession();
criteria = session.createCriteria(Menu.class)
.add(Restrictions.eq("id", id));
return (Menu) criteria.list().get(0);
}
The property restaurante is null.
There is a restaurante loaded in the database with the Id I'm using, and there are several menus loaded with that foreign key as well.
Can someone give me advice or help me?
Thanks in advance!

Adding data to multiple tables using Spring forms in Spring MVC

I have the following database schema and I need to add data to all three tables using a single view http://i.stack.imgur.com/3HXhC.png (Due to stackoverflow rules, I cannot link the image directly).
What I hope to achieve, is to create an order, have it given an Workshop order id, and have it linked to LineItems which will let the user specify the quantity of items from the Inventory table to be added to the order.
I can create a workshop order in my database, and create a lineitem with the workshop orders id, and add the id and quantity from an inventory item into the lineitem table, and then use the attached code to display each lineitem orderline, with the total amount of items, which item is in the order, total price, customer name etc.
How do I go about creating a view that will let me create an order this way? The flow I imagine is:
Create workshop order -> add line items from inventory -> save the order.
Having worked on Spring and Hibernate for only a couple of weeks, I have not really figured out a smart approach to solve this, but hopefully someone in here has. By all means, feel free to criticize my database scheme, my classes and anything else. It may be a stupid design, not well suited for an actual production system.
I have attached my primary classes involved in this.
LineItems.java
#Entity
#Table(name = "LINE_ITEMS")
#AssociationOverrides({
#AssociationOverride(name = "pk.inventory",
joinColumns = #JoinColumn(name = "INVENTORY_Id")),
#AssociationOverride(name = "pk.workshop",
joinColumns = #JoinColumn(name = "WORKSHOP_ORDERS_Id"))
})
public class LineItems implements Serializable {
private static final long serialVersionUID = 5703588914404465647L;
#EmbeddedId
private LineItemsPK pk = new LineItemsPK();
private int quantity;
public LineItems() {
}
public LineItemsPK getPK() {
return pk;
}
public void setPK(LineItemsPK pk) {
this.pk = pk;
}
#Column(name = "WORKSHOP_ORDERS_Id", nullable=false, updatable=false,
insertable=false)
public Long getWorkshopOrdersId() {
return getPK().getWorkshop().getId();
}
#Column(name = "Id")
#JoinColumn(name="INVENTORY_Id", nullable=false, updatable=false, insertable=false)
public Long getInventoryId() {
return getPK().getInventory().getId();
}
#ManyToOne
public Workshop getWorkshop() {
return getPK().getWorkshop();
}
public void setWorkshop(Workshop workshop) {
getPK().setWorkshop(workshop);
}
#ManyToOne
#JoinColumn(name = "INVENTORY_Id")
public Inventory getInventory() {
return getPK().getInventory();
}
public void setInventory(Inventory inventory) {
getPK().setInventory(inventory);
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LineItems that = (LineItems) o;
if (getPK() != null ? !getPK().equals(that.getPK())
: that.getPK() != null) {
return false;
}
return true;
}
public int hashCode() {
return (getPK() != null ? getPK().hashCode() : 0);
}
}
LineItemsPK.java
#Embeddable
public class LineItemsPK implements Serializable {
private static final long serialVersionUID = -4285130025882317338L;
#ManyToOne
private Inventory inventory;
#ManyToOne
private Workshop workshop;
public Workshop getWorkshop() {
return workshop;
}
public void setWorkshop(Workshop workshop) {
this.workshop = workshop;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
#Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
LineItemsPK that = (LineItemsPK) o;
if(workshop != null ? !workshop.equals(that.workshop) : that.workshop != null) {
return false;
}
if(inventory != null ? !inventory.equals(that.inventory) : that.inventory != null) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result;
result = (workshop != null ? workshop.hashCode() : 0);
result = 31 * result + (inventory != null ? inventory.hashCode() : 0);
return result;
}
}
Workshop.java
#Entity
#Table(name = "WORKSHOP_ORDERS")
public class Workshop implements Serializable {
private static final long serialVersionUID = -8106245965993313684L;
public Long id;
public Long inventoryItemId;
public String workshopService;
public String workshopNotes;
public Long customersId;
public Long paymentId;
private Customer customer;
private Payment payment;
private Set<LineItems> lineItems = new HashSet<LineItems>(0);
public Workshop() {
}
public Workshop(Long inventoryItemId, String workshopService, String workshopNotes,
Customer customer, Payment payment) {
this.inventoryItemId = inventoryItemId;
this.workshopService = workshopService;
this.workshopNotes = workshopNotes;
this.customer = customer;
this.payment = payment;
}
public Workshop(Long inventoryItemId, String workshopService, String workshopNotes,
Customer customer, Payment payment, Set<LineItems> lineItems) {
this.inventoryItemId = inventoryItemId;
this.workshopService = workshopService;
this.workshopNotes = workshopNotes;
this.customer = customer;
this.payment = payment;
this.lineItems = lineItems;
}
#OneToMany(mappedBy = "pk.workshop", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LineItems> getLineItems() {
return this.lineItems;
}
public void setLineItems(Set<LineItems> lineItems) {
this.lineItems = lineItems;
}
#ManyToOne
#JoinColumn(name="CUSTOMERS_Id", nullable = false, insertable = false, updatable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(final Customer customer) {
this.customer = customer;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="PAYMENT_Id", insertable = false, updatable = false, nullable = false)
public Payment getPayment() {
return payment;
}
public void setPayment(final Payment payment) {
this.payment = payment;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", nullable = false)
public Long getId() {
return id;
}
#Column(name = "InventoryItemId")
public Long getInventoryItemId() {
return inventoryItemId;
}
#Column(name = "WorkshopService")
public String getWorkshopService() {
return workshopService;
}
#Column(name = "WorkshopNotes")
public String getWorkshopNotes() {
return workshopNotes;
}
#Column(name = "CUSTOMERS_Id")
public Long getCustomersId() {
return customersId;
}
#Column(name = "PAYMENT_Id")
public Long getPaymentId() {
return paymentId;
}
public void setId(Long id) {
this.id = id;
}
public void setInventoryItemId(Long inventoryItemId) {
this.inventoryItemId = inventoryItemId;
}
public void setWorkshopService(String workshopService) {
this.workshopService = workshopService;
}
public void setWorkshopNotes(String workshopNotes) {
this.workshopNotes = workshopNotes;
}
public void setCustomersId(Long customersId) {
this.customersId = customersId;
}
public void setPaymentId(Long paymentId) {
this.paymentId = paymentId;
}
public String toString() {
return "Customer id: " + this.customersId + "Notes: " + workshopNotes;
}
}
Inventory.java
#Entity
#Table(name = "INVENTORY")
public class Inventory implements Serializable {
private static final long serialVersionUID = -8907719450013387551L;
private Long id;
private String itemName;
private String itemVendorName;
private Long itemInventoryStatus;
private Double itemBuyPrice;
private Double itemSellPrice;
private Set<LineItems> lineItems = new HashSet<LineItems>(0);
public Inventory() {
}
public Inventory(String itemName, String itemVendorName, Long itemInventoryStatus,
Double itemBuyPrice, Double itemSellPrice) {
this.itemName = itemName;
this.itemVendorName = itemVendorName;
this.itemInventoryStatus = itemInventoryStatus;
this.itemBuyPrice = itemBuyPrice;
this.itemSellPrice = itemSellPrice;
}
public Inventory(String itemName, String itemVendorName, Long itemInventoryStatus,
Double itemBuyPrice, Double itemSellPrice, Set<LineItems> lineItems) {
this.itemName = itemName;
this.itemVendorName = itemVendorName;
this.itemInventoryStatus = itemInventoryStatus;
this.itemBuyPrice = itemBuyPrice;
this.itemSellPrice = itemSellPrice;
this.lineItems = lineItems;
}
#OneToMany(mappedBy = "pk.inventory", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LineItems> getLineItems() {
return this.lineItems;
}
public void setLineItems(Set<LineItems> lineItems) {
this.lineItems = lineItems;
}
#Id
#Column(name = "Id", nullable = false)
#GeneratedValue(strategy = IDENTITY)
public Long getId() {
return this.id;
}
#Column(name = "ItemName")
public String getItemName() {
return this.itemName;
}
#Column(name = "ItemVendorName")
public String getItemVendorName() {
return this.itemVendorName;
}
#Column(name = "ItemInventoryStatus")
public Long getItemInventoryStatus() {
return this.itemInventoryStatus;
}
#Column(name = "ItemBuyPrice")
public Double getItemBuyPrice() {
return this.itemBuyPrice;
}
#Column(name = "ItemSellPrice")
public Double getItemSellPrice() {
return this.itemSellPrice;
}
public void setId(Long id) {
this.id = id;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public void setItemVendorName(String itemVendorName) {
this.itemVendorName = itemVendorName;
}
public void setItemInventoryStatus(Long itemInventoryStatus) {
this.itemInventoryStatus = itemInventoryStatus;
}
public void setItemBuyPrice(Double itemBuyPrice) {
this.itemBuyPrice = itemBuyPrice;
}
public void setItemSellPrice(Double itemSellPrice) {
this.itemSellPrice = itemSellPrice;
}
public String toString() {
return "Item id:" + this.id + " ItemName: " + this.itemName +
" ItemInventoryStatus: " + this.itemInventoryStatus +
" ItemBuyPrice: " + this.itemBuyPrice + " ItemSellPrice " + this.itemSellPrice;
}
}
This isn't really a question as it is more of a "how would I do this"
What have you tried already?
Where are you running into trouble?
etc.
Your view logic should not be coupled with your domain layer, what I mean is, you write your forms to be as usable as possible yet, still get the information you need. Once you post the information to the backing Controller, you do the required business logic in order to line up how the entities persist, etc.
Continuing this line of thinking, your controller should only be worried about web layer exceptions, and passing information on to the Business / Service Layer. From the Business / Service layer you execute required logic, and pass on to the Domain / Repository layer. This gives a clear separation of concerns allowing for easier testing.