I have 3 tables in my database: Professors, Disciplines and Courses.
From Professors and Disciplines to Courses it is many to one relationship.
I have tried to put foreign keys, but it does not work.
Course class:
package com.licenta.ascourses.model;
import java.io.Serializable;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="Courses")
#AssociationOverrides({
#AssociationOverride(name = "pk.discipline",
joinColumns = #JoinColumn(name = "IDDISCIPLINE")),
#AssociationOverride(name = "pk.professor",
joinColumns = #JoinColumn(name = "IDPROFESSOR")) })
public class Course implements Serializable {
private CourseId idCourse=new CourseId();
private int year;
private int semester;
public Course()
{
}
public Course(CourseId idCourse, int idDiscipline, int idProfessor,int year, int semester) {
super();
this.idCourse = idCourse;
this.year = year;
this.semester = semester;
}
#EmbeddedId
public CourseId getIdCourse() {
return idCourse;
}
public void setIdCourse(CourseId idCourse) {
this.idCourse = idCourse;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
}
CourseId class for composite primary key:
package com.licenta.ascourses.model;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Embeddable
public class CourseId implements Serializable{
#ManyToOne
#JoinColumn(name="IDDISCIPLINE")
private int idDiscipline;
#ManyToOne
#JoinColumn(name="IDPROFESSOR")
private int idProfessor;
private String courseNo;
public int getIdDiscipline() {
return idDiscipline;
}
public void setIdDiscipline(int idDiscipline) {
this.idDiscipline = idDiscipline;
}
public int getIdProfessor() {
return idProfessor;
}
public void setIdProfessor(int idProfessor) {
this.idProfessor = idProfessor;
}
public String getCourseNo() {
return courseNo;
}
public void setCourseNo(String courseNo) {
this.courseNo = courseNo;
}
public boolean equals(Object o) {
return true;
}
public int hashCode() {
return 1;
}
}
Discipline class:
package com.licenta.ascourses.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Disciplines")
public class Discipline implements Serializable {
private int idDiscipline;
#Id
private String name;
private String description;
private int an;
private int semestru;
public Discipline()
{
}
public Discipline(int idDiscipline, String name, String description, int an, int semestru) {
super();
this.idDiscipline = idDiscipline;
this.name = name;
this.description = description;
this.an = an;
this.semestru = semestru;
}
public Discipline(int idDiscipline, String name, String description, int an, int semestru, Set<Course> courses) {
super();
this.idDiscipline = idDiscipline;
this.name = name;
this.description = description;
this.an = an;
this.semestru = semestru;
}
public int getIdDiscipline() {
return idDiscipline;
}
public void setIdDiscipline(int idDiscipline) {
this.idDiscipline = idDiscipline;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAn() {
return an;
}
public void setAn(int an) {
this.an = an;
}
public int getSemestru() {
return semestru;
}
public void setSemestru(int semestru) {
this.semestru = semestru;
}
}
And this is how my Course table is made by Hibernate:
create table Courses (
courseNo varchar2(255 char) not null,
idDiscipline number(10,0) not null,
idProfessor number(10,0) not null,
semester number(10,0) not null,
year number(10,0) not null,
primary key (courseNo, idDiscipline, idProfessor)
)
So, the foreign keys does not appear. Please help me
Try to change this:
#ManyToOne
#JoinColumn(name="IDDISCIPLINE")
private int idDiscipline;
#ManyToOne
#JoinColumn(name="IDPROFESSOR")
private int idProfessor;
private String courseNo;
to this:
#ManyToOne
#JoinColumn(name="idDiscipline")
private Discipline discipline;
#ManyToOne
#JoinColumn(name="idProfessor")
private Professor professor;
private String courseNo;
Related
I have three entity classes Country, State, and City. Now I am trying to display the cities that come under a particular state and states that come under a particular country. but I am facing an error like
org.springframework.dao.DataAccessResourceFailureException:
Could not create JPA EntityManager;
nested exception is org.hibernate.AnnotationException:
#OneToOne or #ManyToOne on com.region.model.State.cities reference
an unknown entity: java.util.List.
Please help me out in one-to-many and many-to-one mapping for the three tables.
package com.region.model;
import java.util.List;
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.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "country")
public class Country {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer country_id;
#Column
private String country_name;
// #Column
// private String status="active";
#Transient
private String statusCode;
#Transient
private String statusmessage;
#OneToMany(targetEntity=State.class, mappedBy="country",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JsonBackReference
private List<State> states;
public Country() {
}
public Integer getCountry_id() {
return country_id;
}
public void setCountry_id(Integer country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusmessage() {
return statusmessage;
}
public void setStatusmessage(String statusmessage) {
this.statusmessage = statusmessage;
}
public List<State> getStates() {
return states;
}
public void setStates(List<State> states) {
this.states = states;
}
}
package com.region.model;
import java.util.List;
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.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "state")
public class State {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer sk_state_id;
#Column
private String state_name;
#Column
private String country_id;
// #Column
// private String status="active";
#Transient
private String statusCode;
#Transient String statusMessage;
#ManyToOne()
#JoinColumn(name="country_id", referencedColumnName = "country_id", insertable = false, updatable = false)
#JsonManagedReference
#OneToMany(targetEntity=City.class, mappedBy="state",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private List<City>cities;
private Country country;
public State() {
}
public Integer getSk_state_id() {
return sk_state_id;
}
public void setSk_state_id(Integer sk_state_id) {
this.sk_state_id = sk_state_id;
}
public String getState_name() {
return state_name;
}
public void setState_name(String state_name) {
this.state_name = state_name;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public List<City> getCities() {
return cities;
}
public void setCities(List<City> cities) {
this.cities = cities;
}
}
package com.region.model;
import java.lang.annotation.Repeatable;
import java.util.List;
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.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "city")
public class City {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer sk_city_id;
#Column
private String city_name;
#Column
private String state_id;
#Column
private String country_id;
#Transient
private String statusCode;
#Transient
String statusMessage;
#ManyToOne(targetEntity = State.class)
#JoinColumn(name="state_id", referencedColumnName ="sk_state_id", insertable = false, updatable = false)
private State state;
private Country country;
//private List<State>states;
public City() {
}
public Integer getSk_city_id() {
return sk_city_id;
}
public void setSk_city_id(Integer sk_city_id) {
this.sk_city_id = sk_city_id;
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getState_id() {
return state_id;
}
public void setState_id(String state_id) {
this.state_id = state_id;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
#Override
public String toString() {
return "City [sk_city_id=" + sk_city_id + ", city_name=" + city_name + ", state_id=" + state_id
+ ", country_id=" + country_id + ", statusCode=" + statusCode + ", statusMessage=" + statusMessage
+ "]";
}
// public List<State> getStates() {
// return states;
// }
// public void setStates(List<State> states) {
// this.states = states;
// }
}
mappedBy is only used once in a relationship between 2 classes, for the class that you want to define the relationship for both. So in the class Countries you probably don't need mappedBy at all, in the class Cities, you should put mappedBy="state", and in the class State it would make sense to put mappedBy="country"
I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
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="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
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="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
import com.lue.billingsystem.enums.Status;
import com.lue.billingsystem.enums.Types;
#Entity
#Table(name="product_tab")
public class Product implements Serializable{
private static final long serialVersionUID = 8919320309645697466L;
#Id
#Column(name="prod_id",updatable=false)
#GenericGenerator(name="product_tab_genetator",strategy="increment")
#GeneratedValue(generator="product_tab_genetator")
private Long id;
private String name;
#Enumerated(EnumType.STRING)
#Column(name = "type")
private Types type;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private Status status;
#Column(name = "description", length = 200)
private String description;
#OneToMany(mappedBy="product")
private List<Charge> charges;
#Column(name = "create_date", columnDefinition = "DATETIME")
private Date createDate;
#Column(name = "update_date", columnDefinition = "DATETIME")
private Date updateDate;
//#Version
private Integer version;
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 Types getType() {
return type;
}
public void setType(Types type) {
this.type = type;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Charge> getCharges() {
return charges;
}
public void setCharges(List<Charge> charges) {
this.charges = charges;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.lue.billingsystem.enums.utils.StatusDeserializer;
import com.lue.billingsystem.exception.BillingException;
#JsonDeserialize(using = StatusDeserializer.class)
public enum Status {
ACTIVE("Active"), INACTIVE("Inactive");
private final String text;
Status(final String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
public String getText() {
return this.text;
}
public static Status fromText(String text) {
for (Status r : Status.values()) {
if (r.getText().equals(text)) {
System.out.println(r);
return r;
}
}
throw new BillingException("Your Status not valied: "+text +" ", HttpStatus.BAD_REQUEST, 400);
}
}
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.lue.billingsystem.enums.Status;
public class StatusDeserializer extends JsonDeserializer<Status> {
#Override
public Status deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node == null) {
return null;
}
String text = node.textValue(); // gives "A" from the request
if (text == null) {
return null;
}
//System.out.println(Status.fromText(text) + "---------------");
return Status.fromText(text);
}
}
How to enum mapping with jpa Spring boot why not save enum value in DB in DB saving enum key when i saving product in databse not save status like Active it always save ACTIVE
You just need to pay attention to the enum values when the table is being created.
What are the enum values in the table e.g. in status column, are the values defined as 'Active', 'Inactive' or 'ACTIVE', 'INACTIVE'. That's what will determine the value saved.
If the enum values are defined as 'ACTIVE', 'INACTIVE', if you insert 'active' as the value for status, it will change to 'ACTIVE' inside the database because it inserts based on the pre defined enum values.
I devised Category,SubCategory and Product entities for JSF project and I had an issue about mapping between SubCategory and Product with ManytoMany relation. Here are Category,SubCategory and Products below. How can I solve out this mapping excepiton. Thks.
#Entity
#Table(name="CATEGORY",schema="DEMO")
public class Category implements Serializable{
#Id
#SequenceGenerator(name="catseq",sequenceName="seqCatSEQ",allocationSize=1)
#GeneratedValue(generator="catseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="NAME")
private String name;
#Column(name="CAT_DESC")
private String catDesc;
#OneToMany(cascade = { CascadeType.PERSIST },mappedBy="category")
private Set<SubCategory> subcategories = new HashSet();
public Category() {
super();
// TODO Auto-generated constructor stub
}
public Category(String name, String catDesc) {
super();
this.name = name;
this.catDesc = catDesc;
}
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 getCatDesc() {
return catDesc;
}
public void setCatDesc(String catDesc) {
this.catDesc = catDesc;
}
public Set<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(Set<SubCategory> subcategories) {
this.subcategories = subcategories;
}
}
SubCategory:
package entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
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.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="SUBCATEGORY",schema="DEMO")
public class SubCategory implements Serializable{
#Id
#SequenceGenerator(name="subcatseq",sequenceName="seqSubCatSEQ",allocationSize=1)
#GeneratedValue(generator="subcatseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="SUBNAME")
private String SubName;
#Column(name="SUBNAME_DESC")
private String SubNameDes;
#ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
#JoinColumn(name = "CAT_ID")
private Category category;
#ManyToMany(cascade=CascadeType.PERSIST,mappedBy="subcategories")
Set<Product> products = new HashSet<Product>();
public SubCategory() {
super();
// TODO Auto-generated constructor stub
}
public SubCategory(String subName, String subNameDes) {
super();
SubName = subName;
SubNameDes = subNameDes;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSubName() {
return SubName;
}
public void setSubName(String subName) {
SubName = subName;
}
public String getSubNameDes() {
return SubNameDes;
}
public void setSubNameDes(String subNameDes) {
SubNameDes = subNameDes;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Product:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="PRODUCTS",schema="DEMO")
public class Product implements Serializable{
#Id
#SequenceGenerator(name="proseq",sequenceName="proSEQ",allocationSize=1)
#GeneratedValue(generator="proseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="NAME")
private String productName;
#Column(name="QUANTITY")
private Integer quantity;
#Column(name="PRICE")
private Double price;
#Column(name="PRODUCT_DESC")
private String productDes;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="PRODUCT_SUBCATEGORY",
joinColumns={#JoinColumn(name="PRODUCT_ID")},
inverseJoinColumns={#JoinColumn(name="SUBCATEGORY_ID")}
)
Set<SubCategory> subcategories = new HashSet<SubCategory>();
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(String productName, Integer quantity, Double price, String productDes,
Set<SubCategory> subcategories) {
super();
this.productName = productName;
this.quantity = quantity;
this.price = price;
this.productDes = productDes;
this.subcategories = subcategories;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getProductDes() {
return productDes;
}
public void setProductDes(String productDes) {
this.productDes = productDes;
}
public Set<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(Set<SubCategory> subcategories) {
this.subcategories = subcategories;
}
}
First mappedby is defined as It refers to the field who owns the relationship, By other meaning mapped by refers to the table class which has the foreign key
So we have two mappedBy that are suspiecous lets take them one by one :
1-
#OneToMany(cascade = { CascadeType.PERSIST },mappedBy="category")
private Set<SubCategory> subcategories = new HashSet();
That means that subcategory table and class owns the relationship field so subcategory table is the one who have the foreign key and from SubCategory class the foreign key name is CAT_ID so this one is OK.
2-
#ManyToMany(cascade=CascadeType.PERSIST,mappedBy="subcategories")
Set<Product> products = new HashSet<Product>();
Ok this one shows that there is a field called subcategories in Product class this one owns the relationship BAM this is not true since this is ManyToMany the owner of the relationship should be a third table exists on database and have to be logically understood by hibernate
So this is the issue mappedBy refers to the the field which is not the owner of the relationship and since the owner is some anonymous entity
this have to be like this :
#ManyToMany(cascade=CascadeType.PERSIST)
#JoinTable(name="PRODUCT_SUBCATEGORY",
joinColumns={#JoinColumn(name="SUBCATEGORY_ID")},
inverseJoinColumns={#JoinColumn(name="PRODUCT_ID")}
Set<Product> products = new HashSet<Product>();
Note Your PRODUCT_SUBCATEGORY table should only have two primary keys and should be primary so that hibernate understands that this is ManyToMany relationship
I devised category and subcategory form in jsf. When I select any category, subcategory related with this category are shown in dropdown. I have a issue how to write hql file. Category and Subcategory is depended on onetomany and vice versa.
Here is the subcategory dao below.
public List getAllSubCategoriesSelectItemName(String name) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getSessionFactory().openSession();
try {
List<Category> liste = session.createQuery("Select S.SubName from SubCategory S left join SC.category scc where scc.name='"+name+"'").list();
return liste;
} catch (Exception e) {
e.printStackTrace();
}finally {
session.close();
}
return null;
}
#Entity
#Table(name="CATEGORY",schema="DEMO")
public class Category implements Serializable{
#Id
#SequenceGenerator(name="catseq",sequenceName="seqCatSEQ",allocationSize=1)
#GeneratedValue(generator="catseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="NAME")
private String name;
#Column(name="CAT_DESC")
private String catDesc;
#OneToMany(cascade = { CascadeType.PERSIST },mappedBy="category")
private Set<SubCategory> subcategories = new HashSet();
public Category() {
super();
// TODO Auto-generated constructor stub
}
public Category(String name, String catDesc) {
super();
this.name = name;
this.catDesc = catDesc;
}
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 getCatDesc() {
return catDesc;
}
public void setCatDesc(String catDesc) {
this.catDesc = catDesc;
}
public Set<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(Set<SubCategory> subcategories) {
this.subcategories = subcategories;
}
}
package entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
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.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="SUBCATEGORY",schema="DEMO")
public class SubCategory implements Serializable{
#Id
#SequenceGenerator(name="subcatseq",sequenceName="seqSubCatSEQ",allocationSize=1)
#GeneratedValue(generator="subcatseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="SUBNAME")
private String SubName;
#Column(name="SUBNAME_DESC")
private String SubNameDes;
#ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
#JoinColumn(name = "CAT_ID")
private Category category;
#ManyToMany(cascade=CascadeType.PERSIST,mappedBy="subcategories")
Set<Product> products = new HashSet<Product>();
public SubCategory() {
super();
// TODO Auto-generated constructor stub
}
public SubCategory(String subName, String subNameDes) {
super();
SubName = subName;
SubNameDes = subNameDes;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSubName() {
return SubName;
}
public void setSubName(String subName) {
SubName = subName;
}
public String getSubNameDes() {
return SubNameDes;
}
public void setSubNameDes(String subNameDes) {
SubNameDes = subNameDes;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Select S.SubName from SubCategory S left join SC.category
There is nothing aliased with SC in that query.The only existing alias is S. So SC.category is incorrect.