JPA many to many relation: unable to insert into generated table - jpa

I have 2 entities "Entree" and "Emplacement":
#Entity
#Table(name = "ENTREE")
public class Entree {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_ENTREE", updatable = false, nullable = false)
private long idEntree;
#Column(name = "NUM_DECLARATION", insertable=true, updatable=true, nullable=true)
private String numDeclaration;
#Column(name = "DATE_ENTREE", insertable=true, updatable=true, nullable=true)
private String dateEntree;
#Column(name = "TYPE_ENTREE", insertable=true, updatable=true, nullable=true)
private String typeEntree;
#Column(name = "NOM_ARTICLE", insertable=true, updatable=true, nullable=true)
private String nomArticle;
#Column(name = "TYPE_ARTICLE", insertable=true, updatable=true, nullable=true)
private String typeArticle;
#Column(name = "QUANTITE_ENTREE", insertable=true, updatable=true, nullable=true)
private int quantiteEntree;
#ManyToOne
#JoinColumn(name="idDossier", nullable=false)
private Dossier dossier;
#ManyToMany( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinTable(name = "entree_emplacement",
joinColumns = {
#JoinColumn(name = "id_entree", referencedColumnName = "id_entree",
nullable = false, updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "id_emplacement", referencedColumnName = "id_emplacement",
nullable = false, updatable = false)})
private Set<Emplacement> emplacement = new HashSet<>();
public Entree() {
super();
}
public Entree( String numDeclaration, String dateEntree, String typeEntree, String nomArticle, String typeArticle, int quantiteEntree, boolean isDone) {
super();
this.numDeclaration = numDeclaration;
this.dateEntree = dateEntree;
this.typeEntree = typeEntree;
this.nomArticle = nomArticle;
this.typeArticle = typeArticle;
this.quantiteEntree = quantiteEntree;
}
public long getIdEntree() {
return idEntree;
}
public void setIdEntree(long idEntree) {
this.idEntree = idEntree;
}
public String getNumDeclaration() {
return numDeclaration;
}
public void setNumDeclaration(String numDeclaration) {
this.numDeclaration = numDeclaration;
}
public String getDateEntree() {
return dateEntree;
}
public void setDateEntree(String dateEntree) {
this.dateEntree = dateEntree;
}
public String getTypeEntree() {
return typeEntree;
}
public void setTypeEntree(String typeEntree) {
this.typeEntree = typeEntree;
}
public String getNomArticle() {
return nomArticle;
}
public void setNomArticle(String nomArticle) {
this.nomArticle = nomArticle;
}
public String getTypeArticle() {
return typeArticle;
}
public void setTypeArticle(String typeArticle) {
this.typeArticle = typeArticle;
}
public int getQuantiteEntree() {
return quantiteEntree;
}
public void setQuantiteEntree(int quantiteEntree) {
this.quantiteEntree = quantiteEntree;
}
public Dossier getDossier() {
return dossier;
}
public void setDossier(Dossier dossier) {
this.dossier = dossier;
}
public Set<Emplacement> getEmplacements() {
return emplacement;
}
public void addEmplacement(Emplacement emplacement) {
this.emplacement.add(emplacement);
emplacement.getEntrees().add(this);
}
public void removeEmplacement(Emplacement emplacement) {
this.emplacement.remove(emplacement);
emplacement.getEntrees().remove(this);
}
}
And here the second entity:
#Entity
#Table(name = "EMPLACEMENT")
public class Emplacement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_EMPLACEMENT", updatable = false, nullable = false)
private long idEmplacement;
#Column(name = "NUM_EMPLACEMENT", insertable=true, updatable=true, nullable=false)
private String numEmplacement;
#ManyToMany(mappedBy = "emplacement", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private Set<Entree> entree = new HashSet<>();
public Emplacement() {
}
public Emplacement( String numEmplacement) {
this.numEmplacement = numEmplacement;
}
public long getIdEmplacement() {
return idEmplacement;
}
public void setIdEmplacement(long idEmplacement) {
this.idEmplacement = idEmplacement;
}
public String getNumEmplacement() {
return numEmplacement;
}
public void setNumEmplacement(String numEmplacement) {
this.numEmplacement = numEmplacement;
}
public Set<Entree> getEntrees() {
return entree;
}
}
Here is my inserting code:
#PostMapping("/ajouterEntree")
public ResponseEntity<String> addEntree(#Valid Entree entree, BindingResult result,ModelMap modelMap, #RequestParam(name = "numDossier") String numDossier, #RequestParam(name = "emplacement") String liste_emplacements) {
Emplacement e = new Emplacement(liste_emplacements);
entree.getEmplacements().add(e);
entreeService.saveEntree(entree);
return new ResponseEntity<String>("ok" + result, HttpStatus.OK);
}
I am able to insert datas into Entree and Emplacement tables, but the third generated table named entree-emplacement is empty.
So how can I insert datas into generated table in #ManyToMany relation?
Thanks

