Started learning Spring Boot, JPA. Finding difficult on understanding JPA relationship concepts, I tried joining two tables but could not achieve the expected result can anyone help me to get the expected result.
Below Requirement
Have two tables as below
product_master table
product_catagory table
ProductMasterModel
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product_master")
public class ProductMasterModel {
#Id
#GeneratedValue
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_category_id")
private int productCategoryId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "product_category_id", referencedColumnName = "product_catogory_id",insertable = false, updatable = false)
private ProductCatagoryMasterModel productCatagoryMasterModel;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public ProductMasterModel() {
super();
}
public ProductMasterModel(String productName, int productCategoryId) {
super();
this.productName = productName;
this.productCategoryId = productCategoryId;
}
}
ProductCatagoryMasterModel
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="product_catagory")
public class ProductCatagoryMasterModel {
#Id
#GeneratedValue
#Column(name="product_catogory_id")
private int productCategoryId;
#Column(name="product_type")
private String productType;
#OneToOne(mappedBy = "productCatagoryMasterModel")
private ProductMasterModel productMasterModel;
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public ProductCatagoryMasterModel() {
super();
}
public ProductCatagoryMasterModel(String productType) {
super();
this.productType = productType;
}
}
ProductMasterRepository
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lollipop.model.ProductMasterModel;
#Repository
public interface ProductMasterRepository extends CrudRepository<ProductMasterModel, Integer> {
#Query (value = "select * from product_master pm, product_catagory pc where pc.product_catogory_id = pm.product_category_id", nativeQuery = true)
public List $ProductMasterModel$ getProductCategoryDetail();
}
ProductService
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lollipop.model.ProductMasterModel;
import com.lollipop.repository.ProductMasterRepository;
#Service
#Transactional
public class ProductService {
#Autowired
private ProductMasterRepository productMasterRepository;
public void getProductCat() {
List $ProductMasterModel$ productMasterModel = productMasterRepository.getProductCategoryDetail();
System.out.println("productMasterModel value "+productMasterModel.toString());
}
}
When calling getProductCat() method getting result as
productMasterModel value [ProductMasterModel [productId=1011,
productName=Pencil, productCategoryId=10], ProductMasterModel
[productId=1012, productName= Mobile, productCategoryId=11]]
Since ProductMasterModel is not having productType variable it is not displaying productType
I need below result by joining two tables, please help me to acheive this
[[productName=Pencil,productType=Stationary],[productName=
Mobile,productType=Electronics]]
Yes, One to One Relationship should work.
Changes should be made in your POJO.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product_master")
public class ProductMasterModel {
#Id
#GeneratedValue
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_category_id")
private int productCategoryId;
#OneToOne(mappedBy= product_master, fetch = FetchType.LAZY)
public ProductCatagoryMasterModel productCatagory;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public ProductMasterModel() {
}
public ProductMasterModel(String productName, int productCategoryId) {
super();
this.productName = productName;
this.productCategoryId = productCategoryId;
}
}
Next Address your Category Model
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="product_catagory")
public class ProductCatagoryMasterModel {
#Id
#GeneratedValue
#Column(name="product_catogory_id")
private int productCategoryId;
#Column(name="product_type")
private String productType;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "product_master", referencedColumnName = "product_id")
private ProductMasterModel productMaster;
public int getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(int productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public ProductCatagoryMasterModel() {
super();
}
public ProductCatagoryMasterModel(String productType) {
super();
this.productType = productType;
}
}
We also need DAO
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.lollipop.model.ProductMasterModel;
#Repository
public interface ProductMasterRepository extends CrudRepository<ProductMasterModel, Integer> {
}
Product Service
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lollipop.model.ProductMasterModel;
import com.lollipop.repository.ProductMasterRepository;
#Service
#Transactional
public class ProductService {
#Autowired
private ProductMasterRepository productMasterRepository;
public List<ProductMasterModel > getAllProducts() {
return productMasterRepository.findAll();
}
public Optional<ProductMasterModel > getProductById(int productId) {
if (!productMasterRepository.existsById(productId)) {
throw new ResourceNotFoundException("Product with id " + productId+ " not found");
}
return productMasterRepository.findById(productId);
}
}
}
You need to establish ont-to-one relationship between those two tables.
Take a look at this:
Example
Related
I've done a few changes on my code, because now I want to have a soft deletion instead of a normal one.
I would only need a few JPA annotations for this purpose.
I think I got the right idea, but now I can't even run it because it give the following error:
"""Type mismatch: cannot convert from String to Class<?>"""
My CloudProduct.java ( the one with the error ) :
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_products_info SET deleted = true WHERE id=?")
#FilterDef(name = "deletedProductFilter", parameters = #ParamDef(name = "isDeleted", type = "boolean"))
#Filter(name = "deletedProductFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
#Id
private String productId;
private String productName;
private String productPrice;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private boolean deleted = Boolean.FALSE;
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(String productId, String productName, String productPrice, Date createdAt, boolean deleted) {
this.productId = productId;
this.productName = productName;
this.productPrice = productPrice;
this.createdAt = createdAt;
this.deleted = deleted;
}
public CloudProduct() {
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
The error is implicit on :
#FilterDef(name = "deletedProductFilter", parameters = #ParamDef(name = "isDeleted", type = "boolean"))
Specifically on the "type = "boolean" ".
He is my CloudProductController.java
package com.proj.my.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.model.CloudProduct;
import com.proj.my.service.CloudProductService;
#RestController
#RequestMapping("/cloudproduct")
public class CloudProductController
{
CloudProductService cloudProductService;
public CloudProductController(CloudProductService cloudProductService)
{
this.cloudProductService = cloudProductService;
}
#GetMapping("{productId}")
public CloudProduct getCloudProductDetails(#PathVariable("productId") String productId){
return cloudProductService.getCloudProduct(productId);
}
#PostMapping
public String createCloudProductDetails(#RequestBody CloudProduct cloudProduct){
cloudProductService.createCloudProduct(cloudProduct);
return "Success";
}
#PutMapping
public String updateCloudProductDetails(#RequestBody CloudProduct cloudProduct){
cloudProductService.updateCloudProduct(cloudProduct);
return "Updated !";
}
#DeleteMapping("/{productId}")
public void removeOne(#PathVariable("productId") String productId) {
cloudProductService.remove(productId);
}
#GetMapping
public Iterable<CloudProduct> findAll(#RequestParam(value = "isDeleted", required = false, defaultValue = "false") boolean isDeleted) {
return cloudProductService.findAll(isDeleted);
}
}
My CloudProductService.java :
package com.proj.my.service;
import com.proj.my.model.CloudProduct;
public interface CloudProductService {
public String createCloudProduct(CloudProduct cloudProduct);
public String updateCloudProduct(CloudProduct cloudProduct);
public CloudProduct getCloudProduct(String cloudProductId);
public Iterable<CloudProduct> findAll(boolean isDeleted);
public void remove(String cloudProductId);
}
My CloudProductServiceimpl.java :
package com.proj.my.service.impl;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import jakarta.persistence.EntityManager;
#Service
public class CloudProductServiceImpl implements CloudProductService
{
CloudProductRepository cloudProductRepository;
#Autowired
private EntityManager entityManager;
public CloudProductServiceImpl(CloudProductRepository cloudProductRepository) {
this.cloudProductRepository = cloudProductRepository;
}
#Override
public String createCloudProduct(CloudProduct cloudProduct){
cloudProductRepository.save(cloudProduct);
return "Success";
}
#Override
public String updateCloudProduct(CloudProduct cloudProduct){
cloudProductRepository.save(cloudProduct);
return "Success";
}
#Override
public CloudProduct getCloudProduct(String cloudProductId){
return cloudProductRepository.findById(cloudProductId).get();
}
public void remove(String cloudProductId){
cloudProductRepository.deleteById(cloudProductId);
}
public Iterable<CloudProduct> findAll(boolean isDeleted){
Session session = entityManager.unwrap(Session.class);
Filter filter = session.enableFilter("deletedProductFilter");
filter.setParameter("isDeleted", isDeleted);
Iterable<CloudProduct> products = cloudProductRepository.findAll();
session.disableFilter("deletedProductFilter");
return products;
}
}
I hope you can help me with this one, THANKS !!!
I have two entities- User and Notes. One User can have multiple Notes. I am trying to implement a soft delete for both the tables. For the User table, it is working fine but for Notes table, calling deleteById is not changing the value of the deleted column to true. I tried returning findById(notesId) and it's returning right row but delete is not working.
package com.we.springmvcboot.Model;
import java.util.ArrayList;
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.Table;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import antlr.collections.List;
#Entity
#Table(name="User")
#SQLDelete(sql = "Update User set deleted = 'true' where UserID=?")
#Where(clause = "deleted = 'false'")//FALSE
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long UserID;
#Column(name="emailid")
private String emailID;
#Column(name="deleted")
private String deleted="false";
#OneToMany(mappedBy="user", fetch = FetchType.EAGER,cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Notes> usernotes;
public User() {}
public User(String emailID) {
super();
this.emailID = emailID;
}
public String getDeleted() {
return deleted;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public long getUserID() {
return UserID;
}
public void setUserID(long userID) {
UserID = userID;
}
public String getemailID() {
return emailID;
}
public void setemailID(String emailID) {
this.emailID = emailID;
}
public Set<Notes> getUsernotes() {
return usernotes;
}
public void setUsernotes(Set<Notes> usernotes) {
this.usernotes = usernotes;
}
}
package com.we.springmvcboot.Model;
import java.sql.Date;
import java.util.ArrayList;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="Notes")
#SQLDelete(sql = "Update Notes set deleted = 'true' where NotesID = ?")
#Where(clause = "deleted = 'false'")
public class Notes {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long NotesID;
#Column(name="title")
private String title;
#Column(name="message")
private String message;
#Column(name="date")
private String date;
#Column(name="deleted")
private String deleted="false";
#Column(name="label")
private int label=1;
#ManyToOne()
#JoinColumn(name = "UserID", nullable = false)
private User user;
public Notes() {}
public Notes(String title, String message, String date, User user, int label) {
super();
this.title = title;
this.message = message;
this.date = date;
this.user = user;
this.label=label;
}
public Notes(long notesID, String title, String message, String date, int label) {
super();
NotesID = notesID;
this.title = title;
this.message = message;
this.date = date;
this.label=label;
}
public String getDeleted() {
return deleted;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public int getLabel() {
return label;
}
public void setLabel(int label) {
this.label = label;
}
public long getNotesID() {
return NotesID;
}
public void setNotesID(long notesID) {
NotesID = notesID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public void setUser(User user) {
this.user = user;
}
}
package com.we.springmvcboot.Service;
import com.we.springmvcboot.Model.*;
import com.we.springmvcboot.exception.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import com.we.springmvcboot.Repository.NotesRepository;
import com.we.springmvcboot.Repository.UserRepository;
#Service
public class TodoService {
#Autowired
UserRepository userrepo;
#Autowired
NotesRepository notesrepo;
public Object deleteNote(Map<String, Object> input) throws InvalidInputException, NoteNotFoundException {
long userID;
try {
userID = ((Number) input.get("userID")).longValue();
} catch (Exception e) {
throw new InvalidInputException("Missing UserID");
}
HashMap<String, Object> map = new HashMap<>();
long notesID = ((Number) input.get("notesID")).longValue();
System.out.println(notesID);
if (!notesrepo.findById(notesID).isPresent())
throw new NoteNotFoundException("Invalid Notes ID");
**notesrepo.deleteById(notesID);**
map.put("status", 200);
map.put("message", "Request Successful");
map.put("data", null);
return map;
}
public Object deleteUser(Map<String, Object> input) throws NoteNotFoundException {
HashMap<String, Object> map = new HashMap<>();
long userID;
userID = ((Number) input.get("userID")).longValue();
if (!userrepo.findById(userID).isPresent())
throw new NoteNotFoundException("Invalid User ID");
userrepo.deleteById(userID);
map.put("status", 200);
map.put("message", "Request Successful");
map.put("data", null);
return map;
}
}
Try with #NamedQuery instead of #SQLDelete
or
try with
repo.deleteInBatch(list)
I'm doing simple JPA entity relationship many to ine in spring using annotation while i am getting error that "com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null";
Below is my pojos
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTDB")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And mapped class as given below.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Marks {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long sid;
private int subject1;
private int subject2;
private int subject3;
#ManyToOne(optional=false)
#JoinColumn(name="id",referencedColumnName="id")
private Student s;
public Student getS() {
return s;
}
public void setS(Student s) {
this.s = s;
}
public long getSid() {
return sid;
}
public void setSid(long sid) {
this.sid = sid;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
}
So what can be possible solution for this?
package com.example;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTDB")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable=false,updatable=false)
private long id;
private String name;
}
Please check the following:
The table named STUDENTDB is defined in the database such that the primary key column id has AUTO_INCREMENT attribute.
Without the above attribute #GeneratedValue(strategy = GenerationType.AUTO) is not going to work in the present scenario.
I read many posts with my same problem, but none seems to fix my issue.
If I add #Cascade(CascadeType.ALL) to the Parent Object (menu) I get the error above.
If I add #Cascade(CascadeType.ALL) to the Child Object (VoceMenu) I get this other error:
ERROR 2015-11-22 15:43:53,689 [http-bio-8080-exec-8] org.hibernate.util.JDBCExceptionReporter - Column 'title' cannot be null
ERROR 2015-11-22 15:43:53,689 [http-bio-8080-exec-8] com.springgestioneerrori.DAO.MenuDAO - could not insert: [com.springgestioneerrori.model.Menu]
ERROR 2015-11-22 15:43:53,691 [http-bio-8080-exec-8] org.hibernate.util.JDBCExceptionReporter - Column 'title' cannot be null
ERROR 2015-11-22 15:43:53,692 [http-bio-8080-exec-8] org.springframework.transaction.interceptor.TransactionInterceptor - Application exception overridden by commit exception
I can't understand if the problem depends on the way I bound the 2 entities or depends on something else.
This is my Menu entity
package com.springgestioneerrori.model;
import java.io.Serializable;
import java.util.List;
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 javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Component
#Entity
#Table(name="menu")
public class Menu implements Serializable{
private static final long serialVersionUID = -7161291305179518214L;
public Menu() {
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id", nullable=false, updatable=false)
private int id;
#NotBlank
#NotNull
#NotEmpty
#Size(min=3,max=50)
#Pattern(regexp = "^[A-Za-z0-9 ]*$")
#Column(name="titolo")
private String titolo;
#NotBlank
#NotNull
#NotEmpty
#Size(min=3,max=255)
#Pattern(regexp = "^[A-Za-z0-9 ]*$")
#Column(name="title")
private String title;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "menu")
#Cascade(CascadeType.ALL) <--------------------
private List<VoceMenu> voceMenuList;
#OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
private Set<MenuAutorizzazioni> menuAutorizzazioni;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<VoceMenu> getVoceMenuList() {
return voceMenuList;
}
public void setVoceMenuList(List<VoceMenu> voceMenuList) {
this.voceMenuList = voceMenuList;
}
public void setMenuAutorizzazioni(Set<MenuAutorizzazioni> menuAutorizzazioni) {
this.menuAutorizzazioni = menuAutorizzazioni;
}
public Set<MenuAutorizzazioni> getMenuAutorizzazioni() {
return menuAutorizzazioni;
}
//transient///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Transient
#NotBlank
#NotNull
#NotEmpty
#Size(min=3,max=255)
#Pattern(regexp = "^[A-Za-z0-9 ]*$")
private String currentLanguageTitle;
#Transient
#NotBlank
#NotNull
#NotEmpty
#Size(min=3,max=255)
#Pattern(regexp = "^[A-Za-z0-9 ]*$")
private String currentLanguageTitolo;
public String getCurrentLanguageTitle() {
return currentLanguageTitle;
}
public void setCurrentLanguageTitle(String currentLanguageTitle) {
this.currentLanguageTitle = currentLanguageTitle;
}
public String getCurrentLanguageTitolo() {
return currentLanguageTitolo;
}
public void setCurrentLanguageTitolo(String currentLanguageTitolo) {
this.currentLanguageTitolo = currentLanguageTitolo;
}
}
This is my VoceMenu Entity
package com.springgestioneerrori.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Component
#Entity
#Table(name="voci_menu")
public class VoceMenu implements Serializable{
private static final long serialVersionUID = 141763842624541637L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id", unique = true, nullable = false)
private Integer id;
#NotBlank
#NotEmpty
#NotNull
#Column(name="descrizione", nullable=false)
private String descrizione;
#NotBlank
#NotEmpty
#NotNull
#Column(name="title")
private String title;
#NotBlank
#NotEmpty
#NotNull
#Column(name="url")
private String url;
/*#NotBlank
#NotEmpty
#NotNull(message="Call is invalid.")*/
#Column(name="ordine")
private int ordine;
#ManyToOne(targetEntity=Menu.class)
#JoinColumn(name="menu", referencedColumnName="id")
#Cascade(CascadeType.ALL) <--------------------
private Menu menu;
#OneToOne(targetEntity=Autorizzazione.class)
#JoinColumn(name="autorizzazione", referencedColumnName="id_autorizzazione")
private Autorizzazione autorizzazione;
public VoceMenu() {
}
public String getDescrizione() {
return descrizione;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getOrdine() {
return ordine;
}
public void setOrdine(int ordine) {
this.ordine = ordine;
}
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
public Autorizzazione getAutorizzazione() {
return autorizzazione;
}
public void setAutorizzazione(Autorizzazione autorizzazione) {
this.autorizzazione = autorizzazione;
}
//transient ////////////////////////////////////////////////////////////////////////////////////////////////////////
#Transient
private String currentLanguageDescrizione;
#Transient
private String currentLanguageTitle;
public String getCurrentLanguageDescrizione() {
return currentLanguageDescrizione;
}
public void setCurrentLanguageDescrizione(String currentLanguageDescrizione) {
this.currentLanguageDescrizione = currentLanguageDescrizione;
}
public String getCurrentLanguageTitle() {
return currentLanguageTitle;
}
public void setCurrentLanguageTitle(String currentLanguageTitle) {
this.currentLanguageTitle = currentLanguageTitle;
}
}
Tahnk you for you help
The org.hibernate.TransientObjectException: object references an unsaved transient error happens as the menu is referring to the child(voce_menu) record that is not created yet in the database.
You have to modify the SovuMenu Entity relationship to be only:
#ManyToOne
#JoinColumn(name="voci_menu_id")
private Menu menu;
and modify the menu to be:
#OneToMany(cascade = CascadeType.ALL)
#joinColumn(name="menu_id")
private List<VoceMenu> voceMenuList;
Make sure that you import all annotations from the Javax.persistence
I am trying to use Hibernate annotations for writing a model class for my database tables.
I have two tables each having a primary key User and ChartDetails.
package com.winnow.springservice.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//User Entity class mapped with hibernate
#Entity
#Table(name="User")
#SuppressWarnings(value = { "all" })
public class User implements Serializable
{
#Id
#Column(name="user_id")
public String user_Id;
#Column(name="user_name")
public String userName;
public String password;
#Column(name="last_login")
public String last_Login;
#Column(name="role_id")
public int role_Id;
public int status;
public String getUser_Id() {
return user_Id;
}
public void setUser_Id(String user_Id) {
this.user_Id = user_Id;
}
public String getLast_Login() {
return last_Login;
}
public void setLast_Login(String last_Login) {
this.last_Login = last_Login;
}
public int getRole_Id() {
return role_Id;
}
public void setRole_Id(int role_Id) {
this.role_Id = role_Id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
System.out.println("username"+userName);
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password)
{
System.out.println("password "+password);
this.password = password;
}
}
Chart details
package com.winnow.springservice.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Chart_Details")
#SuppressWarnings(value = { "all" })
public class ChartDetails implements Serializable
{
#Id
#Column(name="chart_id")
public int chartId;
#Id
#Column(name="chart_type_id")
public int chartTypeId;
#Column(name="chart_name")
public String chartName;
#Column(name="x_axis")
public String x_axis;
#Column(name="y_axis")
public String y_axis;
#Column(name="z_axis")
public int z_axis;
#Column(name="chart_filter_id")
public int chartFilterId;
#Column(name="is_data_table")
public boolean isDataTable;
#Column(name="dataset_id")
public int datasetId;
#Column(name="user_id")
public int userId;
#Column(name="project_id")
public int projectId;
}
And I have one more table – ChartsStarredBy – which has userId and chart_id as foreign keys from the above two tables.
But I am unable to find how I can reference these constraints in the ChartsStarredBy table.
package com.winnow.springservice.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="Chart_Starred_By")
#SuppressWarnings(value = { "all" })
public class ChartsStarredBy implements Serializable
{
#Id
public int id;
#Temporal(TemporalType.DATE)
public Date starred_date;
#ManyToOne
#JoinColumn(name = "FK_chart_id4")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "FK_user_id4")
private User user;
public Date getStarred_date()
{
return starred_date;
}
public void setStarred_date(Date starred_date)
{
this.starred_date = starred_date;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public ChartDetails getChart_details() {
return chart_details;
}
public void setChart_details(ChartDetails chart_details) {
this.chart_details = chart_details;
}
}
Please help me achieve this? Thanks in advance.
First of all you should create an integer id for User table which is primary key. Here in your code you creating it as String type.
You are doing wrong here
#ManyToOne
#JoinColumn(name = "FK_chart_id4")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "FK_user_id4")
private User user;
You have IDs in User table & ChartDetails table as
#Id
#Column(name="user_id")
public String user_Id;
AND
#Id
#Column(name="chart_id")
public int chartId;
So when you refer to id of another class you should give name of that id in #JoinColumn. Just like this
#ManyToOne
#JoinColumn(name = "chartId")
private ChartDetails chart_details;
#ManyToOne
#JoinColumn(name = "user_Id")
private User user;
You can also use #ForeignKey(name = "user_Id") annotation from Hibernate like this
#ManyToOne
#ForeignKey(name = "user_Id")
private User user;
Example tutorial :- Hibernate One To Many Annotation Tutorial