Hibernate, Oracle, Sequence and One To Many Problem - oracle

I am having an issue with doing a one line save on a one to many object. That foreign key does not get populated in the child objects. Aren't they suppose to automatically from Hibernate? The BadgeID never gets inserted into the BadgeLevel.BadgeID.
Badge.java
#Basic
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="BADGE_SEQUENCE")
#SequenceGenerator(name="BADGE_SEQUENCE", sequenceName = "BADGE_SEQUENCE")
#Column(name = "ID", nullable=false, unique=true)
public Long getId() {
return id;
}
#OneToMany(mappedBy="badge", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#Fetch(value=FetchMode.SELECT)
public List<BadgeLevel> getBadgeLevels() {
return this.badgelevels;
}
BadgeLevel.java
#Basic
#Id
#NotNull
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="BADGELEVEL_SEQUENCE")
#SequenceGenerator(name="BADGELEVEL_SEQUENCE", sequenceName = "BADGELEVEL_SEQUENCE")
#Column(name = "ID", nullable=false, unique=true)
public Long getId() {
return id;
}
#ManyToOne()
#JoinColumn(name = "BADGEID")
public Badge getBadge() {
return this.badge;
}
/**
* set badge
*/
public void setBadge(Badge badge) {
this.badge = badge;
}

Before calling save on Badge, try the following
......
for(BadgeLevel badgeLevel : badge.getBadegeLevels()
{
badgeLevel.setBadge(badge);
}
repo.save(badge);

Related

Not null reference a null or transient value

So i am trying to achieve oneToone relationship between two entity classes.First class is a customer entity class which have two foreign keys buyer_id and seller_id.So what i want initially is that when the user fills the initial credentials in the website the buyer_id and seller_id field should be null and after the user fills the required information for the buyer or seller i will update the row of the corresponding customer and add the buyer_id and seller_id.But when i try to create a customer entry i am getting this error that buyer_id cannot be null?
This is my customer table
#Entity
#Table(name = "Customer")
public class Customer {
public enum Status{
ACTIVE,
IN_ACTIVE
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#OneToOne(fetch = FetchType.LAZY,optional = true,cascade=CascadeType.ALL)
#JoinColumn(name = "seller_id",nullable = true,referencedColumnName = "id",updatable = true)
#Basic(optional = true)
private Seller seller_id;
#OneToOne(fetch=FetchType.LAZY,optional = true,cascade=CascadeType.ALL)
#JoinColumn(name = "buyer_id", nullable = true,referencedColumnName="id",updatable = true)
#Basic(optional = true)
private Buyer buyer_id;
#OneToOne(fetch=FetchType.LAZY,optional = false,cascade = CascadeType.ALL)
#JoinColumn(name = "user_id",nullable = false,unique = true,referencedColumnName = "id")
private User user_id;
public Buyer getBuyer_id() {
return buyer_id;
}
public void setBuyer_id(Buyer buyer_id) {
this.buyer_id = buyer_id;
}
#Column(name = "Name")
String name;
#Enumerated(EnumType.STRING)
#Column(name = "Status")
private Status status;
public Customer(String name,Status status){
this.name=name;
this.status = status;
}
public Customer(){
}
public Seller getSeller_id() {
return seller_id;
}
public void setSeller_id(Seller seller_id) {
this.seller_id = seller_id;
}
public User getUser_id() {
return user_id;
}
public void setUser_id(User user_id) {
this.user_id = user_id;
}
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;
}
public User getUser() {
return user_id;
}
public void setUser(User user) {
this.user_id = user;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
This is my buyer table
#Entity
#Table(name="Buyer")
public class Buyer {
#Id
#Column(name = "id") private long id;
#Column(name = "GSTIN")
String GSTIN;
#Column(name = "Legal_Document")
#Lob
private byte[] legalDocument;
#OneToOne(fetch=FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "buyer_id")
#JsonIgnore
private Customer customer;
#Column(name = "Authorized_person_name")
String authorized_person_name;
#Column(name = "Authorized_person_email")
String authorized_person_email;
}
This is my seller table
#Entity
#Table(name = "Seller")
public class Seller {
#Id
#Nullable
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "GSTIN")
private String GSTIN;
#Column(name = "GST_Document")
#Lob
private byte[] gst_document;
#OneToOne(fetch=FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "seller_id")
#JsonIgnore
private Customer customer;
// #OneToOne(fetch = FetchType.LAZY,
// cascade = CascadeType.ALL,
// mappedBy = "sellerId")
// #JsonIgnore
// private PickupAddress pickupAddress;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
public String getGSTIN() {
return GSTIN;
}
public void setGSTIN(String GSTIN) {
this.GSTIN = GSTIN;
}
public byte[] getGst_document() {
return gst_document;
}
public void setGst_document(byte[] gst_document) {
this.gst_document = gst_document;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

how to assign id mapped entity

*#Entity
#Table(name = "model_data")
public class ModelData {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "diagram_id")
private DiagramEntity diagram;
//Getter Setter
}
#Entity
#Table(name = "diagram")
public class DiagramEntity {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#JsonProperty(value = "class")
private String aciklama;
#OneToMany(mappedBy = "diagram")
private Set<ModelData> modelData;
//Getter Setter
}*
DiagramEntity has manytoone relation with modeldata entity. Then I post
*{
"modelData": [
{
"diagram": null,
}
],
}*
via postman, DiagramEntity id is automatically updated but I cannot assign id to modelData entity and cannot save to database. what should I do?
I find solution for my problem. I streamed every object and mapped to my entities in the my controller class.
public DiagramEntityDto saveOrUpdate(#RequestBody DiagramEntityDto dto) {
try {
dto.getModelData().stream().map(a ->
this.modelDataService.saveOrUpdate(a)).collect(Collectors.toSet());
return this.diagramService.saveOrUpdate(dto);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}

JPA repository null pointer exception for many to one mapping with composite primary key

Post class
one to many mapping
Composite primary key using id
I am getting null pointer exception when I make get request for getting comments
#Entity
#Table(name = "posts")
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(max = 100)
#Column(unique = true)
private String title;
#NotNull
#Size(max = 250)
private String description;
#NotNull
#Lob
private String content;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "posted_at")
private Date postedAt = new Date();
#NotNull
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();
#OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "post")
private Set<Comment> comments = new HashSet<>();
public Post() {
}
public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}
//getters and setters
}
Comment class
many to one mapping with composite primary keys using #Idclass
#Entity
#IdClass(CommentId.class)
#Table(name = "comments")
public class Comment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Lob
private String text;
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "post_id", nullable = false)
private Post post;
public Comment() {
}
public Comment(String text) {
this.text = text;
}
//getters and setters
}
Id class
CommentId
public class CommentId implements Serializable {
private static final long serialVersionUID = 1L;
private Post post;
private Long id;
public CommentId(Post post, Long id) {
super();
this.post = post;
this.id = id;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result+ ((post == null) ? 0 : post.hashCode());
result = prime * result ;
return result;
}
public boolean equals(Object object) {
if (object instanceof CommentId) {
CommentId pk = (CommentId)object;
return id.equals(pk.id) && post == pk.post;
} else {
return false;
}
}
//getters and setters
}
repositories
PostRepository
CommentRepository
#Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
#Repository
public interface CommentRepository extends JpaRepository<Comment, Long>
{
}
Controller class get request and I am using mysql database
#RestController
#RequestMapping("/demo")
public class Controller {
#Autowired
PostRepository ps;
CommentRepository cs;
#GetMapping("/post")
public List<Post> getAll(){
return ps.findAll();
}
#GetMapping("/comment")
public List<Comment> getAllcom(){
return cs.findAll();
}
}