Ok it's resolved. Here is my code:
if(!liste_emplacements.equals(""))
{
List<String> list = new ArrayList<String>(Arrays.asList(liste_emplacements.split(",")));
Emplacement[] emp = new Emplacement[list.size()];
for (int i=0; i<list.size() ;i++)
{
emp[i] = new Emplacement(Long.parseLong(list.get(i)));
entree.getEmplacements().add(emp[i]);
emp[i].getEntrees().add(entree);
}
}
entreeService.saveEntree(entree);
return new ResponseEntity<String>("ok" + result, HttpStatus.OK);

Related

Spring Data JPA. Parent table data is not getting rolled back when exception occurred while inserting record in child table

I have 2 tables one to many relationship between Employee and Department table, Employee table are having column Id as PK, Name and Sal whereas Department table having column Dept_ID,Dept_Name & Dept_Loc and primary key is (Dept_ID,Dept_Name) i.e composite key and Dept_ID is foreign key ref from Employee table's Id column. The issue is when I save record in parent table i.e Employee it get saved but if in case I get exception while inserting record for child table i.e Department table,,data is not getting rolled back for EMployee table. Please help I m struggling and I am attaching my code.
public class GlEmployee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
#Column(name = "EMP_ID")
private long empId;
#Column(name = "EMP_CITY")
private String empCity;
#Column(name = "EMP_NAME")
private String empName;
#Column(name = "EMP_SALARY")
private BigDecimal empSalary;
// bi-directional many-to-one association to EmpDepartment
#OneToMany(mappedBy = "glEmployee",cascade = CascadeType.ALL)
private List<EmpDepartment> empDepartments = new ArrayList<>();
public GlEmployee() {
}
public long getEmpId() {
return this.empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public String getEmpCity() {
return this.empCity;
}
public void setEmpCity(String empCity) {
this.empCity = empCity;
}
public String getEmpName() {
return this.empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public BigDecimal getEmpSalary() {
return this.empSalary;
}
public void setEmpSalary(BigDecimal empSalary) {
this.empSalary = empSalary;
}
public List<EmpDepartment> getEmpDepartments() {
return this.empDepartments;
}
public void setEmpDepartments(List<EmpDepartment> empDepartments) {
this.empDepartments = empDepartments;
}
public EmpDepartment addEmpDepartment(EmpDepartment empDepartment) {
getEmpDepartments().add(empDepartment);
empDepartment.setGlEmployee(this);
return empDepartment;
}
public EmpDepartment removeEmpDepartment(EmpDepartment empDepartment) {
getEmpDepartments().remove(empDepartment);
empDepartment.setGlEmployee(null);
return empDepartment;
}
}
#Entity
#Table(name = "EMP_DEPARTMENT")
public class EmpDepartment implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private EmpDepartmentPK id;
#Column(name = "DEP_LOC")
private String depLoc;
public EmpDepartment(EmpDepartment id, String dep) {
}
// bi-directional many-to-one association to GlEmployee
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "DEP_ID", insertable = false, updatable = false)
private GlEmployee glEmployee;
public EmpDepartment() {
}
public EmpDepartmentPK getId() {
return this.id;
}
public void setId(GlEmployee glEmployee, String deptName) {
EmpDepartmentPK empDepartment = new
EmpDepartmentPK(glEmployee.getEmpId(), deptName);
this.id = empDepartment;
}
public String getDepLoc() {
return this.depLoc;
}
public void setDepLoc(String depLoc) {
this.depLoc = depLoc;
}
public GlEmployee getGlEmployee() {
return this.glEmployee;
}
public void setGlEmployee(GlEmployee glEmployee) {
this.glEmployee = glEmployee;
}
}
#Embeddable
public class EmpDepartmentPK implements Serializable {
// default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name = "DEP_ID")
private long depId;
#Column(name = "DEP_NAME")
private String depName;
public EmpDepartmentPK() {
}
public EmpDepartmentPK(long depId, String depName) {
super();
this.depId = depId;
this.depName = depName;
}
public long getDepId() {
return this.depId;
}
public void setDepId(long depId) {
this.depId = depId;
}
public String getDepName() {
return this.depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository employeeRepository;
#Transactional
public void createEmp() {
GlEmployee employee = new GlEmployee();
employee.setEmpCity("Pune");
employee.setEmpName("Ankush");
employee.setEmpSalary(new BigDecimal(200));
employeeRepository.save(employee);
EmpDepartment department = new EmpDepartment();
department.setId(employee, "ME");
department.setDepLoc(null);
department.setGlEmployee(employee);
employee.addEmpDepartment(department);
employeeRepository.save(employee);
}
}

JPA- insert a ID of parent to child table

when there is a many to one associate between two object in hibernate(JPA) and we want insert a ID of parent to child table without new record in parent table how do I implement it?
#ManyToOne(targetEntity = RoleEntity.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "FK_ROLE_ID",referencedColumnName = "ID")
private RoleEntity role;
I write this:
UserEntity userEntity=new UserEntity();
userEntity.setUserName(username);
userEntity.setPassword(password);
userEntity.setCreatedDate(new Date().toString());
RoleEntity roleEntity=new RoleEntity();
roleEntity.setTitle("user");
userEntity.setRole(roleEntity);
but the last three line also insert a new record in user table.
This completely of roleEntity:
package Entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Mohsen on 7/10/2018.
*/
#Entity(name = "role")
#Table(name = "ROLE")
public class RoleEntity implements Serializable {
#Id
#Column(name = "ID")
#SequenceGenerator(name = "SEQ_ROLE", sequenceName = "SEQ_ROLE", allocationSize = 1)
#GeneratedValue(generator = "SEQ_ROLE", strategy = GenerationType.SEQUENCE)
private int id;
#Basic
#Column(name = "Title")
private String title;
// #OneToMany(targetEntity = UserEntity.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
// #JoinColumn(name = "FK_ROLE_ID",referencedColumnName = "ID")
// private Set<UserEntity> user;
public RoleEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
This completely of userEntity:
package Entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Mohsen on 7/10/2018.
*/
#Entity(name = "user")
#Table(name = "USERR")
public class UserEntity implements Serializable {
#Id
#Column(name = "ID")
#SequenceGenerator(name = "SEQ_USER", allocationSize = 1, sequenceName = "SEQ_USER")
#GeneratedValue(generator = "SEQ_USER", strategy = GenerationType.SEQUENCE)
private int id;
#Basic
#Column(name = "UserName", columnDefinition = "VARCHAR2(20 CHAR)")
private String userName;
#Basic
#Column(name = "Password", columnDefinition = "VARCHAR2(255 CHAR)")
private String password;
#Basic
#Column(name = "CreatedDate")
private String createdDate;
#Basic
#Column(name = "EndedDate")
private String endedDate;
#OneToOne(targetEntity = PeopleEntity.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private PeopleEntity people;
#ManyToOne(targetEntity = RoleEntity.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "FK_ROLE_ID",referencedColumnName = "ID")
private RoleEntity role;
public RoleEntity getRole() {
return role;
}
public void setRole(RoleEntity role) {
this.role = role;
}
public UserEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getEndedDate() {
return endedDate;
}
public void setEndedDate(String endedDate) {
this.endedDate = endedDate;
}
public PeopleEntity getPeople() {
return people;
}
public void setPeople(PeopleEntity people) {
this.people = people;
}
}
I have found the solution
I set cascade = CascadeType.REMOVE in child object and it works

Merge 3 Tables into 1 SpringBoot + Postgres

I have an Application written in spring boot with 3 Tables T1, T2 and T3 on Postgres
t1 one2many mapping with t2 and t2 one2many with t3
How can I merge these tables into one? Do the model and repository still stay the same?
Model for T1
#Entity
#Table(name = "maintenance_type")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class MaintenanceType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Column(unique=true)
private String changeType;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
#OneToMany(mappedBy = "maintenanceType", cascade = CascadeType.ALL)
private Set<TierTwoQuestion> tierTwoQuestion;
public MaintenanceType() {
}
public MaintenanceType(Long id, String changeType) {
super();
this.id = id;
this.changeType = changeType;
}
public MaintenanceType(String changeType) {
super();
this.changeType = changeType;
}
public Set<TierTwoQuestion> getTierTwoQuestion() {
return tierTwoQuestion;
}
//
public void setTierTwoQuestion(Set<TierTwoQuestion> tierTwoQuestion) {
this.tierTwoQuestion = tierTwoQuestion;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChangeType() {
return changeType;
}
public void setChangeType(String changeType) {
this.changeType = changeType;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
Model for T2
#Entity
#Table(name = "tier_two_question")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class TierTwoQuestion implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Column(unique=true)
private String question;
#ManyToOne
#JoinColumn(name = "maintenanceId", nullable = false)
private MaintenanceType maintenanceType;
#OneToMany(mappedBy = "tierTwoQuestion", cascade = CascadeType.ALL)
private Set<TierThreeQuestion> tierThreeQuestion;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
public TierTwoQuestion() {
}
public TierTwoQuestion(Long id) {
super();
this.id = id;
this.question = question;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
// public MaintenanceType getMaintenanceType() {
// return maintenanceType;
// }
public void setMaintenanceType(MaintenanceType maintenanceType) {
this.maintenanceType = maintenanceType;
}
public Set<TierThreeQuestion> getTierThreeQuestion() {
return tierThreeQuestion;
}
public void setTierThreeQuestion(Set<TierThreeQuestion> tierThreeQuestion) {
this.tierThreeQuestion = tierThreeQuestion;
}
}
I tried adding recreating the model with all T1 T2 T3 in one table but not working as expected

jpa named query using foreign key is not working

MY Entity class
#Entity
#Table(catalog = "", schema = "MYIS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Answers.findAll", query = "SELECT a FROM Answers a"),
#NamedQuery(name = "Answers.findByAid", query = "SELECT a FROM Answers a WHERE a.aid = :aid"),
#NamedQuery(name ="Anaswers.findByqid", query ="SELECT a FROM Answers a WHERE a.answerQid.qid = :x"),
#NamedQuery(name = "Answers.findByAnsValue", query = "SELECT a FROM Answers a WHERE a.ansValue = :ansValue"),
#NamedQuery(name = "Answers.findByAnsDate", query = "SELECT a FROM Answers a WHERE a.ansDate = :ansDate")})
public class Answers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(nullable = false)
private Integer aid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 4000)
#Column(name = "ANS_VALUE", nullable = false, length = 4000)
private String ansValue;
#Basic(optional = false)
#NotNull
#Column(name = "ANS_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date ansDate;
#JoinColumn(name = "A_USERID", referencedColumnName = "USERID", nullable = false)
#ManyToOne(optional = false)
private Users aUserid;
#JoinColumn(name = "ANSWER_QID", referencedColumnName = "QID", nullable = false)
#ManyToOne(optional = false)
private Questions answerQid;
#JoinColumn(name = "A_GROUPID", referencedColumnName = "GID", nullable = false)
#ManyToOne(optional = false)
private Groups aGroupid;
public Answers() {
}
public Answers(Integer aid) {
this.aid = aid;
}
public Answers(Integer aid, String ansValue, Date ansDate) {
this.aid = aid;
this.ansValue = ansValue;
this.ansDate = ansDate;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAnsValue() {
return ansValue;
}
public void setAnsValue(String ansValue) {
this.ansValue = ansValue;
}
public Date getAnsDate() {
return ansDate;
}
public void setAnsDate(Date ansDate) {
this.ansDate = ansDate;
}
public Users getAUserid() {
return aUserid;
}
public void setAUserid(Users aUserid) {
this.aUserid = aUserid;
}
public Questions getAnswerQid() {
return answerQid;
}
public void setAnswerQid(Questions answerQid) {
this.answerQid = answerQid;
}
public Groups getAGroupid() {
return aGroupid;
}
public void setAGroupid(Groups aGroupid) {
this.aGroupid = aGroupid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aid != null ? aid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Answers)) {
return false;
}
Answers other = (Answers) object;
if ((this.aid == null && other.aid != null) || (this.aid != null && !this.aid.equals(other.aid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Answers[ aid=" + aid + " ]";
}
}
MY SESSION FACADE
import com.entity.Answers;
import com.entity.Groups;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author krishna teja
*/
#Stateless
public class AnswersFacade extends AbstractFacade<Answers> implements AnswersFacadeLocal {
#PersistenceContext(unitName = "My_communityPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public AnswersFacade() {
super(Answers.class);
}
public List<Answers> getdataByQid(Long qid){
Query query=em.createNamedQuery("Answers.findByqid");
query.setParameter(1, qid);
List<Answers> a =query.getResultList();
return a;
}
}
My managed bean
#PostConstruct
public void init(){
questions = questionsFacade.findAll();
ansList = answersFacade.getdataByQid(g);
}
I am getting following exception
at com.ejb.AnswersFacade.getdataByQid(AnswersFacade.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
I have created named query for the foreign key attribute answerQid and and created method in the sessionfacade and tried to access it in the managed bean the default methods work perfectly but my method for query is not working please help me
Looks like a simple typo. Named query is defined as Anaswers.findByqid, but used as Answers.findByqid.

Why JPA doesnt generate a join junction table in this case

I have two tables Students and Books , with a many to many relationship. The code of both are given below. Now when I try to run the code I get the error.
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'acme.book_stud' doesn't exist
Error Code: 1146
Call: INSERT INTO book_stud (idStudents, idBooks) VALUES (?, ?)
bind => [2 parameters bound]
It seems like JPA is trying to write to a juction table which does not exist (in this case it assumes a junction table books_students is already created so it doesnt create one.). It works if I create a books_students but I dont want to do that since its JPA responsibility to create it. Is there a way in which I could explicitly tell it to create one. ? (I am taking a wild guess here - but I guess when creating a persitance unit I specified "none" I think thats why it didnt create that table . Am I correct ? Anyways here are my Student and Books Classes
BOOKS CLASS
#Entity
#Table(name = "books")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Books.findAll", query = "SELECT b FROM Books b"),
#NamedQuery(name = "Books.findByIdBooks", query = "SELECT b FROM Books b WHERE b.idBooks = :idBooks"),
#NamedQuery(name = "Books.findByBookName", query = "SELECT b FROM Books b WHERE b.bookName = :bookName"),
#NamedQuery(name = "Books.findByBookType", query = "SELECT b FROM Books b WHERE b.bookType = :bookType")})
public class Books implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "idBooks")
private String idBooks;
#Size(max = 45)
#Column(name = "BookName")
private String bookName;
#Size(max = 45)
#Column(name = "BookType")
private String bookType;
/******************************************ADDED **********************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idStudents") },
inverseJoinColumns = { #JoinColumn(name = "idBooks") })
/**************************************ENDED*****************************/
public Books() {
}
public Books(String idBooks) {
this.idBooks = idBooks;
}
public String getIdBooks() {
return idBooks;
}
public void setIdBooks(String idBooks) {
this.idBooks = idBooks;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookType() {
return bookType;
}
public void setBookType(String bookType) {
this.bookType = bookType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idBooks != null ? idBooks.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Books)) {
return false;
}
Books other = (Books) object;
if ((this.idBooks == null && other.idBooks != null) || (this.idBooks != null && !this.idBooks.equals(other.idBooks))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.Books[ idBooks=" + idBooks + " ]";
}
}
STUDENT CLASS
#Entity
#Table(name = "students")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "StudentEnroll.findAll", query = "SELECT s FROM StudentEnroll s"),
#NamedQuery(name = "StudentEnroll.findByIdStudents", query = "SELECT s FROM StudentEnroll s WHERE s.idStudents = :idStudents"),
#NamedQuery(name = "StudentEnroll.findByName", query = "SELECT s FROM StudentEnroll s WHERE s.name = :name"),
#NamedQuery(name = "StudentEnroll.findByRoll", query = "SELECT s FROM StudentEnroll s WHERE s.roll = :roll"),
#NamedQuery(name = "StudentEnroll.findBySsn", query = "SELECT s FROM StudentEnroll s WHERE s.ssn = :ssn"),
#NamedQuery(name = "StudentEnroll.findByProgram", query = "SELECT s FROM StudentEnroll s WHERE s.program = :program")})
public class StudentEnroll implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 40)
#Column(name = "idStudents")
private String idStudents;
#Size(max = 45)
#Column(name = "Name")
private String name;
#Column(name = "Roll")
private Integer roll;
#Column(name = "SSN")
private Integer ssn;
#Size(max = 45)
#Column(name = "Program")
private String program;
#JoinColumn(name = "CustomerID", referencedColumnName = "UserID")
#ManyToOne
private Customer customerID;
//#OneToMany(mappedBy = "studentRoll")
#OneToMany(mappedBy = "studentRoll",cascade = CascadeType.REMOVE)//added REMOVE
private Collection<Subject> subjectCollection;
/**************************ADDED*****************************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idBooks") },
inverseJoinColumns = { #JoinColumn(name = "idStudents") })
/**********************************END**********************/
public StudentEnroll() {
}
public StudentEnroll(String idStudents) {
this.idStudents = idStudents;
}
public String getIdStudents() {
return idStudents;
}
public void setIdStudents(String idStudents) {
this.idStudents = idStudents;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRoll() {
return roll;
}
public void setRoll(Integer roll) {
this.roll = roll;
}
public Integer getSsn() {
return ssn;
}
public void setSsn(Integer ssn) {
this.ssn = ssn;
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public Customer getCustomerID() {
return customerID;
}
public void setCustomerID(Customer customerID) {
this.customerID = customerID;
}
#XmlTransient
public Collection<Subject> getSubjectCollection() {
return subjectCollection;
}
public void setSubjectCollection(Collection<Subject> subjectCollection) {
this.subjectCollection = subjectCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idStudents != null ? idStudents.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StudentEnroll)) {
return false;
}
StudentEnroll other = (StudentEnroll) object;
if ((this.idStudents == null && other.idStudents != null) || (this.idStudents != null && !this.idStudents.equals(other.idStudents))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.StudentEnroll[ idStudents=" + idStudents + " ]";
}
}