I am new to the JPA world. Here I have tried to make a simple POS. The problem is that when there is no predefined value in tables although the PK is auto-incremented, data is not being inserted into DB. But if I set a predefined row into the tables then there are no issues and data is being inserted successfully. please help me.
The following are my Java classes, and I am using Mysql for DB.
#Entity
#Table(name = "card_payment")
public class Card_payment {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "order_id")
private Orders order;
#Column(name = "issuing_bank")
String issuing_bank;
#Column(name = "card_type")
String card_type;
#Column(name = "card_expiry_date")
String card_expiry_date;
#Column(name = "amount")
int amount;
public Card_payment() {
super();
}
public Orders getOrder() {
return order;
}
public void setOrder(Orders order) {
this.order = order;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIssuing_bank() {
return issuing_bank;
}
public void setIssuing_bank(String issuing_bank) {
this.issuing_bank = issuing_bank;
}
public String getCard_type() {
return card_type;
}
public void setCard_type(String card_type) {
this.card_type = card_type;
}
public String getCard_expiry_date() {
return card_expiry_date;
}
public void setCard_expiry_date(String card_expiry_date) {
this.card_expiry_date = card_expiry_date;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
#Entity
#Table(name = "customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#Column(name = "name")
String name;
#Column(name = "mobile_no")
long mobile_no;
#Column(name = "address")
String address;
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL,
fetch=FetchType.LAZY)
private List<Orders> orders;;
public Customer() {
super();
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
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 long getMobile_no() {
return mobile_no;
}
public void setMobile_no(long mobile_no) {
this.mobile_no = mobile_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
#Entity
#Table(name = "Item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#Column(name = "name")
String name;
#Column(name = "unit")
String unit;
#Column(name = "stock_quantity")
int stock_quantity;
#Column(name = "reorder_level")
int reorder_level;
#Column(name = "unit_price")
int unit_price;
#Column(name = "tax_percentage")
float tax_percentage;
#OneToMany(mappedBy = "item", cascade = CascadeType.ALL,
fetch=FetchType.LAZY)
private List<Orderline> orderLines;
public Item() {
super();
}
public List<Orderline> getOrderLines() {
return orderLines;
}
public void setOrderLines(List<Orderline> orderLines) {
this.orderLines = orderLines;
}
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 getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public int getStock_quantity() {
return stock_quantity;
}
public void setStock_quantity(int stock_quantity) {
this.stock_quantity = stock_quantity;
}
public int getReorder_level() {
return reorder_level;
}
public void setReorder_level(int reorder_level) {
this.reorder_level = reorder_level;
}
public int getUnit_price() {
return unit_price;
}
public void setUnit_price(int unit_price) {
this.unit_price = unit_price;
}
public float getTax_percentage() {
return tax_percentage;
}
public void setTax_percentage(float tax_percentage) {
this.tax_percentage = tax_percentage;
}
}
#Entity
#Table(name = "OrderLine")
public class Orderline {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#ManyToOne
#JoinColumn(name = "itemId")
private Item item;
#ManyToOne
#JoinColumn(name = "orderId")
private Orders orders;
#Column(name = "unit_cost")
float unit_cost;
#Column(name = "unit")
int unit;
#Column(name = "tax_percentage")
float tax_percentage;
#Column(name = "quantity")
int quantity;
#Column(name = "amount")
int amount;
#Column(name = "tax_amount")
float tax_amount;
#Column(name = "line_total")
int line_total;
public Orderline() {
super();
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Orders getOrders() {
return orders;
}
public void setOrders(Orders orders) {
this.orders = orders;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getUnit_cost() {
return unit_cost;
}
public void setUnit_cost(float unit_cost) {
this.unit_cost = unit_cost;
}
public int getUnit() {
return unit;
}
public void setUnit(int unit) {
this.unit = unit;
}
public float getTax_percentage() {
return tax_percentage;
}
public void setTax_percentage(float tax_percentage) {
this.tax_percentage = tax_percentage;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public float getTax_amount() {
return tax_amount;
}
public void setTax_amount(float tax_amount) {
this.tax_amount = tax_amount;
}
public int getLine_total() {
return line_total;
}
public void setLine_total(int line_total) {
this.line_total = line_total;
}
#Entity
#Table(name = "orders")
public class Orders {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#ManyToOne
#JoinColumn(name = "customerId")
private Customer customer;
#Column(name = "order_date")
String order_date;
#Column(name = "delivery_address")
String delivery_address;
#Column(name = "total")
long total;
#OneToMany(mappedBy = "orders", cascade = CascadeType.ALL,
fetch=FetchType.LAZY)
private List<Orderline> orderlines;
#OneToOne(mappedBy = "order")
private Cash_payment cash_payment;
#OneToOne(mappedBy = "order")
private Card_payment card_payment;
#OneToOne(mappedBy = "order")
private Cheque_payment cheque_payment;
public Orders() {
super();
}
public Cash_payment getCash_payment() {
return cash_payment;
}
public void setCash_payment(Cash_payment cash_payment) {
this.cash_payment = cash_payment;
}
public Card_payment getCard_payment() {
return card_payment;
}
public void setCard_payment(Card_payment card_payment) {
this.card_payment = card_payment;
}
public Cheque_payment getCheque_payment() {
return cheque_payment;
}
public void setCheque_payment(Cheque_payment cheque_payment) {
this.cheque_payment = cheque_payment;
}
public List<Orderline> getOrderlines() {
return orderlines;
}
public void setOrderlines(List<Orderline> orderlines) {
this.orderlines = orderlines;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date = order_date;
}
public String getDelivery_address() {
return delivery_address;
}
public void setDelivery_address(String delivery_address) {
this.delivery_address = delivery_address;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
}
public class JPAExample {
private static EntityManager entityManager = EntityManagerUtil.getEntityManager();
public static void main(String[] args) {
JPAExample example = new JPAExample();
entityManager.getTransaction().begin();
Orders order = new Orders();
order.setOrder_date("2019/05/05");
order.setTotal(1000);
order.setDelivery_address("kolkata");
Item item = new Item();
item.setName("cream");
item.setReorder_level(10);
item.setUnit_price(10);
item.setUnit("kg");
item.setTax_percentage((float) 12.5);
item.setStock_quantity(20);
item.setReorder_level(5);
Orderline orderline = new Orderline();
orderline.setAmount(1);
orderline.setItem(item);
orderline.setLine_total(200);
orderline.setQuantity(1);
List<Orderline> orderlns = new ArrayList<>();
orderlns.add(orderline);
item.setOrderLines(orderlns);
Customer customer = new Customer();
customer.setId(1234);
customer.setName("Tanusha");
customer.setMobile_no(Long.valueOf("9609"));
customer.setAddress("u-86, garia");
orderline.setOrders(order);
List<Orderline> orderLinesList = new ArrayList<>();
orderLinesList.add(orderline);
order.setOrderlines(orderLinesList);
order.setCustomer(customer);
List<Orders> orderList = new ArrayList<>();
orderList.add(order);
customer.setOrders(orderList);
Card_payment cp = new Card_payment();
cp.setAmount(200);
cp.setCard_expiry_date("2019/05/05");
cp.setCard_type("visa");
cp.setIssuing_bank("SBI");
cp.setOrder(order);
order.setCard_payment(cp);
entityManager.merge(order);
try {
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
}
Related
I've created ManyToMany tables with extra column that's named reqserviceguest_details, then I've tested with filling on my jsp page form to insert the data. When the all data inserted, everything is fine except my servicelaundry_id. It's null and I have no idea why it happened.
ReqServiceGuestDetails.class
#Entity
#Table(name = "reqserviceguest_details")
public class ReqServiceGuestDetails {
#Id
#Column(name = "reqserviceguest_details_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
#ManyToOne
#JoinColumn(name = "reqserviceguest_id")
private ReqServiceGuest reqServiceGuest;
#ManyToOne
#JoinColumn(name = "servicelaundry_id")
private ServiceLaundry serviceLaundry;
private int amount;
public ReqServiceGuestDetails() {
}
public ReqServiceGuestDetails(ReqServiceGuest reqServiceGuest, ServiceLaundry serviceLaundry, int amount) {
this.reqServiceGuest = reqServiceGuest;
this.serviceLaundry = serviceLaundry;
this.amount = amount;
}
public ReqServiceGuest getReqServiceGuest() {
return reqServiceGuest;
}
public void setReqServiceGuest(ReqServiceGuest reqServiceGuest) {
this.reqServiceGuest = reqServiceGuest;
}
public ServiceLaundry getServiceLaundry() {
return serviceLaundry;
}
public void setServiceLaundry(ServiceLaundry serviceLaundry) {
this.serviceLaundry = serviceLaundry;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
ReqServiceGuest.class
#Entity
#Table(name = "reqserviceguest")
public class ReqServiceGuest {
#Id
#Column(name = "reqserviceguest_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
int id;
#Column(nullable = false, unique = true)
private String reqServiceGuestId;
private Date reqDate;
private Date pickDate;
private String type;
private String serviceStatus;
private String guestName;
private String guestTelNo;
#OneToMany(mappedBy = "reqServiceGuest", cascade = CascadeType.ALL)
private Set<ReqServiceGuestDetails> reqServiceGuestDetails = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReqServiceGuestId() {
return reqServiceGuestId;
}
public void setReqServiceGuestId(String reqServiceGuestId) {
this.reqServiceGuestId = reqServiceGuestId;
}
public Date getReqDate() {
return reqDate;
}
public void setReqDate(Date reqDate) {
this.reqDate = reqDate;
}
public Date getPickDate() {
return pickDate;
}
public void setPickDate(Date pickDate) {
this.pickDate = pickDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public String getGuestName() {
return guestName;
}
public void setGuestName(String guestName) {
this.guestName = guestName;
}
public String getGuestTelNo() {
return guestTelNo;
}
public void setGuestTelNo(String guestTelNo) {
this.guestTelNo = guestTelNo;
}
public Set<ReqServiceGuestDetails> getReqServiceGuestDetails() {
return reqServiceGuestDetails;
}
public void setReqServiceGuestDetails(Set<ReqServiceGuestDetails> reqServiceGuestDetails) {
this.reqServiceGuestDetails = reqServiceGuestDetails;
}
}
ServiceLaundry.class
#Entity
#Table(name = "servicelaundry")
public class ServiceLaundry {
#Id
#Column(name = "servicelaundry_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
int id;
#Column(nullable = false, unique = true)
private String serviceId;
private String serviceName;
private int price;
#OneToMany(mappedBy = "serviceLaundry")
private Set<ReqServiceGuestDetails> reqServiceGuestDetails = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And this is form processor in a controller
#RequestMapping(path = "/savereqserviceguest", method = RequestMethod.GET)
public String processAddReqServiceGuestForm (ReqServiceGuest reqServiceGuest, #RequestParam Map<String, String> allParams) {
int latestId = reqServiceGuestService.getLatestReqServiceGuestId();
reqServiceGuest.setReqServiceGuestId(generateReqServiceGuestId(latestId));
reqServiceGuest.setServiceStatus("NP");
/*
for (Map.Entry<String, String> entry : allParams.entrySet()) {
if (entry.getKey().contains("service")) {
String getServiceId = String.valueOf(entry.getKey().charAt(7));
reqServiceGuest.getReqServiceGuestServiceLaundry().add();
}
}
reqServiceGuest.setReqServiceGuestServiceLaundry(serviceGuestDetails);
*/
ServiceLaundry service1 = serviceLaundryService.getServiceLaundry(1);
ServiceLaundry service2 = serviceLaundryService.getServiceLaundry(2);
ReqServiceGuestDetails reqServiceGuestDetails1 = new ReqServiceGuestDetails(reqServiceGuest, service1, 55);
ReqServiceGuestDetails reqServiceGuestDetails2 = new ReqServiceGuestDetails(reqServiceGuest, service2, 35);
reqServiceGuest.getReqServiceGuestDetails().add(reqServiceGuestDetails1);
reqServiceGuest.getReqServiceGuestDetails().add(reqServiceGuestDetails2);
Calendar cReqDate = Calendar.getInstance();
if (reqServiceGuest.getType().equals("Ordinary")) {
Date reqDate = cReqDate.getTime();
reqServiceGuest.setReqDate(reqDate);
Calendar cPickDate = Calendar.getInstance();
cPickDate.add(Calendar.DATE, 5);
Date pickDate = cPickDate.getTime();
reqServiceGuest.setPickDate(pickDate);
} else {
Date reqDate = cReqDate.getTime();
reqServiceGuest.setReqDate(reqDate);
Calendar cPickDate = Calendar.getInstance();
cPickDate.add(Calendar.DATE, 2);
Date pickDate = cPickDate.getTime();
reqServiceGuest.setPickDate(pickDate);
}
reqServiceGuestService.saveReqServiceGuest(reqServiceGuest);
return "redirect:/home";
}
And the final result is
Result
orders.java
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "created_at")
private Date createdAt;
#OneToMany
private List<Product> orderItem;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public List<Product> getOrderItem() {
return orderItem;
}
public void setOrderItem(List<Product> orderItem) {
this.orderItem = orderItem;
}
OrderProduct.java
#Entity
#Table(name = "orders_product")
public class OrderProduct {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "order_id")
private int orderId;
#Column(name = "orderItem_id")
private int orderItemId;
#Column(name = "quantity")
private int quantity;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getOrderItemId() {
return orderItemId;
}
public void setOrderItemId(int orderItemId) {
this.orderItemId = orderItemId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
Product.java
#Entity
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="code")
private String code;
#Column(name="name")
private String name;
#Column(name="price")
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Product [id=" + id + ", code=" + code + ", name=" + name + ", price=" + price + "]";
}
}
I try to save the from the order and set the orderItem, and only the order id
and product id that have been inserted to the table, I try to insert the quantity also, but don't know how to do it.
i have two entity classes named Qa.java and Answeres.java
my Qa entity consists of lists of answers.
Qa.Java
#Entity
#Table(name = "qa")
public class Qa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private String question;
private String type;
private String description;
private String param;
private int maxlength;
#OneToMany(mappedBy = "qa", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Answers> answersList = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
}
Answers.java
#Entity
#Table(name = "answers")
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ans_label;
private int ans_value;
private int ans_weightage;
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "question_id", referencedColumnName = "id",nullable = false)
private Qa qa;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Qa getQa() {
return qa;
}
public void setQa(Qa qa) {
this.qa = qa;
}
}
My controller from where i am trying to insert data.
TableDataController.java
#Controller
public class TabletDataController {
#Autowired
QaRepository qaRepository;
#RequestMapping(value = "/saveApiData", method = RequestMethod.GET)
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
answersArrayList.add(answers);
qa.setAnswersList(answersArrayList);
qaRepository.save(qa);
}
}
my qaRepository extends JpaRepository. so whenever i call this api i get an error of com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'question_id' cannot be null
what am i doing wrong?
You have a bidirectional OneToMany relationship, so you need to manually maintain both sides of the relationship. Here you are only setting the Qa side with qa.setAnswersList(answersArrayList);
You need to set the other side of your relationship manually. add:
answers.setQa(qa);
before you save your list
code as follow
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
answers.setQa(qa);
answersArrayList.add(answers);
qa.setAnswersList(answersArrayList);
qaRepository.save(qa);
}
when you save.you should Cascade save.Your annotations configure the relationship of the associated tables but also to associate them when they are saved
I am facing problem while inserting. I want to save the details in result table without saving the foreign key parameters in parent table.
there are three pojo classes:
#Entity
#Table(name="course")
public class Course implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column( name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="course_id",nullable = false)
private String course_id;
#Column( name="course_name")
private String course_name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCourse_id() {
return course_id;
}
public void setCourse_id(String course_id) {
this.course_id = course_id;
}
public String getCourse_name() {
return course_name;
}
public void setCourse_name(String course_name) {
this.course_name = course_name;
}
**#OneToMany(fetch = FetchType.EAGER, mappedBy = "course")
private Set<Result> result = new HashSet<Result>(0);
public Set<Result> getResult() {
return this.result;
}
public void setResult(Set<Result> result) {
this.result = result;
}**
}
The second class is Student.java
#Entity
#Table(name ="student")
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
//Attribute----------------------------------
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//Attribute----------------------------------
#Column(name="student_id", nullable=false)
private long student_id;
public long getStudent_id() {
return student_id;
}
public void setStudent_id(long student_id) {
this.student_id = student_id;
}
//Attribute----------------------------------
#Column(name="student_name")
private String student_name;
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
//Attribute----------------------------------
#Column(name="student_contact_number")
private long student_contact_number;
public long getStudent_contact_number() {
return student_contact_number;
}
public void setStudent_contact_number(long student_contact_number) {
this.student_contact_number = student_contact_number;
}
//This is for the foreign key element in the Result.java POJO class
#OneToMany(fetch = FetchType.LAZY,cascade = {CascadeType.ALL}, mappedBy = "student")
private Set<Result> result = new HashSet<Result>(0);
public Set<Result> getResult() {
return this.result;
}
public void setResult(Set<Result> result) {
this.result = result;
}
}
Third is Result.java which contains the foreign keys
#Entity
#Table(name="result")
public class Result implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="semester")
private int semester;
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
#Column(name="marks")
private int marks;
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "student_id", nullable = false)
private Student student;
public Student getStudent() {
return this.student;
}
public void setStudent(Student student_id) {
this.student = student_id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "course_id", nullable = false)
private Course course;
public Course getCourse() {
return this.course;
}
public void setCourse(Course course) {
this.course = course;
}
}
Now the code I used to insert is like this:
Session session;
Transaction t;
Query query;
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//#SuppressWarnings("deprecation")
SessionFactory factory=cfg.buildSessionFactory();
session=factory.openSession();
t=session.beginTransaction();
Result result;
Course cs;
Student st;
for(int i=0; i<jsrm.get(0).size(); i++)
{
result=new Result();
cs= new Course();
st=new Student();
cs.setCourse_id(jsrm.get(0).get(i).getcourse_id());
st.setStudent_id(Integer.parseInt(jsrm.get(0).get(i).getstudent_id()));
result.setSemester(Integer.parseInt(jsrm.get(0).get(i).getsemester()));
result.setMarks(Integer.parseInt(jsrm.get(0).get(i).getmarks()));
result.setCourse(cs);
result.setStudent(st);
session.save(result);
}
t.commit();//transaction is committed
session.close();
The error is
org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before
current operation: Result.course -> Course
Is there a way to store the data without saving the course and student.
How to join newMap detals in custMap.
Map<String, Customer> custMap= new HashMap<String,Customer>();
Map<String, DoCustomer> newMap= new HashMap<String,DoCustomer>();
for (Map.Entry<String, DoCustomer> cust: newMap.entrySet()) {
custMap.put(cust.getKey(),cust.getValue());
}
public class DoCustomer {
private Long id;
private String custName;
private String description;
private String status;
private List<DoCustomerBranch> doCustomerBranch=new ArrayList<DoCustomerBranch>
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
getter/setters of doCustomerBranch
}
#Entity
#Table(name = "CUSTOMER")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String custName;
private String description;
private String createdBy;
private Date createdOn;
private String updatedBy;
private Date updatedOn;
private Set<CustomerBranch> customerBranch=new HashSet<CustomerBranch>
#Id
#GeneratedValue(generator = "CUSTOMER_SEQ")
#SequenceGenerator(name = "CUSTOMER_SEQ", sequenceName = "CUSTOMERN_SEQ", allocationSize = 1)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "CUST_NAME",nullable=false)
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "CREATED_BY", length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_ON")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name = "UPDATED_BY", length = 50)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_ON")
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "customer")
public Set<CustomerBranch> getCustomerBranch() {
return customerBranch;
}
public void setCustomerBranch(Set<CustomerBranch> customerBranch) {
this.customerBranch = customerBranch;
}
}
CustomerBranch
#Entity
#Table(name = "CUSTOMER_BRANCH")
public class CustomerBranch implements Serializable{
#Id
#GeneratedValue(generator = "CUSTOMER_BRANCH_SEQ")
#SequenceGenerator(name = "CUSTOMER_BRANCH_SEQ", sequenceName = "CUSTOMER_BRANCH_SEQ", allocationSize = 1)
#Column(name = "ID")
private Long id;
private String branchName;
private String branchAddress;
private Customer customer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "BRANCH_NAME",nullable=false)
public String getBranchName() {
return branchName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "MOBEE_CUSTOMER")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
The problem with your code is that you want to put a DoCustomer in a Customer container. It only works if DoCustomer is a subclass of Customer.
Edit 1: You could use BeanUtils to convert a DoCustomer into a Customer. Here is a good tutorial.
Do you mean:
custMap.putAll(newMap)
As everyone else has pointed out, we need to know what DoCustomer is to be able to help.
But, from what you have given us, I'd suggest casting each DoCustomer to a Customer or, more correctly, making a new Customer from the fields of each DoCustomer.
Something like:
custMap.put(cust.getKey(), new Customer(cust.getValue().getId(), cust.getValue().getCustName(), and so on..));
inside your for loop.
I can see the customer class defined you have provided doesn't have a constructor, so naturally you would have to add one to it