problem with saving data in many-to-many intermediate table spring boot - spring-boot

following are my entity
package bt.gov.dit.inventoryservice.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
//import org.hibernate.mapping.Set;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "items")
public class Items implements Serializable {
private Long Id;
#Column(name = "item_name")
private String itemName;
// #ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name = "categories_id",nullable = false, referencedColumnName = "id")
private Categories categories;
private Stores stores;
//#Temporal(TemporalType.TIMESTAMP)
#Column(name = "insert_date")
private Date insertDate = new Date();
// #Temporal(TemporalType.TIMESTAMP)
#Column(name = "update_date")
private Date updateDate = new Date();
private Set<Logs> logs = new HashSet<Logs>() ;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
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;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "categories_id", nullable = false, referencedColumnName = "id")
public Categories getCategories() {
return categories;
}
public void setCategories(Categories categories) {
this.categories = categories;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stores_id", nullable = false, referencedColumnName = "id")
public Stores getStores() {
return stores;
}
public void setStores(Stores stores) {
this.stores = stores;
}
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;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "items_logs", joinColumns = #JoinColumn(name = "items_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "logs_id",referencedColumnName = "id") )
public Set<Logs> getLogs() {
return logs;
}
public void setLogs(Set<Logs> logs) {
this.logs = logs;
}
}
package bt.gov.dit.inventoryservice.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "logs")
public class Logs {
private Long id;
#Column(name = "cadet_id")
private Long cadetId;
private Set<Items> items = new HashSet<Items>() ;
#Column(name = "borrowed_date")
//#Temporal(TemporalType.TIMESTAMP)
private Date borrowedDate = new Date();
private String status;
private String comments;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCadetId() {
return cadetId;
}
public void setCadetId(Long cadetId) {
this.cadetId = cadetId;
}
public Date getBorrowedDate() {
return borrowedDate;
}
public void setBorrowedDate(Date borrowedDate) {
this.borrowedDate = borrowedDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
#ManyToMany(fetch = FetchType.LAZY,mappedBy = "logs")
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}
I have many to many relationship between them. Due to that there is an intermediate table created with field item_id and log_id. Now I don't know how to save data in that table. I can save items and i can save log. But I have problem with saving the many-to-many relationship between them?

Related

Spring Boot Rest API Issues

I'm trying to implement a Spring Boot Rest API using Spring Data Jdbc with H2 Database.
This is a microservice, and I'm trying to send a POST request to the microservice from an angular app. I know my POST is working correctly from Angular. Inside of microservice, I am trying to save the POST request to a local H2 database.
This should be relatively straight forward based on documentation I've read online, but I am getting error messages. Any help would be greatly appreciated. Here are the files I have setup inside my spring boot microservice (titled 'order'):
OrderController.java:
package com.clothingfly.order;
import java.util.ListIterator;
import org.springframework.web.client.RestTemplate;
import com.clothingfly.order.Model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.clothingfly.order.Model.Order;
#RestController
#CrossOrigin(origins = "http://localhost:4200")
public class OrderController {
#Autowired
TempOrderRepository orderRepository;
#PostMapping("/order")
public Order postOrder(#RequestBody Order order) {
Order _order = orderRepository.save(new Order(order.getId(), order.getAddress(), order.getPayment(), order.getItems()));
return _order;
}
}
TempOrderRepository.java:
package com.clothingfly.order;
import org.springframework.data.jpa.repository.JpaRepository;
import com.clothingfly.order.Model.Order;
public interface TempOrderRepository extends JpaRepository<Order, Long>{
}
OrderApplication.java:
package com.clothingfly.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
And I have a model named Order.java:
package com.clothingfly.order.Model;
import java.util.List;
import javax.persistence.*;
import org.springframework.data.annotation.Id;
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "Address")
private Address address;
#Column(name = "Payment")
private PaymentInfo payment;
#Column(name = "Items")
private List<Item> items;
#Column(name = "Error")
private String error;
public Order() {
}
public Order(long id, Address address, PaymentInfo payment, List<Item> items){
this.id = id;
this.address = address;
this.payment = payment;
this.items = items;
this.error = "";
}
public long getId() {
return id;
}
public Address getAddress() {
return address;
}
public PaymentInfo getPayment() {
return payment;
}
public List<Item> getItems() {
return items;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
The Order model takes in three other models:
Item.java:
package com.clothingfly.order.Model;
import javax.persistence.*;
#Entity
#Table(name = "items")
public class Item {
#Id
#GeneratedValue
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "price")
private float price;
#Column(name = "imageUrl")
private String imageUrl;
#Column(name = "quantity")
private long quantity;
#Column(name = "inventory")
private long inventory;
public long getId() {
return id;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
public long getQuantity() {
return quantity;
}
public long getInventory() {
return inventory;
}
public String getImageUrl(){
return imageUrl;
}
public void setInventory(long inventory) {
this.inventory = inventory;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(float price) {
this.price = price;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public Item(long id, String name, float price, long quantity, long inventory, String imageUrl) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.inventory = inventory;
this.imageUrl = imageUrl;
}
public Item() {
}
}
Address.java:
package com.clothingfly.order.Model;
import javax.persistence.*;
#Entity
#Table(name = "addresses")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "address")
private String address;
#Column(name = "country")
private String country;
#Column(name = "apartmentNo")
private String apartmentNo;
#Column(name = "state")
private String state;
#Column(name = "city")
private String city;
#Column(name = "zipcode")
private String zipcode;
public Address() {
}
public Address(String firstName, String lastName, String address, String country, String apartmentNo, String state,
String city, String zipcode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.country = country;
this.apartmentNo = apartmentNo;
this.state = state;
this.city = city;
this.zipcode = zipcode;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getApartmentNo() {
return apartmentNo;
}
public void setApartmentNo(String apartmentNo) {
this.apartmentNo = apartmentNo;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
}
PaymentInfo.java:
package com.clothingfly.order.Model;
import javax.persistence.*;
#Entity
#Table(name = "payments")
public class PaymentInfo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "cardHolder")
private String cardHolder;
#Column(name = "cardNumber")
private String cardNumber;
#Column(name = "expirationDate")
private String expirationDate;
#Column(name = "cvv")
private String cvv;
public PaymentInfo(String cardHolder, String cardNumber, String expirationDate, String cvv) {
this.cardHolder = cardHolder;
this.cardNumber = cardNumber;
this.expirationDate = expirationDate;
this.cvv = cvv;
}
public String getCardHolder() {
return cardHolder;
}
public void setCardHolder(String cardHolder) {
this.cardHolder = cardHolder;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
}
I'm getting the following error when trying to run microservice:
Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.clothingfly.order.Model.Address, at table: orders, for columns: [org.hibernate.mapping.Column(address)]
How would I go about fixing this?
I want to be able to display all of my models inside a table.
I tried changing Address model so that it only returns a string of the city, but that seemed to cause more issues than anything.
Note, one to one will always cause you an issue, always better to implement many to one and one to many. and add it to both entities you are mapping. It will do the same job with no errors.
First, create packages, and don't place everything in one package.
create
package com.clothingfly.repo or com.clothingfly.order.repo
package com.clothingfly.controller or com.clothingfly.order.controller
Secondly, add the annotation #Repository to your repository interface
package com.clothingfly.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.clothingfly.order.Model.Order;
#Repository
public interface TempOrderRepository extends JpaRepository<Order, Long>{
}
Thirdly, add the annotation #EnableJpaRepositories(basePackages = "com.clothingfly.repo") to your main application class.
package com.clothingfly.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#EnableJpaRepositories(basePackages = "com.clothingfly.repo")
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
Lastly, this will not work correctly. Not sure what you are doing here.
#Column(name = "Address")
private Address address;
Try this:
add this in your address entity
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name="order_id", nullable = false)// add this column
// order_id in your Address database not the entity
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private Order order;
Then, add this to your Order class.
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="order")
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
List<Address> address = new ArrayList<Address>(); // I use list cause sometimes it throws an error
// try to simply use this, if it throws expection then use the list
//private Address address;
Your Order constructor should be like:
public Order(long id, List<Address> address ...etc
Or simply
public Order(long id, Address address ...etc
Do this for all your mapped entities and don't forget to add setters and getters for all fields.
you have to tell hibernate that the Address object is coming from another table and how to join those tables, since your orders table most likely does not have a column which contains the hole address but the the address id/ primary key of the address as foreign key.
this is possible, depending if you have 1:1, 1:n, n:1 or n:m relations with the corresponding #OneToOne, #OneToMany, #ManyToOne and #ManyToMany annotations.
for your example it could be something like
#OneToOne
#JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;

The primary key of the parent table is the primary key of the child table, How can I map it using jpa?

This is the diagram:
References: https://docs.spring.io/spring-batch/docs/current/reference/html/index-single.html
I get the list from the batch_job_execution_params table but the data is repeated with the information in the first row, the count is correct.
My Entity classes are as follows:
BATCH_JOB_EXECUTION TABLE
package com.maxcom.interfact_services.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "BATCH_JOB_EXECUTION")
public class BatchJobExecutionEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "JOB_EXECUTION_ID", nullable = false)
private Long jobExecutionId;
#Column(name = "VERSION")
private Long version;
#ManyToOne
#JoinColumn(name = "JOB_INSTANCE_ID", nullable = false, updatable = false)
private BatchJobInstanceEntity jobInstanceId;
#Column(name = "CREATE_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date createTime;
#Column(name = "START_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date startTime;
#Column(name = "END_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date endTime;
#Column(name = "STATUS")
private String status;
#Column(name = "EXIT_CODE")
private String exitCode;
#Column(name = "EXIT_MESSAGE")
private String exitMessage;
#Column(name = "LAST_UPDATED")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdated;
#Column(name = "JOB_CONFIGURATION_LOCATION")
private String jobConfigurationLocation;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "batchJobExecutionEntity", orphanRemoval = true)
private Set<BatchStepExecutionEntity> batchSteps;
#JsonManagedReference
#MapsId("jobExecutionId")
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "jobExecutionId", orphanRemoval = true)
// #JsonIgnoreProperties("batchJobExecutionEntity")
private List<BatchJobExecutionParamsEntity> batchJobParams = new ArrayList<>();
public BatchJobExecutionEntity() {
}
public Long getJobExecutionId() {
return jobExecutionId;
}
public void setJobExecutionId(Long jobExecutionId) {
this.jobExecutionId = jobExecutionId;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
#JsonBackReference
public BatchJobInstanceEntity getJobInstanceId() {
return jobInstanceId;
}
public void setJobInstanceId(BatchJobInstanceEntity jobInstanceId) {
this.jobInstanceId = jobInstanceId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getExitCode() {
return exitCode;
}
public void setExitCode(String exitCode) {
this.exitCode = exitCode;
}
public String getExitMessage() {
return exitMessage;
}
public void setExitMessage(String exitMessage) {
this.exitMessage = exitMessage;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public String getJobConfigurationLocation() {
return jobConfigurationLocation;
}
public void setJobConfigurationLocation(String jobConfigurationLocation) {
this.jobConfigurationLocation = jobConfigurationLocation;
}
#JsonManagedReference
public Set<BatchStepExecutionEntity> getBatchSteps() {
return batchSteps;
}
public void setBatchSteps(Set<BatchStepExecutionEntity> batchSteps) {
this.batchSteps = batchSteps;
}
public List<BatchJobExecutionParamsEntity> getBatchJobParams() {
return batchJobParams;
}
public void setBatchJobParams(List<BatchJobExecutionParamsEntity> batchJobParams) {
this.batchJobParams = batchJobParams;
}
}
BATCH_JOB_EXECUTION_PARAMS TABLE
package com.maxcom.interfact_services.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "BATCH_JOB_EXECUTION_PARAMS")
public class BatchJobExecutionParamsEntity implements Serializable {
#Id
// #GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "JOB_EXECUTION_ID", length = 20)
private Long jobExecutionId;
// #JsonBackReference
// #ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name= "JOB_EXECUTION_ID", insertable = false, updatable = false)
// #JsonIgnoreProperties("batchJobParams")
// private BatchJobExecutionEntity batchJobExecutionEntity;
#Column(name = "TYPE_CD", length = 6)
private String typeCd;
#Column(name = "KEY_NAME", length = 100)
private String keyName;
#Column(name = "STRING_VAL", length = 250)
private String stringVal;
#Column(name = "DATE_VAL")
#Temporal(TemporalType.TIMESTAMP)
private Date dateVal;
#Column(name = "LONG_VAL")
private Long longVal;
#Column(name = "DOUBLE_VAL")
private Double doubleVal;
#Column(name = "IDENTIFYING", columnDefinition = "char(1)")
private String identifying;
public BatchJobExecutionParamsEntity() {
}
public Long getJobExecutionId() {
return jobExecutionId;
}
public void setJobExecutionId(Long jobExecutionId) {
this.jobExecutionId = jobExecutionId;
}
public String getTypeCd() {
return typeCd;
}
public void setTypeCd(String typeCd) {
this.typeCd = typeCd;
}
public String getKeyName() {
return keyName;
}
public void setKeyName(String keyName) {
this.keyName = keyName;
}
public String getStringVal() {
return stringVal;
}
public void setStringVal(String stringVal) {
this.stringVal = stringVal;
}
public Date getDateVal() {
return dateVal;
}
public void setDateVal(Date dateVal) {
this.dateVal = dateVal;
}
public Long getLongVal() {
return longVal;
}
public void setLongVal(Long longVal) {
this.longVal = longVal;
}
public Double getDoubleVal() {
return doubleVal;
}
public void setDoubleVal(Double doubleVal) {
this.doubleVal = doubleVal;
}
public String getIdentifying() {
return identifying;
}
public void setIdentifying(String identifying) {
this.identifying = identifying;
}
/*
public BatchJobExecutionEntity getBatchJobExecutionEntity() {
return batchJobExecutionEntity;
}
public void setBatchJobExecutionEntity(BatchJobExecutionEntity batchJobExecutionEntity) {
this.batchJobExecutionEntity = batchJobExecutionEntity;
}
*/
}
How to map 1:N of this scenario?
Having a non-unique primary key is a recipe for disaster (/duplicates).
You missed Appendix B.3:
Note that there is no primary key for this table. This is because the framework has no use for one and, thus, does not require it. If need be, you can add a primary key may be added with a database generated key without causing any issues to the framework itself.
So you can either add a generated primary key to the table and use it as Id or create an EmbeddedId / IdClass on BatchJobExecutionParamsEntity with all the fields.
my solution was the following based on the answer from #Lookslikeitsnot and also to the following article: https://fullstackdeveloper.guru/2021/08/25/what-is-mapsid-used-for-in-jpa-hibernate-part-ii/
The keywords in this scenario were:
#Embeddable
#EmbeddedId
#MapsId
I Share my final code:
- BatchJobExecutionParamsEntity: (Child Table)
package com.maxcom.interfact_services.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "BATCH_JOB_EXECUTION_PARAMS")
public class BatchJobExecutionParamsEntity implements Serializable {
#EmbeddedId
private BatchJobParamIdEmbedded id;
#JsonBackReference
#ManyToOne
#MapsId("jobExecutionId")
#JoinColumn(name= "JOB_EXECUTION_ID", insertable = false, updatable = false)
private BatchJobExecutionEntity batchJobExecutionEntity;
public BatchJobExecutionParamsEntity() {
}
public BatchJobParamIdEmbedded getId() {
return id;
}
public void setId(BatchJobParamIdEmbedded id) {
this.id = id;
}
public BatchJobExecutionEntity getBatchJobExecutionEntity() {
return batchJobExecutionEntity;
}
public void setBatchJobExecutionEntity(BatchJobExecutionEntity batchJobExecutionEntity) {
this.batchJobExecutionEntity = batchJobExecutionEntity;
}
}
- BatchJobParamIdEmbedded: (Embedded Entity)
package com.maxcom.interfact_services.entity;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.io.Serializable;
import java.util.Date;
#Embeddable
public class BatchJobParamIdEmbedded implements Serializable {
private Long jobExecutionId; // composite key class
#Column(name = "TYPE_CD", length = 6)
private String typeCd;
#Column(name = "KEY_NAME", length = 100)
private String keyName;
#Column(name = "STRING_VAL", length = 250)
private String stringVal;
#Column(name = "DATE_VAL")
#Temporal(TemporalType.TIMESTAMP)
private Date dateVal;
#Column(name = "LONG_VAL")
private Long longVal;
#Column(name = "DOUBLE_VAL")
private Double doubleVal;
#Column(name = "IDENTIFYING", columnDefinition = "char(1)")
private String identifying;
public Long getJobExecutionId() {
return jobExecutionId;
}
public void setJobExecutionId(Long jobExecutionId) {
this.jobExecutionId = jobExecutionId;
}
public String getTypeCd() {
return typeCd;
}
public void setTypeCd(String typeCd) {
this.typeCd = typeCd;
}
public String getKeyName() {
return keyName;
}
public void setKeyName(String keyName) {
this.keyName = keyName;
}
public String getStringVal() {
return stringVal;
}
public void setStringVal(String stringVal) {
this.stringVal = stringVal;
}
public Date getDateVal() {
return dateVal;
}
public void setDateVal(Date dateVal) {
this.dateVal = dateVal;
}
public Long getLongVal() {
return longVal;
}
public void setLongVal(Long longVal) {
this.longVal = longVal;
}
public Double getDoubleVal() {
return doubleVal;
}
public void setDoubleVal(Double doubleVal) {
this.doubleVal = doubleVal;
}
public String getIdentifying() {
return identifying;
}
public void setIdentifying(String identifying) {
this.identifying = identifying;
}
}
- BatchJobExecutionEntity: (Parent Table)
package com.maxcom.interfact_services.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Entity
#Table(name = "BATCH_JOB_EXECUTION")
public class BatchJobExecutionEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "JOB_EXECUTION_ID", nullable = false)
private Long jobExecutionId;
#Column(name = "VERSION")
private Long version;
#ManyToOne
#JoinColumn(name = "JOB_INSTANCE_ID", nullable = false, updatable = false)
private BatchJobInstanceEntity jobInstanceId;
#Column(name = "CREATE_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date createTime;
#Column(name = "START_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date startTime;
#Column(name = "END_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date endTime;
#Column(name = "STATUS")
private String status;
#Column(name = "EXIT_CODE")
private String exitCode;
#Column(name = "EXIT_MESSAGE")
private String exitMessage;
#Column(name = "LAST_UPDATED")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdated;
#Column(name = "JOB_CONFIGURATION_LOCATION")
private String jobConfigurationLocation;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "batchJobExecutionEntity", orphanRemoval = true)
private List<BatchStepExecutionEntity> batchSteps;
#JsonManagedReference
#OneToMany(mappedBy = "batchJobExecutionEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private List<BatchJobExecutionParamsEntity> batchJobParams = new ArrayList<>();
public BatchJobExecutionEntity() {
}
public Long getJobExecutionId() {
return jobExecutionId;
}
public void setJobExecutionId(Long jobExecutionId) {
this.jobExecutionId = jobExecutionId;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
#JsonBackReference
public BatchJobInstanceEntity getJobInstanceId() {
return jobInstanceId;
}
public void setJobInstanceId(BatchJobInstanceEntity jobInstanceId) {
this.jobInstanceId = jobInstanceId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getExitCode() {
return exitCode;
}
public void setExitCode(String exitCode) {
this.exitCode = exitCode;
}
public String getExitMessage() {
return exitMessage;
}
public void setExitMessage(String exitMessage) {
this.exitMessage = exitMessage;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public String getJobConfigurationLocation() {
return jobConfigurationLocation;
}
public void setJobConfigurationLocation(String jobConfigurationLocation) {
this.jobConfigurationLocation = jobConfigurationLocation;
}
#JsonManagedReference
public List<BatchStepExecutionEntity> getBatchSteps() {
return batchSteps;
}
public void setBatchSteps(List<BatchStepExecutionEntity> batchSteps) {
this.batchSteps = batchSteps;
}
public List<BatchJobExecutionParamsEntity> getBatchJobParams() {
return batchJobParams;
}
public void setBatchJobParams(List<BatchJobExecutionParamsEntity> batchJobParams) {
this.batchJobParams = batchJobParams;
}
/* Add an batchJobParam to jobExecution Entity to maintain the bi-directional OneToMapping */
public void addBatchJobExecutionParam(BatchJobExecutionParamsEntity batchJobParam) {
this.batchJobParams.add(batchJobParam);
batchJobParam.setBatchJobExecutionEntity(this);
}
}
As shown in the following image, I now get different objects, of course encapsulated in the id (BatchJobParamIdEmbedded):
The second picture shows more details:
Thank you all for your support.
Best regards

Function saves new record for room table instead of booking table (booking table has room_id as foreign key)

Ive tried to save record for booking in the bookings table, but it does not create a record and instead adds a room for the room table which i do not want as the room table is not supposed to change, only records of bookings should be added into the bookings table with a foreign key room_id of the room that was booked.
Any help would be much appreciated! Thanks!
Tbl_Bookings Entity
package com.sam.ResourceBookingMS.model;
import java.io.Serializable;
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.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
#Entity
#Table(name = "Tbl_Bookings")
public class Tbl_Bookings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "booking_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Integer getEmployee_id() {
return employee_id;
}
public void setEmployee_id(Integer employee_id) {
this.employee_id = employee_id;
}
public Integer getEquipment_id() {
return equipment_id;
}
public void setEquipment_id(Integer equipment_id) {
this.equipment_id = equipment_id;
}
#Column(name = "type")
private String type;
#Column(name = "date")
private String date;
#Column(name = "time")
private String time;
#Column(name = "employee_id")
private Integer employee_id;
#Column(name = "equipment_id")
private Integer equipment_id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Tbl_Rooms thisroom;
public Tbl_Rooms getThisroom() {
return thisroom;
}
public void setThisroom(Tbl_Rooms thisroom) {
this.thisroom = thisroom;
}
public Tbl_Bookings() {
}
public Tbl_Bookings(String type, String date, String time, Integer employee_id, Integer equipment_id) {
this.type = type;
this.date = date;
this.time = time;
this.employee_id = employee_id;
this.equipment_id = equipment_id;
}
}
Tbl_Rooms Entity
package com.sam.ResourceBookingMS.model;
import java.io.Serializable;
import java.util.Set;
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.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Tbl_Rooms")
public class Tbl_Rooms implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCapacity() {
return capacity;
}
public void setCapacity(String capacity) {
this.capacity = capacity;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "capacity")
private String capacity;
#Column(name = "location")
private String location;
#Column(name = "description")
private String description;
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "id", orphanRemoval = false, fetch = FetchType.LAZY)
private Set<Tbl_Bookings> bookings;
public Set<Tbl_Bookings> getBookings() {
return bookings;
}
public void setBookings(Set<Tbl_Bookings> bookings) {
this.bookings = bookings;
}
public Tbl_Rooms() {
}
public Tbl_Rooms(String name, String capacity, String location, String description) {
this.name = name;
this.capacity = capacity;
this.location = location;
this.description = description;
}
}
Controller
package com.sam.ResourceBookingMS;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.sam.ResourceBookingMS.model.Tbl_Bookings;
import com.sam.ResourceBookingMS.model.Tbl_Rooms;
#RestController
public class BookRmController {
#Autowired
private TblBkRepository tbr;
#Autowired
private TblRmRepository trr;
#Autowired
private EntityManager entityManager;
#RequestMapping(value = "/bookRm", method = RequestMethod.POST)
#ResponseBody
public String sendData(#RequestBody Tbl_Bookings bk) {
Tbl_Rooms rm = entityManager.getReference(Tbl_Rooms.class, 1);
System.out.println(rm.getId());
Tbl_Bookings booking = new Tbl_Bookings();
booking.setDate(bk.getDate());
booking.setType(bk.getType());
booking.setTime(bk.getTime());
Tbl_Rooms room = new Tbl_Rooms();
room.setCapacity(rm.getCapacity());
room.setDescription(rm.getDescription());
room.setLocation(rm.getLocation());
room.setName(rm.getName());
Set<Tbl_Bookings> bookingOfRoom = new HashSet<Tbl_Bookings>();
bookingOfRoom.add(booking);
room.setBookings(bookingOfRoom);
booking.setThisroom(room);
trr.save(room);
return "Confirmed";
}
}
This is the json data being sent to the controller.
{"room_id":2,"date":"2019-07-26","time":"10:00am to 10:30am","type":"Room"}
mappedBy in parent must be matched with a name defined in the child
(change id to thisroom)
case: "save Child with Parents ID" (might be above UseCase)
For that, we have to request the Child Entity with Parent ID (see JSON request at the controller and set the Parent for that Child) and using Child Repository save the object instead of using parent repository.
case: "save child-parent at same request"
For that, we have to request the Parent Entity which has multiple children (for OneToMany) and using for setting the childerns
Parent
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private Set<Tbl_Bookings> bookings;
Child
#ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "room_id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Tbl_Rooms thisroom;
Parent-Child Relationship for referance
Parent.java
#Entity
#Table(name = "parent")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int parentId;
private String name;
#OneToMany(mappedBy="parent",fetch=FetchType.LAZY,cascade = CascadeType.PERSIST)
private List<Child> child = new ArrayList<Child>();
}
Child.java
#Entity
#Table(name = "child")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int childId;
private String account;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = Parent.class)
#JoinColumn(name="parentId", referencedColumnName = "parentId", nullable = false)
private Parent parent;
}
Controller
#RestController
public class RelationshipController {
#Autowired ParentRepository parentRepository;
#Autowired ChildRepository childRepository;
//save Child with Parent at same
#PostMapping(value = "/onetomany")
public String OneToMany(#RequestBody Parent parent)
{
for (Child child : parent.getChild()) {
child.setParent(parent);
}
parent.setChild(parent.getChild());
parentRepository.save(parent);
return "saved";
/*{
"name":"Romil",
"child":[
{"account":"1"},
{"account":"2"}
]
}*/
}
//save Child with Parent's ID
#PostMapping(value = "/onetomanyPID")
public String OneToMany(#RequestBody Child child)
{
child.setParent(child.getParent());;
childRepository.save(child);
return "saved";
/*{
"account":"3",
"parent":{
"parentId":"1",
"name":"Romil"
}
}*/
}
}
UPDATE
Controller
#PostMapping("/save")
public String save(#RequestBody Tbl_Bookings bookings)
{
bookings.setThisroom(bookings.getThisroom());
tbr.save(bookings);
return "Confirmed";
}
JSON
{
"thisroom":{
"id":"1"
},
"date":"2019-07-26",
"time":"10:00am to 10:30am",
"type":"Room"
}
Tbl_Bookings
#Entity
#Table(name = "Tbl_Bookings")
public class Tbl_Bookings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "booking_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", referencedColumnName = "room_id")
private Tbl_Rooms thisroom;
}
Tbl_Rooms
#Entity
#Table(name = "Tbl_Rooms")
public class Tbl_Rooms implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "room_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
private List<Tbl_Bookings> bookings = new ArrayList<Tbl_Bookings>();
}
There are two points you made mistakes.
First) You need to change OneToMany relation in Tbl_Rooms class as below:
#OneToMany(targetEntity = Tbl_Bookings.class, mappedBy = "thisroom", orphanRemoval = false, fetch = FetchType.LAZY)
private Set<Tbl_Bookings> bookings;
The mappedBy attribute should be the class member of owner side.
Second) You create a new Tbl_Rooms instance in controller. So it is natural a new record would be created for rooms too.

