I'm trying to persist a relationship #ManyToMany. I created an association class using #IdClass for association, but doesn't work using persist, works only using merge.
I need add others registers but using merge doesn't work because the register is always updated.
I want my table in the database looks like this
id_aluno | id_graduacao | grau | date
1 1 FIRST 2014-08-02
1 1 SECOND 2014-08-02
1 1 THIRD 2014-08-02
My entities
#Entity
#Table(name="aluno")
public class Aluno implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
//historico de graduacao
#OneToMany(mappedBy = "aluno")
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Aluno(){}
/** adiciona lista de HistoricoDeGraduacao para aluno */
public void addListaHistoricoGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
///gets e sets
#Entity
#Table(name="graduacao")
public class Graduacao implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graus_graduacao", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="graus")
private List<String> graus;
#OneToMany(mappedBy = "graduacao")
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Graduacao() {
}
/** adiciona historicodegraduacao a graduacao */
public void addHistoricoDeGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
//gets e sets
public class HistoricoDeGraduacaoId implements Serializable {
private static final long serialVersionUID = 1L;
private Aluno aluno;
private Graduacao graduacao;
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Graduacao getGraduacao() {
return graduacao;
}
public void setGraduacao(Graduacao graduacao) {
this.graduacao = graduacao;
}
#Entity
#IdClass(HistoricoDeGraduacaoId.class)
public class HistoricoDeGraduacao implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "id_aluno")
private Aluno aluno;
#Id
#ManyToOne
#JoinColumn(name="id_graduacao")
private Graduacao graduacao;
private String grau;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
public HistoricoDeGraduacao() {
}
//gets e sets
//persisting
public void insert(){
//doesn't work using persist, works only with merge but record is always updated and not added
em.getTransaction().begin();
Aluno a = new Aluno();
a.setId(1); //aluno have Id
Graduacao g = new Graduacao();
g.setId(1); //graduacao have Id
HistoricoDeGraduacao hdg1 = new HistoricoDeGraduacao();
hdg1.setAluno(a);
hdg1.setGraduacao(g);
hdg1.setDataGraduou(new Date());
hdg1.setGrau("FIRST");
a.addHistoricoDeGraduacao(hdg1);
g.addHistoricoDeGraduacao(hdg1);
em.persist(hdg1);
em.getTransaction().commit();
HistoricoDeGraduacao hdg2 = new HistoricoDeGraduacao();
hdg2.setAluno(a);
hdg2.setGraduacao(g);
hdg2.setDataGraduou(new Date());
hdg2.setGrau("SECOND");
a.addHistoricoDeGraduacao(hdg2);
g.addHistoricoDeGraduacao(hdg2);
em.persist(hdg2);
em.getTransaction().commit();
HistoricoDeGraduacao hdg3 = new HistoricoDeGraduacao();
hdg3.setAluno(a);
hdg3.setGraduacao(g);
hdg3.setDataGraduou(new Date());
hdg3.setGrau("THIRD");
a.addHistoricoDeGraduacao(hdg3);
g.addHistoricoDeGraduacao(hdg3);
em.persist(hdg3);
em.getTransaction().commit();
em.close();
}
Any idea ?
now works
here how I did
#Entity
#Table(name="aluno")
public class Aluno implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
//historico de graduacao
#OneToMany(mappedBy = "aluno", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Aluno() {
}
public void addListaHistoricoGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
public void setListaHistoricoGraduacao(List<HistoricoDeGraduacao> listaHistoricoGraduacao) {
this.listaHistoricoGraduacao = listaHistoricoGraduacao;
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Aluno other = (Aluno) obj;
return true;
}
}
#Entity
#Table(name="graduacao")
public class Graduacao implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graus_graduacao", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="graus")
private List<String> graus;
#OneToMany(mappedBy = "graduacao", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Graduacao() {
}
public Graduacao(Integer id, String graduacao, List<String> graus) {
this.id = id;
this.graduacao = graduacao;
this.graus = graus;
}
/** adiciona historicodegraduacao a graduacao */
public void addHistoricoDeGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGraduacao() {
return graduacao;
}
public void setGraduacao(String graduacao) {
this.graduacao = graduacao;
}
public List<String> getGraus() {
return graus;
}
public void setGraus(List<String> graus) {
this.graus = graus;
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
public void setListaHistoricoGraduacao(List<HistoricoDeGraduacao> listaHistoricoGraduacao) {
this.listaHistoricoGraduacao = listaHistoricoGraduacao;
}
public String toString(){
return graduacao;
}
}
#Embeddable
public class HistoricoDeGraduacaoId implements Serializable {
private static final long serialVersionUID = 1L;
#JoinColumn(name="EMP_ID")
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of generated methods, choose Tools | Templates.
}
#Override
public int hashCode() {
return super.hashCode(); //To change body of generated methods, choose Tools | Templates.
}
}
#Entity
public class HistoricoDeGraduacao implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
HistoricoDeGraduacaoId pk;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_aluno")
private Aluno aluno;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="id_graduacao")
private Graduacao graduacao;
private String grau;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
public HistoricoDeGraduacao() {
}
public void begin(){
//instancia pk
pk = new HistoricoDeGraduacaoId();
//aqui insiro o id
pk.setId(new HistoricoDeGraduacaoDAO().getIndex());
}
public HistoricoDeGraduacaoId getPk() {
return pk;
}
public void setPk(HistoricoDeGraduacaoId pk) {
this.pk = pk;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Graduacao getGraduacao() {
return graduacao;
}
public void setGraduacao(Graduacao graduacao) {
this.graduacao = graduacao;
}
public String getGrau() {
return grau;
}
public void setGrau(String grau) {
this.grau = grau;
}
public Date getDataGraduou() {
return dataGraduou;
}
public void setDataGraduou(Date dataGraduou) {
this.dataGraduou = dataGraduou;
}
#Override
public int hashCode() {
int hash = 3;
hash = 59 * hash + Objects.hashCode(this.aluno);
hash = 59 * hash + Objects.hashCode(this.graduacao);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final HistoricoDeGraduacao other = (HistoricoDeGraduacao) obj;
if (!Objects.equals(this.aluno, other.aluno)) {
return false;
}
if (!Objects.equals(this.graduacao, other.graduacao)) {
return false;
}
return true;
}
}
//aqui meu jframe com seus componentes, pegando valores montando tudo para ser salvo
historico.setDataGraduou(jdp_dataGraduou.getDate());
historico.setGrau(jl_graus.getSelectedValue().toString());
//pega graduacao do jcombobox
Graduacao g = (Graduacao)cbx_graduacao.getSelectedItem();
historico.setGraduacao(g);
//bean aluno
historico.setAluno(bean);
//add a listas
bean.addListaHistoricoGraduacao(historico);
g.addHistoricoDeGraduacao(historico);
//inicia instancia de pk e insere o proximo id
historico.begin();
//salva tudo
new HistoricoDeGraduacaoDAO().update(historico);
//aqui meu DAO
public class HistoricoDeGraduacaoDAO {
private EntityManager em;
public HistoricoDeGraduacaoDAO(){
em = Persistencia.getEntityManager();
}
/** pega o ultimo valor da tabela HistoricoDeGraduacao e adiciona + 1 para o proximo indice */
public Integer getIndex(){
int count = 0;
Query query = em.createQuery("SELECT MAX(hdg.pk.id) FROM HistoricoDeGraduacao hdg");
if(query.getSingleResult() == null){
++count;
}else{
count = (int)query.getSingleResult() + 1;
}
return count;
}
/** executa update */
public void update(HistoricoDeGraduacao historico){
try{
em.getTransaction().begin();
em.merge(historico);
em.getTransaction().commit();
}catch(PersistenceException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}finally{
em.close();
}
}
}
Related
I've created ManyToMany tables with extra column that's named reqserviceguest_details, then I've tested with filling on my jsp page form to insert the data. When the all data inserted, everything is fine except my servicelaundry_id. It's null and I have no idea why it happened.
ReqServiceGuestDetails.class
#Entity
#Table(name = "reqserviceguest_details")
public class ReqServiceGuestDetails {
#Id
#Column(name = "reqserviceguest_details_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
#ManyToOne
#JoinColumn(name = "reqserviceguest_id")
private ReqServiceGuest reqServiceGuest;
#ManyToOne
#JoinColumn(name = "servicelaundry_id")
private ServiceLaundry serviceLaundry;
private int amount;
public ReqServiceGuestDetails() {
}
public ReqServiceGuestDetails(ReqServiceGuest reqServiceGuest, ServiceLaundry serviceLaundry, int amount) {
this.reqServiceGuest = reqServiceGuest;
this.serviceLaundry = serviceLaundry;
this.amount = amount;
}
public ReqServiceGuest getReqServiceGuest() {
return reqServiceGuest;
}
public void setReqServiceGuest(ReqServiceGuest reqServiceGuest) {
this.reqServiceGuest = reqServiceGuest;
}
public ServiceLaundry getServiceLaundry() {
return serviceLaundry;
}
public void setServiceLaundry(ServiceLaundry serviceLaundry) {
this.serviceLaundry = serviceLaundry;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
ReqServiceGuest.class
#Entity
#Table(name = "reqserviceguest")
public class ReqServiceGuest {
#Id
#Column(name = "reqserviceguest_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
int id;
#Column(nullable = false, unique = true)
private String reqServiceGuestId;
private Date reqDate;
private Date pickDate;
private String type;
private String serviceStatus;
private String guestName;
private String guestTelNo;
#OneToMany(mappedBy = "reqServiceGuest", cascade = CascadeType.ALL)
private Set<ReqServiceGuestDetails> reqServiceGuestDetails = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReqServiceGuestId() {
return reqServiceGuestId;
}
public void setReqServiceGuestId(String reqServiceGuestId) {
this.reqServiceGuestId = reqServiceGuestId;
}
public Date getReqDate() {
return reqDate;
}
public void setReqDate(Date reqDate) {
this.reqDate = reqDate;
}
public Date getPickDate() {
return pickDate;
}
public void setPickDate(Date pickDate) {
this.pickDate = pickDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(String serviceStatus) {
this.serviceStatus = serviceStatus;
}
public String getGuestName() {
return guestName;
}
public void setGuestName(String guestName) {
this.guestName = guestName;
}
public String getGuestTelNo() {
return guestTelNo;
}
public void setGuestTelNo(String guestTelNo) {
this.guestTelNo = guestTelNo;
}
public Set<ReqServiceGuestDetails> getReqServiceGuestDetails() {
return reqServiceGuestDetails;
}
public void setReqServiceGuestDetails(Set<ReqServiceGuestDetails> reqServiceGuestDetails) {
this.reqServiceGuestDetails = reqServiceGuestDetails;
}
}
ServiceLaundry.class
#Entity
#Table(name = "servicelaundry")
public class ServiceLaundry {
#Id
#Column(name = "servicelaundry_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
int id;
#Column(nullable = false, unique = true)
private String serviceId;
private String serviceName;
private int price;
#OneToMany(mappedBy = "serviceLaundry")
private Set<ReqServiceGuestDetails> reqServiceGuestDetails = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And this is form processor in a controller
#RequestMapping(path = "/savereqserviceguest", method = RequestMethod.GET)
public String processAddReqServiceGuestForm (ReqServiceGuest reqServiceGuest, #RequestParam Map<String, String> allParams) {
int latestId = reqServiceGuestService.getLatestReqServiceGuestId();
reqServiceGuest.setReqServiceGuestId(generateReqServiceGuestId(latestId));
reqServiceGuest.setServiceStatus("NP");
/*
for (Map.Entry<String, String> entry : allParams.entrySet()) {
if (entry.getKey().contains("service")) {
String getServiceId = String.valueOf(entry.getKey().charAt(7));
reqServiceGuest.getReqServiceGuestServiceLaundry().add();
}
}
reqServiceGuest.setReqServiceGuestServiceLaundry(serviceGuestDetails);
*/
ServiceLaundry service1 = serviceLaundryService.getServiceLaundry(1);
ServiceLaundry service2 = serviceLaundryService.getServiceLaundry(2);
ReqServiceGuestDetails reqServiceGuestDetails1 = new ReqServiceGuestDetails(reqServiceGuest, service1, 55);
ReqServiceGuestDetails reqServiceGuestDetails2 = new ReqServiceGuestDetails(reqServiceGuest, service2, 35);
reqServiceGuest.getReqServiceGuestDetails().add(reqServiceGuestDetails1);
reqServiceGuest.getReqServiceGuestDetails().add(reqServiceGuestDetails2);
Calendar cReqDate = Calendar.getInstance();
if (reqServiceGuest.getType().equals("Ordinary")) {
Date reqDate = cReqDate.getTime();
reqServiceGuest.setReqDate(reqDate);
Calendar cPickDate = Calendar.getInstance();
cPickDate.add(Calendar.DATE, 5);
Date pickDate = cPickDate.getTime();
reqServiceGuest.setPickDate(pickDate);
} else {
Date reqDate = cReqDate.getTime();
reqServiceGuest.setReqDate(reqDate);
Calendar cPickDate = Calendar.getInstance();
cPickDate.add(Calendar.DATE, 2);
Date pickDate = cPickDate.getTime();
reqServiceGuest.setPickDate(pickDate);
}
reqServiceGuestService.saveReqServiceGuest(reqServiceGuest);
return "redirect:/home";
}
And the final result is
Result
I am facing problem while inserting. I want to save the details in result table without saving the foreign key parameters in parent table.
there are three pojo classes:
#Entity
#Table(name="course")
public class Course implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column( name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="course_id",nullable = false)
private String course_id;
#Column( name="course_name")
private String course_name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCourse_id() {
return course_id;
}
public void setCourse_id(String course_id) {
this.course_id = course_id;
}
public String getCourse_name() {
return course_name;
}
public void setCourse_name(String course_name) {
this.course_name = course_name;
}
**#OneToMany(fetch = FetchType.EAGER, mappedBy = "course")
private Set<Result> result = new HashSet<Result>(0);
public Set<Result> getResult() {
return this.result;
}
public void setResult(Set<Result> result) {
this.result = result;
}**
}
The second class is Student.java
#Entity
#Table(name ="student")
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
//Attribute----------------------------------
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//Attribute----------------------------------
#Column(name="student_id", nullable=false)
private long student_id;
public long getStudent_id() {
return student_id;
}
public void setStudent_id(long student_id) {
this.student_id = student_id;
}
//Attribute----------------------------------
#Column(name="student_name")
private String student_name;
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
//Attribute----------------------------------
#Column(name="student_contact_number")
private long student_contact_number;
public long getStudent_contact_number() {
return student_contact_number;
}
public void setStudent_contact_number(long student_contact_number) {
this.student_contact_number = student_contact_number;
}
//This is for the foreign key element in the Result.java POJO class
#OneToMany(fetch = FetchType.LAZY,cascade = {CascadeType.ALL}, mappedBy = "student")
private Set<Result> result = new HashSet<Result>(0);
public Set<Result> getResult() {
return this.result;
}
public void setResult(Set<Result> result) {
this.result = result;
}
}
Third is Result.java which contains the foreign keys
#Entity
#Table(name="result")
public class Result implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="semester")
private int semester;
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
#Column(name="marks")
private int marks;
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "student_id", nullable = false)
private Student student;
public Student getStudent() {
return this.student;
}
public void setStudent(Student student_id) {
this.student = student_id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "course_id", nullable = false)
private Course course;
public Course getCourse() {
return this.course;
}
public void setCourse(Course course) {
this.course = course;
}
}
Now the code I used to insert is like this:
Session session;
Transaction t;
Query query;
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//#SuppressWarnings("deprecation")
SessionFactory factory=cfg.buildSessionFactory();
session=factory.openSession();
t=session.beginTransaction();
Result result;
Course cs;
Student st;
for(int i=0; i<jsrm.get(0).size(); i++)
{
result=new Result();
cs= new Course();
st=new Student();
cs.setCourse_id(jsrm.get(0).get(i).getcourse_id());
st.setStudent_id(Integer.parseInt(jsrm.get(0).get(i).getstudent_id()));
result.setSemester(Integer.parseInt(jsrm.get(0).get(i).getsemester()));
result.setMarks(Integer.parseInt(jsrm.get(0).get(i).getmarks()));
result.setCourse(cs);
result.setStudent(st);
session.save(result);
}
t.commit();//transaction is committed
session.close();
The error is
org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before
current operation: Result.course -> Course
Is there a way to store the data without saving the course and student.
my code is :
List<Session> futureSessions = this.getFutureSession(group.getSessions());
for (Session session: futureSessions) {
Boolean exists = false;
for (SessionDTO sessionDTO: groupDTO.getSessions()) {
if (session.getId() == sessionDTO.getId()) {
exists = true;
}
}
if(false == exists) {
// sessionService.delete(session);
group.getSessions().remove(session);
} else {
exists = false;
}
} Group groupUpdated = groupService.save(group);
This part of code is for remove object (session) into my group object. I use java spring for dilog between angular and java.
I have a relationship between this 2 objects and before save my group object i look for if my session groupServive.save(group) my sessions are not removed from database.
Any help will be very appreciate !
Here is my group model :
`#Entity
#Table(name = "t_group")
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Boolean actif;
private Boolean deleted;
private Enterprise enterprise;
private String avatar;
private Date date_creation;
private Date date_update;
private Integer version;
private Set<User> users;
private List<Rule> rules;
private List<Session> sessions;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(nullable = false, unique = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(nullable = false)
public Boolean getActif() {
return actif;
}
public void setActif(Boolean actif) {
this.actif = actif;
}
#Column(nullable = false)
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#ManyToOne
#JoinColumn(name = "t_enterprise", nullable = true)
public Enterprise getEnterprise() {
return enterprise;
}
public void setEnterprise(Enterprise enterprise) {
this.enterprise = enterprise;
}
#Lob
#Column(columnDefinition = "LONGTEXT")
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Date getDate_creation() {
return date_creation;
}
public void setDate_creation(Date date_creation) {
this.date_creation = date_creation;
}
public Date getDate_update() {
return date_update;
}
public void setDate_update(Date date_update) {
this.date_update = date_update;
}
#ManyToMany
#JoinTable(name = "t_user_group", joinColumns = {
#JoinColumn(name = "t_group", nullable = false) },
inverseJoinColumns = { #JoinColumn(name = "t_user") })
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="group")
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="group")
public List<Session> getSessions() {
return sessions;
}
public void setSessions(List<Session> sessions) {
this.sessions = sessions;
}
#Version
#Column(nullable = false)
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#PreUpdate
private void setLastUpdate() {
this.setDate_update(new Date());
}
#PrePersist
private void setFirstCreationDate() {
this.setLastUpdate();
if(null == this.getDate_creation()){
this.setDate_creation(new Date());
}
}
`
ok, the solution was only to add a method in my sessionDAO
`
#Override
public void delete(Session session) {
// repository.delete(session);
if (session.getId() > 0) {
query = em.createNativeQuery("DELETE FROM `t_session` WHERE `id` = :t_session", Session.class);
query.setParameter("t_session", session.getId());
query.executeUpdate();
}
}`
I have three entities which form the association relationship by having composite primary keys that also foreign key of other tables. These are the implementation of these entites:
#Entity
#Table(name = "STUDENTSCOURSES", schema = "GPA")
#NamedQuery(name = "getAllStdCrs", query = "SELECT sc FROM StudentsCourses sc")
#IdClass(StudentCourseId.class)
public class StudentsCourses implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="studentID", insertable=false, updatable= false)
private int studentID;
#Id
#Column(name="crsID", insertable=false, updatable=false)
private int crsID;
#ManyToOne
#JoinColumn(name="STUDENTID")
Student student;
#ManyToOne
#JoinColumn(name="CRSID")
Course course;
public StudentsCourses() {
super();
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getStudentID() {
return studentID;
}
public void setCrsID(int crsID) {
this.crsID = crsID;
}
public int getCrsID() {
return crsID;
}
}
Course entity:
#Entity
#Table(name = "COURSES", schema = "GPA")
#NamedQuery(name = "getAllCourses", query = "SELECT c FROM Course c")
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="CRSID")
private int crsID;
private String name;
#OneToMany(mappedBy="course", fetch=FetchType.LAZY)
private Set<Assesment> assesments;
#OneToMany(mappedBy="course", fetch=FetchType.LAZY)
private Set<StudentsCourses> studentCourses;
public Course() {
super();
}
public int getCrsID() {
return crsID;
}
public void setCrsID(int crsID) {
this.crsID = crsID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAssesments(Set<Assesment> assesments) {
this.assesments = assesments;
}
public Set<Assesment> getAssesments() {
return assesments;
}
public void setStudentCourses(Set<StudentsCourses> studentCourses) {
this.studentCourses = studentCourses;
}
public Set<StudentsCourses> getStudentCourses() {
return studentCourses;
}
}
Student Entity:
#Entity
#Table(name = "STUDENTS", schema = "GPA")
#NamedQuery(name = "getAllStudents", query = "SELECT s FROM Student s")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int studentID;
private String studentName;
#OneToMany(mappedBy="student", fetch = FetchType.LAZY)
private Set<Assesment> assesments;
#OneToMany(mappedBy="student", fetch = FetchType.LAZY)
private Set<StudentsCourses> studentCourses;
public Student() {
super();
}
public int getStudnetID() {
return studentID;
}
public void setStudnetID(int stdID) {
this.studentID = stdID;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentName() {
return studentName;
}
public void setAssesments(Set<Assesment> assesments) {
this.assesments = assesments;
}
public Set<Assesment> getAssesments() {
return assesments;
}
public void setStudentCourses(Set<StudentsCourses> studentCourses) {
this.studentCourses = studentCourses;
}
public Set<StudentsCourses> getStudentCourses() {
return studentCourses;
}
}
When I try to lanuch the program I am getting following error:
[4/5/13 0:30:15:243 EDT] 00000028 webapp E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[com.gpa.app.servlet.LoginServlet]: <openjpa-2.1.1-SNAPSHOT-r422266:1141200 fatal user error> org.apache.openjpa.persistence.ArgumentException: Field "com.gpa.app.entities.Course.studentCourses" cannot declare that it is mapped by another field. Its mapping strategy (org.apache.openjpa.jdbc.meta.strats.HandlerFieldStrategy) does not support mapping by another field.
What could be the cause of the prob. Appreciate your help.
So the problem was in my #Id classes. In that class I didn't implemented equal and hash code method and also didn't implemented Serializable. After done that everything worked smoothly. Thanks to Eelke, he gave me the idea to try in different version and it helped me to find out the cause.
My modified code in looks like this:
public class StudentCourseId implements Serializable{
private static final long serialVersionUID = 1L;
private int studentID;
private int crsID;
public StudentCourseId() {
}
public StudentCourseId(int studentID, int crsID) {
this.studentID = studentID;
this.crsID = crsID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getStudentID() {
return studentID;
}
public void setCrsID(int crsID) {
this.crsID = crsID;
}
public int getCrsID() {
return crsID;
}
public int hashCode() {
return studentID + crsID;
}
public boolean equals(Object o) {
return ((o instanceof StudentCourseId)
&& studentID == ((StudentCourseId) o).getStudentID() && crsID == ((StudentCourseId) o)
.getCrsID());
}
}
public int getCrsID() {
return crsID;
}
}
Hope it helps for someone in the future.
Thanks,
Sas
I have recently setup a spring + hibernate project. I am using oracle DB. I have a entity as shown in the code.
#Entity
#Table(name = "P_EMP_STATUS")
public class EmployeeStatus extends AbstractEntity<Integer> implements Serializable{
private static final long serialVersionUID = 5451825528280340412L;
private Integer id;
private Region region;
private Project project;
private TaskType taskName;
private String taskType
private PrinceUser princeUser;
private Integer assignee;
private Date actualStartDate;
private Date actualFinishDate;
private Integer scheduledStartDate;
private Integer scheduledFinishDate;
private Integer effortSpent;
private String empComments;
private String mgrcomments;
private String archive;
#Id
#Column(name = "ID")
#GeneratedValue(generator="P_STATUS_SEQ", strategy=GenerationType.AUTO)
#SequenceGenerator(name="P_STATUS_SEQ", sequenceName="P_STATUS_SEQ", allocationSize=1)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "REGION_ID")
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "PROJECT_ID")
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "TASK_ID")
public TaskType getTaskName() {
return taskName;
}
public void setTaskName(TaskType taskName) {
this.taskName = taskName;
}
#Column(name = "TASK_TYPE")
public String getTaskType() {
return taskType;
}
public void setTaskType(String taskType) {
this.taskType = taskType;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "ASSIGNEE")
public PrinceUser getPrinceUser() {
return princeUser;
}
public void setPrinceUser(PrinceUser princeUser) {
this.princeUser = princeUser;
}
#Column(name = "ACT_START")
public Date getActualStartDate() {
return actualStartDate;
}
public void setActualStartDate(Date actualStartDate) {
this.actualStartDate = actualStartDate;
}
#Column(name = "ACT_FINISH")
public Date getActualFinishDate() {
return actualFinishDate;
}
public void setActualFinishDate(Date actualFinishDate) {
this.actualFinishDate = actualFinishDate;
}
#Column(name = "SCH_START")
public Integer getScheduledStartDate() {
return scheduledStartDate;
}
public void setScheduledStartDate(Integer scheduledStartDate) {
this.scheduledStartDate = scheduledStartDate;
}
#Column(name = "SCH_FINISH")
public Integer getScheduledFinishDate() {
return scheduledFinishDate;
}
public void setScheduledFinishDate(Integer scheduledFinishDate) {
this.scheduledFinishDate = scheduledFinishDate;
}
#Column(name = "EFFORT_SPENT")
public Integer getEffortSpent() {
return effortSpent;
}
public void setEffortSpent(Integer effortSpent) {
this.effortSpent = effortSpent;
}
#Column(name = "EMP_COMMENTS")
public String getEmpComments() {
return empComments;
}
public void setEmpComments(String empComments) {
this.empComments = empComments;
}
#Column(name = "MGR_COMMENTS")
public String getMgrcomments() {
return mgrcomments;
}
public void setMgrcomments(String mgrcomments) {
this.mgrcomments = mgrcomments;
}
#Column(name = "ARCHIVE")
public String getArchive() {
return archive;
}
public void setArchive(String archive) {
this.archive = archive;
}
When i try to get data from DB using
Query query = em.createQuery("FROM EmployeeStatus");
return query.getResultList();
I get the following error.
java.sql.SQLException: Invalid column type: getInt not implemented for class oracle.jdbc.driver.T4CDateAccessor
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
oracle.jdbc.driver.Accessor.unimpl(Accessor.java:358)
I have checked the mappings, everything seems alright. Can someone please help me?
You declared two dates as Integer properties:
private Integer scheduledStartDate;
private Integer scheduledFinishDate;
These fields are probably stored in a column of type Date in database, and the database driver doesn't know how to convert a date to an integer.