JsonIgnore dynamically If it is nested?

I have hibernate models like following:
Ticket Model:
#Entity
#Table(name = "ticket")
public class TicketModel {
private BigInteger id;
private UserModel user;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name = "seqTicket", sequenceName = "ticket_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqTicket")
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
public UserModel getUser() {
return user;
}
public void setUser(UserModel user) {
this.user = user;
}
}
User Model:
#Entity
#Table(name = "user")
public class UserModel {
private BigInteger id;
private String name;
private CompanyModel company;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name = "seqUser", sequenceName = "user_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqUser")
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "company_id", referencedColumnName = "id")
public CompanyModel getUser() {
return company;
}
public void setUser(CompanyModel company) {
this.company = company;
}
}
Company Model:
#Entity
#Table(name = "company")
public class UserModel {
private BigInteger id;
private String name;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name = "seqCompany", sequenceName = "company_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqCompany")
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now, what i want to do is json ignoring user's company in my rest controller if I am returning ticket object. But if I am returning User object I dont want to ignore company relation.
For example:
in ticket controller's return it should be a json like :
{
"id":1,
"user":{
"id":3,
"name":"something"
}
}
but in user controller's return it should be like:
{
"id":3,
"name":"something",
"company":{
"id":5,
"name":"something else"
}
}
So shortly, I want to ignore relations if it is in second dimension.
Is that possible?

Child primary key not updated by hibernate

I'm using hibernate and spring data to save entities in my database. I'm attaching child elements to the parent and vice versa. Everything is saved correctly in the database, as well the child instances.
After calling save method again, the child elements get saved twice. I found out, that the reason is, that the framework does not update the childrens Id after persisting. It is always zero. Parent ID got updated correctly.
Any idea how to solve that?
Receipt.java:
#Entity
#javax.persistence.Table(name = "receipts")
public class Receipt {
private int id;
/*
* [...]
*/
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumn(name = "receipt_id",referencedColumnName = "id")
private List<ReceiptItem> getReceiptItemList() {
return receiptItemList;
}
private void setReceiptItemList(List<ReceiptItem> receiptItemList) {
this.receiptItemList = receiptItemList;
}
/*
* [...]
*/
}
ReceiptItem.java:
#Entity
#Table(name = "receipt_items")
public class ReceiptItem {
private int id;
/*
* [...]
*/
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "receipt_id")
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
}
Saving:
item = new ReceiptItem();
item.setReceipt(receipt);
receipt.getReceiptItemList().add(item);
// this should create the new ReceiptItem instance
receiptService.save(receipt);
System.out.println("ItemId: "+item.getId()); //but the id is still 0
// calling save method twice results in a second entry in the database
// instead of updating the previously inserted one
receiptService.save(receipt);
System.out.println("ItemId: "+item.getId());
Output:
ItemId: 0
ItemId: 0

Resources