Spring Hibernate lazy load behavior

I am making a web based app in spring/hibernate. In database I am using onetomany and manytoone relations. I have manytoone relationship in users for location and onetomany relationship for users in location. In both entities I have lazy loading option turned on. As per my understanding if this is turned on, the database query to get the location should not be executed until explicitly called for it but whenever I do a get from the userdao the below query is executed which makes me think that even after having the lazy option turned on it is retrieving the location information. Can anyone let me know what am I doing wrong or is this the expected behavior.
Below is my user entity code
package com.kwisque.database.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "USERS")
public class User implements Serializable{
#Id
#Column(name = "USER_ID", unique = true, nullable = false)
private String userId;
#Column(name = "NAME", nullable = true, length = 32)
private String name;
#Column(name = "PASSWORD", nullable = false, length = 64)
private String password;
#Column(name = "EMAIL_ID", nullable = true, length = 128)
private String emailId;
#Column(name = "ACTIVE", nullable = false, length = 1)
private Integer active;
#Column(name = "PROVIDER", nullable = false, length = 32)
private String provider;
#ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinTable(
name = "USER_ROLE",
joinColumns = #JoinColumn(name = "USER_ID"),
inverseJoinColumns = #JoinColumn(name = "ROLE_ID")
)
private Set<Role> roles = new HashSet<>();
//#ManyToOne(fetch = FetchType.LAZY)
//#JoinColumn(name = "LOCATION_ID", nullable = true)
#ManyToOne(fetch=FetchType.LAZY, cascade={javax.persistence.CascadeType.ALL})
#JoinTable(name="USER_LOCATION_INFO",
joinColumns={#javax.persistence.JoinColumn(name="USER_ID")},
inverseJoinColumns={#javax.persistence.JoinColumn(name="LOCATION_ID")})
private Location location;
// #OneToMany(fetch = FetchType.LAZY)
// #JoinColumn(name = "SPECIALIZATION_ID", nullable = true)
#OneToMany(fetch=FetchType.LAZY, cascade={javax.persistence.CascadeType.ALL})
#JoinTable(name="USER_SPECIALIZATION_INFO",
joinColumns={#javax.persistence.JoinColumn(name="USER_ID")},
inverseJoinColumns={#javax.persistence.JoinColumn(name="SPECIALIZATION_ID")})
private Set<Specialization> specialization = new HashSet<>();
public User() {
}
public User(final String userId, final String name, final String password, final String emailId, final Integer active, final String provider, final Set<Role> roles, final Location location) {
this.userId = userId;
this.name = name;
this.password = password;
this.emailId = emailId;
this.active = active;
this.provider = provider;
this.roles = roles;
this.location = location;
}
public String getUserId() {
return userId;
}
public void setUserId(final String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public Integer getActive() {
return active;
}
public void setActive(final Integer active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(final Set<Role> roles) {
this.roles = roles;
}
public String getProvider() {
return provider;
}
public void setProvider(final String provider) {
this.provider = provider;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(final String emailId) {
this.emailId = emailId;
}
public Location getLocation() {
return location;
}
public void setLocation(final Location location) {
this.location = location;
}
}
Location entity code
package com.kwisque.database.model;
import java.io.Serializable;
import java.util.Set;
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.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name = "LOCATION")
public class Location implements Serializable {
private static final long serialVersionUID = -7153748534015057865L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "LOCATION_ID", unique = true, nullable = false)
private Integer locationId;
#Column(name = "ZIP_CODE", nullable = true, length = 132)
private String zipCode;
#Column(name = "STATE_ABBR", nullable = true, length = 132)
private String stateAbbr;
#Column(name = "LATITUDE", nullable = true, length = 132)
private double latitude;
#Column(name = "LONGITUDE", nullable = true, length = 132)
private double longitude;
#Column(name = "CITY", nullable = true, length = 132)
private String city;
#Column(name = "STATE", nullable = true, length = 132)
private String state;
#JsonIgnore
#OneToMany(fetch = FetchType.LAZY, mappedBy = "location")
private Set<User> users;
public double getLatitude() {
return this.latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return this.longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public Location() {
}
public Location(Integer locationId, long longitude, String city, long latitude, String zipCode, String state,
String stateAbbr, Set<User> users) {
this.locationId = locationId;
this.longitude = longitude;
this.latitude = latitude;
this.city = city;
this.state = state;
this.stateAbbr = stateAbbr;
this.users = users;
}
public Integer getLocationId() {
return this.locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
#JsonIgnore
public Set<User> getUser() {
return this.users;
}
#JsonIgnore
public void setUser(Set<User> users) {
this.users = users;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return this.zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getStateAbbr() {
return this.stateAbbr;
}
public void setStateAbbr(String stateAbbr) {
this.stateAbbr = stateAbbr;
}
}
Query being executed at my get from USerDao
Hibernate: select user0_.USER_ID as USER_ID1_3_0_, user0_.ACTIVE as ACTIVE2_3_0_, user0_.EMAIL_ID as EMAIL_ID3_3_0_, user0_.NAME as NAME4_3_0_, user0_.PASSWORD as PASSWORD5_3_0_, user0_.PROVIDER as PROVIDER6_3_0_, user0_1_.LOCATION_ID as LOCATION1_4_0_, roles1_.USER_ID as USER_ID1_3_1_, role2_.ROLE_ID as ROLE_ID2_5_1_, role2_.ROLE_ID as ROLE_ID1_1_2_, role2_.NAME as NAME2_1_2_ from USERS user0_ left outer join USER_LOCATION_INFO user0_1_ on user0_.USER_ID=user0_1_.USER_ID left outer join USER_ROLE roles1_ on user0_.USER_ID=roles1_.USER_ID left outer join ROLE role2_ on roles1_.ROLE_ID=role2_.ROLE_ID where user0_.USER_ID=?

Updating null value for foreign key

I am working with JPA and I am trying to insert foreign key value its working fine but during modifying it is updating null values..
Please Refer following code
package com.bcits.bfm.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="JOB_CALENDER")
public class JobCalender implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int jobCalenderId;
private int scheduleType;
private String title;
private String description;
private String recurrenceRule;
private String recurrenceException;
private int recurrenceId;
private boolean isAllDay;
private Date start;
private Date end;
private String jobNumber;
private String jobGroup;
private int expectedDays;
private String jobPriority;
private String jobAssets;
private MaintainanceTypes maintainanceTypes;
private MaintainanceDepartment departmentName;
private JobTypes jobTypes;
#Id
#Column(name="JOB_CALENDER_ID")
#SequenceGenerator(name = "JOB_CALENDER_SEQUENCE", sequenceName = "JOB_CALENDER_SEQUENCE")
#GeneratedValue(generator = "JOB_CALENDER_SEQUENCE")
public int getJobCalenderId() {
return jobCalenderId;
}
public void setJobCalenderId(int jobCalenderId ) {
this.jobCalenderId = jobCalenderId ;
}
#Column(name="SCHEDULE_TYPE")
public int getScheduleType() {
return scheduleType;
}
public void setScheduleType(int scheduleType) {
this.scheduleType = scheduleType;
}
#Column(name="START_DATE")
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
#Column(name="END_DATE")
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
#Column(name="Title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="RECURRENCE_RULE")
public String getRecurrenceRule() {
return recurrenceRule;
}
public void setRecurrenceRule(String recurrenceRule) {
this.recurrenceRule = recurrenceRule;
}
#Column(name="IS_ALL_DAY")
public boolean getIsAllDay() {
return isAllDay;
}
public void setIsAllDay(boolean isAllDay) {
this.isAllDay = isAllDay;
}
#Column(name="RECURENCE_EXCEPTION")
public String getRecurrenceException() {
return recurrenceException;
}
public void setRecurrenceException(String recurrenceException) {
this.recurrenceException = recurrenceException;
}
#Column(name="RECURRENCE_ID")
public int getRecurrenceId() {
return recurrenceId;
}
public void setRecurrenceId(int recurrenceId) {
this.recurrenceId = recurrenceId;
}
/*Custom Columns*/
#Column(name = "JOB_NUMBER", nullable = false, length = 45)
public String getJobNumber() {
return this.jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
#Column(name = "JOB_GROUP", nullable = false, length = 45)
public String getJobGroup() {
return this.jobGroup;
}
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}
#Column(name = "EXPECTED_DAYS", nullable = false, precision = 11, scale = 0)
public int getExpectedDays() {
return this.expectedDays;
}
public void setExpectedDays(int expectedDays) {
this.expectedDays = expectedDays;
}
#Column(name = "JOB_PRIORITY", nullable = false, length = 45)
public String getJobPriority() {
return this.jobPriority;
}
public void setJobPriority(String jobPriority) {
this.jobPriority = jobPriority;
}
#Column(name = "JOB_ASSETS", nullable = false, length = 4000)
public String getJobAssets() {
return this.jobAssets;
}
public void setJobAssets(String jobAssets) {
this.jobAssets = jobAssets;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_DEPT_ID",referencedColumnName="MT_DP_IT",nullable = false)
public MaintainanceDepartment getMaintainanceDepartment() {
return this.departmentName;
}
public void setMaintainanceDepartment(
MaintainanceDepartment departmentName) {
this.departmentName = departmentName;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_TYPE_ID",referencedColumnName="JT_ID",nullable = false)
public JobTypes getJobTypes() {
return this.jobTypes;
}
public void setJobTypes(JobTypes jobTypes) {
this.jobTypes = jobTypes;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "MAINTAINANCE_TYPE_ID",nullable = false)
public MaintainanceTypes getMaintainanceTypes() {
return this.maintainanceTypes;
}
public void setMaintainanceTypes(MaintainanceTypes maintainanceTypes) {
this.maintainanceTypes = maintainanceTypes;
}
}
And Parent Table Is
package com.bcits.bfm.model;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* MaintainanceTypes entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "MAINTAINANCE_TYPES")
public class MaintainanceTypes implements java.io.Serializable {
private static final long serialVersionUID = 1L;
// Fields
private int mtId;
private String maintainanceType;
private String description;
private Timestamp mtDt;
private String createdBy;
private String lastUpdatedBy;
private Timestamp lastUpdatedDt;
private Set<JobCards> jobCardses = new HashSet<JobCards>(0);
private Set<JobCalender> jobCalenders = new HashSet<JobCalender>(0);
// Constructors
/** default constructor */
public MaintainanceTypes() {
}
/** minimal constructor */
public MaintainanceTypes(int mtId, String maintainanceType, Timestamp mtDt) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.mtDt = mtDt;
}
/** full constructor */
public MaintainanceTypes(int mtId, String maintainanceType,
String description, Timestamp mtDt, String createdBy,
String lastUpdatedBy, Timestamp lastUpdatedDt,
Set<JobCards> jobCardses) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.description = description;
this.mtDt = mtDt;
this.createdBy = createdBy;
this.lastUpdatedBy = lastUpdatedBy;
this.lastUpdatedDt = lastUpdatedDt;
this.jobCardses = jobCardses;
}
// Property accessors
#Id
#Column(name = "MT_ID", unique = true, nullable = false, precision = 11, scale = 0)
#SequenceGenerator(name = "MAINTENANCE_TYPES_SEQ", sequenceName = "MAINTENANCE_TYPES_SEQ")
#GeneratedValue(generator = "MAINTENANCE_TYPES_SEQ")
public int getMtId() {
return this.mtId;
}
public void setMtId(int mtId) {
this.mtId = mtId;
}
#Column(name = "MAINTAINANCE_TYPE", nullable = false, length = 20)
public String getMaintainanceType() {
return this.maintainanceType;
}
public void setMaintainanceType(String maintainanceType) {
this.maintainanceType = maintainanceType;
}
#Column(name = "DESCRIPTION", length = 200)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "MT_DT", nullable = false, length = 11)
public Timestamp getMtDt() {
return this.mtDt;
}
public void setMtDt(Timestamp mtDt) {
this.mtDt = mtDt;
}
#Column(name = "CREATED_BY", length = 45)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "LAST_UPDATED_BY", length = 45)
public String getLastUpdatedBy() {
return this.lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
#Column(name = "LAST_UPDATED_DT", length = 11)
public Timestamp getLastUpdatedDt() {
return this.lastUpdatedDt;
}
public void setLastUpdatedDt(Timestamp lastUpdatedDt) {
this.lastUpdatedDt = lastUpdatedDt;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCards> getJobCardses() {
return this.jobCardses;
}
public void setJobCardses(Set<JobCards> jobCardses) {
this.jobCardses = jobCardses;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCalender> getJobCalenders() {
return this.jobCalenders;
}
public void setJobCalenders(Set<JobCalender> jobCalenders) {
this.jobCalenders = jobCalenders;
}
}
I am calling below method to Update
public void Update(JobCalender jobCalender) {
update(jobCalender); //update() is generic method
}
public T update(final T t) {
BfmLogger.logger.info("updating "+t+" instance");
try {
T result = this.entityManager.merge(t);
BfmLogger.logger.info("update successful");
return result;
} catch (RuntimeException re) {
BfmLogger.logger.error("update failed", re);
throw re;
}
}
My Controller Code
#RequestMapping(value = "/index/create", method = RequestMethod.POST)
public #ResponseBody List<?> create(#RequestBody Map<String, Object>model,#ModelAttribute JobCalender jobCalender,BindingResult bindingResult, HttpServletRequest request) throws ParseException {
jobCalender.setDescription((String)model.get("description"));
jobCalender.setTitle((String)model.get("title"));
SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-M-dd'T'HH:mm:ss.SSS'Z'");
iso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
jobCalender.setStart(iso8601.parse((String)model.get("start")));
jobCalender.setEnd(iso8601.parse((String)model.get("end")));
jobCalender.setIsAllDay((boolean) model.get("isAllDay"));
jobCalender.setRecurrenceRule((String)model.get("recurrenceRule"));
jobCalender.setRecurrenceException((String)model.get("recurrenceException"));
if(model.get("recurrenceId")!=null)
jobCalender.setRecurrenceId((Integer)model.get("recurrenceId"));
jobCalender.setScheduleType(Integer.parseInt(model.get("scheduleType").toString()));
jobCalender.setJobNumber((String) model.get("jobNumber"));
jobCalender.setDescription((String) model.get("description"));
jobCalender.setJobGroup((String) model.get("jobGroup"));
jobCalender.setMaintainanceDepartment(maintainanceDepartmentService.find(Integer.parseInt(model.get("departmentName").toString())));
jobCalender.setMaintainanceTypes(maintainanceTypesService.find(Integer.parseInt(model.get("maintainanceTypes").toString())));
jobCalender.setJobTypes(jobTypesService.find(Integer.parseInt(model.get("jobTypes").toString())));
jobCalender.setJobPriority((String) model.get("jobPriority"));
String ids="";
#SuppressWarnings("unchecked")
List<Map<String, Object>> listAssets = (ArrayList<Map<String, Object>>) model.get("assetName");// this is what you have already
for (Map<String, Object> map1 :listAssets) {
for (Map.Entry<String, Object> entry : map1.entrySet()) {
if(entry.getKey().equalsIgnoreCase("assetId")){
ids+=entry.getValue()+",";
}
}
}
jobCalender.setJobAssets(ids);
jobCalenderService.Update(jobCalender);
}
while Updating JOB_CALENDER Table it is Adding NULL Value For MAINTAINANCE_TYPE_ID Column
Please Help Me
Thank You
Regards
Manjunath Kotagi

Resources