insert into database using jpa , jboss7.1 . #OneToMany annotation - java

I am using Jboss7.1 and jpa , ejb
I want to insert data -with OneToMany relationship- into my mysql database.
I have two entitys personne and voiture. I want to save a person in my database and associate voiture for him. The problem is that when i test my code (test), i find that there is a new personne added to my database and there is no voiture added in the table voiture
please can you help me .
code :
the entity personne
package com.domain;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Set;
/**
* The persistent class for the personne database table.
*
*/
#Entity
public class Personne implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int idpersonne;
private String nom;
//bi-directional many-to-one association to Voiture
#OneToMany(mappedBy="personne")
private Set<Voiture> voitures;
public Personne() {
}
public Personne(String nom) {
super();
this.nom = nom;
}
public int getIdpersonne() {
return this.idpersonne;
}
public void setIdpersonne(int idpersonne) {
this.idpersonne = idpersonne;
}
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Set<Voiture> getVoitures() {
return this.voitures;
}
public void setVoitures(Set<Voiture> voitures) {
this.voitures = voitures;
}
}
entity voiture
package com.domain;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the voiture database table.
*
*/
#Entity
public class Voiture implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int idvoiture;
private String type;
//bi-directional many-to-one association to Personne
#ManyToOne
private Personne personne;
public Voiture() {
}
public Voiture(String type) {
super();
this.type = type;
}
public int getIdvoiture() {
return this.idvoiture;
}
public void setIdvoiture(int idvoiture) {
this.idvoiture = idvoiture;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public Personne getPersonne() {
return this.personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
}
this is the interface
package com.DAO;
import javax.ejb.Remote;
import com.domain.Personne;
#Remote
public interface PersonneDAO {
public void save(Personne personne);
public String sayhello();
}
the implementation
package com.DAO.Impl;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.DAO.VoitureDAO;
import com.domain.Voiture;
#Stateless
public class VoitureDAOImpl implements VoitureDAO {
#PersistenceContext(name = "JPADD")
EntityManager em;
#Override
public void save(Voiture voiture) {
em.persist(voiture);
}
}
the implementation
package com.DAO.Impl;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.DAO.PersonneDAO;
import com.domain.Personne;
#Stateless
public class PersonneDAOImpl implements PersonneDAO {
#PersistenceContext(name = "JPADD")
EntityManager em;
#Override
public String sayhello() {
// TODO Auto-generated method stub
return "helllllllllllllllllo";
}
#Override
public void save(Personne personne) {
em.persist(personne);
}
}
this is the test
package test;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.DAO.PersonneDAO;
import com.domain.Personne;
import com.domain.Voiture;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
Context intialcontext;
Properties properties = new Properties();
properties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
try {
intialcontext = new InitialContext(properties);
PersonneDAO dao = (PersonneDAO) intialcontext
.lookup("ejb:/projetweb/PersonneDAOImpl!com.DAO.PersonneDAO");
// /----------------------------objet voiture-------------
Voiture voiture = new Voiture("216");
Set<Voiture> voitures = new HashSet<Voiture>();
voitures.add(voiture);
// -------------------------------------------------------
Personne personne = new Personne("slatnia");
personne.setVoitures(voitures);
dao.save(personne);
} catch (NamingException e) {
e.printStackTrace();
}
}
}
and this is my jboss-ejb-client.properties
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false

Try add following attributes to the #OneToMany annotation
#OneToMany(cascade=CascadeType.ALL)

You should add cascade = CascadeType.PERSIST in the #OneToMany
CascadeType.PERSIST
When persisting an entity, also persist the entities held in this
field. We suggest liberal application of this cascade rule, because if
the EntityManager finds a field that references a new entity during
flush, and the field does not use CascadeType.PERSIST, it is an error.
example:
#OneToMany(cascade = CascadeType.PERSIST)
private Set<Voiture> voitures;
Javadoc for CascadeType and other doc at here.

Related

How to Use Criteria and Hibernates

Hello guys I need help to create a query to use in my #Repository.
This is the sql query consult
select * from sig_versions where sft_product_name like 'kiadoc-desktop' order by created_date DESC limit 1;
And this is the output
I don't know how to create the hibernate query using Hibernate and criteria
Now how can I call this from my #Repository
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}
I'm getting the InvocationTargetException
These are my files
package ar.com.lakaut.sig.core.dao;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.InternalErrorException;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import java.util.List;
import com.curcico.jproject.core.daos.BaseAuditedEntityDaoImpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class SoftwareVersionDaoImpl extends BaseAuditedEntityDaoImpl<SoftwareVersion> implements SoftwareVersionDao {
public SoftwareVersionDaoImpl() { super(); }
Logger logger = Logger.getLogger(getClass());
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}}
And the entity
package ar.com.lakaut.sig.core.domain;
import com.curcico.jproject.core.entities.BaseAuditedEntity;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "sig_versions")
#SQLDelete(sql="UPDATE sig_versions SET deleted = '1' WHERE version_id = ? and version = ?")
#Where(clause="deleted is null")
public class SoftwareVersion extends BaseAuditedEntity implements Serializable {
public SoftwareVersion() {}
private String product_name;
private String sft_version;
private String obs;
#Id
#SequenceGenerator(name = "id_generator", sequenceName = "sig_versions_config_seq", allocationSize = 1)
#GeneratedValue(generator = "id_generator", strategy =GenerationType.SEQUENCE)
#Column(name = "sft_id", unique = true, nullable = false)
public Integer getId() { return this.id; }
#Column(name = "sft_product_name", nullable = false)
public String getProductName() { return product_name; }
public void setProductName(String product_name) { this.product_name = product_name; }
#Column(name = "sft_version", nullable = false)
public String get_Version() { return sft_version; }
public void set_Version(String version) { this.sft_version = version; }
#Column(name = "sft_obs", nullable = false)
public String getObs() { return obs; }
public void setObs(String obs) { this.obs = obs; }
}
The #Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.curcico.jproject.core.services.BaseAuditedEntityServiceImpl;
import ar.com.lakaut.sig.core.dao.SoftwareVersionDao;
import org.apache.log4j.Logger;
#Service("SoftwareVersionService")
public class SoftwareVersionServiceImpl extends BaseAuditedEntityServiceImpl<SoftwareVersion, SoftwareVersionDao> implements SoftwareVersionService {
Logger logger = Logger.getLogger(SoftwareVersionServiceImpl.class);
#Override
public String getSoftwareVersion(String name) throws BaseException {
logger.info("softwareVersionId: " + name);
return dao.getSoftwareVersion(name);
}
}
The Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.services.BaseAuditedEntityService;
import com.curcico.jproject.core.exception.BaseException;
public interface SoftwareVersionService extends BaseAuditedEntityService<SoftwareVersion> {
/**
* Params: name
* Return
* Throws BaseException
*/
public String getSoftwareVersion(String name) throws BaseException;
}
The DAO
package ar.com.lakaut.sig.core.dao;
import com.curcico.jproject.core.daos.BaseAuditedEntityDao;
import com.curcico.jproject.core.exception.BaseException;
import com.curcico.jproject.core.exception.InternalErrorException;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
public interface SoftwareVersionDao extends BaseAuditedEntityDao<SoftwareVersion>{
String getSoftwareVersion(String name) throws InternalErrorException;
}

How to POST correctly to a bidirectional relationship

So im implmenting an API using springboot, spring-data and Jackson, but im having some troubles when im trying to POST a request to an endpoint who have a Bidirection relationship of #OneToMany.
I dont have so much background so i need really help.
I have two Entities:
Partida
package lucas.duarte.jazz.model.bean;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
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 com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class Partida implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String timeA;
private String timeB;
private boolean visitante;
#OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Set> sets;
public List<Set> getSets() {
return sets;
}
public void setSets(List<Set> sets) {
this.sets = sets;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimeA() {
return timeA;
}
// Mocado o valor pois o Time A sempre e a Sao Judas
public void setTimeA(String timeA) {
this.timeA = timeA;
}
public String getTimeB() {
return timeB;
}
public void setTimeB(String timeB) {
this.timeB = timeB;
}
public boolean isVisitante() {
return visitante;
}
public void setVisitante(boolean visitante) {
this.visitante = visitante;
}
}
and SET
package lucas.duarte.jazz.model.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#Entity
#Table(name = "meu_set")
public class Set implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ponto_a")
private long pontoA;
#Column(name = "ponto_b")
private long pontoB;
#Column(name = "set_finalizado")
private boolean setFinalizado;
#ManyToOne
#JoinColumn(name = "partida_id")
private Partida partida;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getPontoA() {
return pontoA;
}
public void setPontoA(long pontoA) {
this.pontoA = pontoA;
}
public long getPontoB() {
return pontoB;
}
public void setPontoB(long pontoB) {
this.pontoB = pontoB;
}
public boolean isSetFinalizado() {
return setFinalizado;
}
public void setSetFinalizado(boolean setFinalizado) {
this.setFinalizado = setFinalizado;
}
public Partida getPartida() {
return partida;
}
public void setPartida(Partida partida) {
this.partida = partida;
}
}
This is my SetControler
package lucas.duarte.jazz.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponentsBuilder;
import lucas.duarte.jazz.model.bean.Set;
import lucas.duarte.jazz.model.service.SetService;
#Controller
#RequestMapping("/api")
public class SetController {
private SetService setServ;
#RequestMapping(value = "/set/", method = RequestMethod.POST)
public ResponseEntity<?> salvarSet(#RequestBody Set set, UriComponentsBuilder ucBuilder) {
System.out.println("Vou cadastrar um set vinculado a uma partida");
System.out.println(set.getPartida().getId());
setServ.salvarSet(set);
return new ResponseEntity(HttpStatus.CREATED);
}
}
When i POST to the URL, i get the following return
{
"timestamp": "2019-03-28T04:17:46.857+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)\n at [Source: (PushbackInputStream); line: 5, column: 14] (through reference chain: lucas.duarte.jazz.model.bean.Set[\"partida\"])",
"path": "/api/set/"
}
I Already have a Partida inside my database, but i cannot POST to this method, need really help.
This issue has nothing to do with JPA bi-directional mapping. Its raising error at the time of de serializing.
Partida -> should have zero argument constructor
Request payload should have { "partida":{"id":123}} in order to populate partida object property.
for details check this link Jackson library.
#Entity
public class Partida implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String timeA;
private String timeB;
private boolean visitante;
public Partida(){
//Default constructor required here
}
#OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade =
CascadeType.ALL)
private List<Set> sets;
public List<Set> getSets() {
return sets;
}
public void setSets(List<Set> sets) {
this.sets = sets;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimeA() {
return timeA;
}
// Mocado o valor pois o Time A sempre e a Sao Judas
public void setTimeA(String timeA) {
this.timeA = timeA;
}
public String getTimeB() {
return timeB;
}
public void setTimeB(String timeB) {
this.timeB = timeB;
}
public boolean isVisitante() {
return visitante;
}
public void setVisitante(boolean visitante) {
this.visitante = visitante;
}
}
if issue not not resolved then try JSON creator
#JsonCreator
public Partida(#JsonProperty("id") Long id, #JsonProperty("timeA") String
timeA, #JsonProperty("timeB") String timeB, #JsonProperty("desc") boolean
visitante) {
this.id = id;
this.timeA = timeA;
this.timeB= timeB;
this.visitante= visitante;
}

hibernate two way mapping insert and delete beginner

Today I did some experiments with hibernate. Unfortunately it seems if I’m misunderstanding something about the sessions.
I have three entities (book “buch”, user “benutzer” and rent “leihstellung”).
Each book knows about the rents, it’s concerned by. Each rent knows about the associated book. Furthermore each rent knows about the fitting user and of course each user knows the associated rents.
I explicitly want to have this two way mappings.
Now I wrote a small tester which inserts some data. The insert progress works as expected. After inserting some data I would like to delete a user.
If I do this before the commit, hibernate gives me an error, because the user will be reinserted be the rents it belongs to (that even happens, if I manually delete the user from this rents). Here I don’t really understand why that happens.
Everything works fine, if I do a session.close and open a new session for deleting the user.
I guess, that there is a smarter way to do this within one session. But unfortunately I don’t know how this can be done.
Any explanation is welcome.
public class Worker implements Iworker{
private Sessiongetter sg;
private MainMenu mm;
public void work(File datei)
{
sg = new Sessiongetter();
Session session = sg.getSesseion();
WlBuchart wlBuchart = new WlBuchart(1, "Sachbuch");
Buch buch = new Buch("test", "ich", 1);
buch.setWlBuchart(wlBuchart);
Buch buch2 = new Buch("versuch", "du",2);
buch2.setWlBuchart(wlBuchart);
session.beginTransaction();
session.save(wlBuchart);
session.save(buch);
session.save(buch2);
Benutzer benutzer = new Benutzer("hans", "dampf", "Lehrer", "versuch");
session.save(benutzer);
Leihstellung leihstellung = new Leihstellung(benutzer, buch);
Leihstellung leihstellung2 = new Leihstellung(benutzer, buch2);
session.save(leihstellung);
session.save(leihstellung2);
benutzer.addLeihstellung(leihstellung);
benutzer.addLeihstellung(leihstellung2);
session.update(benutzer);
buch.addLeihstellung(leihstellung);
buch2.addLeihstellung(leihstellung2);
session.update(buch);
session.update(buch2);
session.remove(benutzer);
session.flush();
session.getTransaction().commit();
session.close();
System.out.println("fertig");
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.Session;
#Entity
#Table(name="benutzer")
public class Benutzer {
#Column(nullable=false)
private String vorname, nachname, gruppe;
#Id
private String kennung;
private boolean admin;
#Column(nullable=true)
private String kennwort;
#OneToMany(cascade=CascadeType.ALL, mappedBy="benutzer")
private List<Leihstellung>leihstellungs;
public String getKennwort() {
return kennwort;
}
public void setKennwort(String kennwort) {
this.kennwort = kennwort;
}
public Benutzer(String vorname, String nachname, String gruppe, String kennung) {
this.vorname=vorname;
this.nachname=nachname;
this.gruppe=gruppe;
this.kennung=kennung;
this.leihstellungs= new ArrayList<>();
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
public String getVorname() {
return vorname;
}
public String getNachname() {
return nachname;
}
public String getGruppe() {
return gruppe;
}
public String getKennung() {
return kennung;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
public int compare(Benutzer other)
{
if (this.getNachname().compareTo(other.getNachname())!=0)
{
return this.getNachname().compareTo(other.getNachname());
}
return this.getVorname().compareTo(other.getVorname());
}
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.ManyToAny;
#Entity
#Table(name="buch")
public class Buch {
#Column(nullable=false)
private String titel;
private String autor;
#ManyToOne
private WlBuchart wlBuchart;
#OneToMany(cascade=CascadeType.ALL, mappedBy="buch")
private List<Leihstellung>leihstellungs;
public WlBuchart getWlBuchart() {
return wlBuchart;
}
public void setWlBuchart(WlBuchart wlBuchart) {
this.wlBuchart = wlBuchart;
}
#Id
private int nummer;
public Buch(String titel, String autor,int nummer) {
this.titel=titel;
this.autor=autor;
this.nummer=nummer;
leihstellungs = new ArrayList<>();
}
public Buch() {
// TODO Auto-generated constructor stub
}
public String getTitel() {
return titel;
}
public String getAutor() {
return autor;
}
public int getNummer() {
return nummer;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
}
package code.logik;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="leihstellung")
public class Leihstellung {
#ManyToOne
private Benutzer benutzer;
#Id #GeneratedValue
private int id;
#Column(nullable=false)
private LocalDate von;
private LocalDate bis;
#ManyToOne
private Buch buch;
public Leihstellung(Benutzer benutzer, Buch buch) {
this.benutzer=benutzer;
this.buch=buch;
this.von = LocalDate.now();
}
public Leihstellung() {
// TODO Auto-generated constructor stub
}
public void setAbgegeben()
{
bis = LocalDate.now();
}
public Benutzer getBenutzer() {
return benutzer;
}
public int getId() {
return id;
}
public LocalDate getVon() {
return von;
}
public LocalDate getBis() {
return bis;
}
public Buch getBuch() {
return buch;
}
}
Found the solution myself. I had to delete the references from the connected rents and books.
Now everything works find.

Updating primary key spring boot jpa

i need to update tow columns inside my table (Job this table is joint with two other tables employees and job-history)one of them is the primary key, but i get error, if someone can help!
package com.touati.org.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
#Entity
#Table(name="jobs")
#NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="JOB_ID")
private String jobId;
#Column(name="JOB_TITLE")
private String jobTitle;
#Column(name="MAX_SALARY")
private BigDecimal maxSalary;
#Column(name="MIN_SALARY")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="job")
private List<Employee> employees;
//bi-directional many-to-one association to JobHistory
#OneToMany(mappedBy="job")
private List<JobHistory> jobHistories;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
public List<JobHistory> getJobHistories() {
return this.jobHistories;
}
public void setJobHistories(List<JobHistory> jobHistories) {
this.jobHistories = jobHistories;
}
public JobHistory addJobHistory(JobHistory jobHistory) {
getJobHistories().add(jobHistory);
jobHistory.setJob(this);
return jobHistory;
}
public JobHistory removeJobHistory(JobHistory jobHistory) {
getJobHistories().remove(jobHistory);
jobHistory.setJob(null);
return jobHistory;
}
}
my controller: here when i try to look for all job in the data base it works fine, also if i try to update juste the title of the job it works fine to but in case that i try to set a new primary key for the job table it gives me error here my controller.
package com.touati.org.model;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
#Controller // This means that this class is a Controller
#RequestMapping(path="/project") // This means URL's start with /demo (after Application path)
public class MainController {
#GetMapping(path="/job")
public #ResponseBody Iterable<Job> getAllJob() {
// This returns a JSON or XML with the users
return jobRepository.findAll();
}
#GetMapping(path="/job/{jobId}")
public #ResponseBody String getJob(#PathVariable String jobId) {
Job job = jobRepository.findOne(jobId);
try {
job.setJobTitle("manager");
job.setJobId("test1");
jobRepository.save(job);
}
catch (Exception ex) {
return "Error updating the job: " + ex.toString();
}
return "Job succesfully updated!";
}
i got this error,
Error updating the user: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.touati.org.model.Job was altered from test to test1; nested exception is org.hibernate.HibernateException: identifier of an instance of com.touati.org.model.Job was altered from test to test1
Thank you for your help.
Altering the PK of an entity is not permitted - if you really have to do it, you should delete, and recreate it.
Reference (an older question) : JPA Hibernate - changing the primary key of an persisted object

Spring Data JPA Interface Type Collection with ManyToMany relationship

I am developing Spring Boot app with Spring Data JPA and H2 database. I was writing my model entity classes and I got to the moment where I need to make ManyToMany relationship between FreetimeActivity and Goal entities. In Goal class I have collection of Goalable objects. Goalable is my interface. This interface is implemented by 3 classes. I want objects of any of this classes to be stored in that collection. FreetimeActivity is one of them (but the only implemented so far). Can Spring Data make some magic and make that kind of relationship for me or do I have to make separate colletion for all of these 3 classes and merge them into one interface type collection in the end?
I tried with #ManyToMany and #JoinColumn annotations and added some testing code to starting class, but when run It throws an exception:
#OneToMany or #ManyToMany targeting an unmapped class: com.github.mesayah.assista.model.Goal.activityList[com.github.mesayah.assista.model.Goalable]
Are there any annotations that can make that for me?
FreetimeActivity.java
package com.github.mesayah.assista.model;
import javax.persistence.*;
import java.util.List;
/**
* Created by Mesayah on 03.07.2017.
*/
#Entity
#Table(name = "freetime_activity")
public class FreetimeActivity extends Activity {
#Id
#GeneratedValue
private long id;
private String name;
#ManyToMany(mappedBy = "freetime_activities")
private List<Goal> goals;
#Override
public long getId() {
return id;
}
#Override
public void setId(long id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
public List<Goal> getGoals() {
return goals;
}
public void setGoals(List<Goal> goalList) {
this.goals = goalList;
}
public FreetimeActivity(String name) {
this.name = name;
}
}
Goal.java
package com.github.mesayah.assista.model;
import javax.persistence.*;
import java.util.List;
/**
* Created by Mesayah on 02.07.2017.
*/
#Entity
public class Goal {
#Id
#GeneratedValue
private long id;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "goal_freetime_activity", joinColumns = #JoinColumn(name = "goal_id", referencedColumnName =
"id"),
inverseJoinColumns = #JoinColumn(name = "freetime_activity_id", referencedColumnName = "id"))
private List<FreetimeActivity> activityList;
private List<Milestone> milestoneList;
public Goal() {
}
public Goal(List<FreetimeActivity> activityList) {
this.activityList = activityList;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<FreetimeActivity> getActivityList() {
return activityList;
}
public void setActivityList(List<FreetimeActivity> activityList) {
this.activityList = activityList;
}
public List<Milestone> getMilestoneList() {
return milestoneList;
}
public void setMilestoneList(List<Milestone> milestoneList) {
this.milestoneList = milestoneList;
}
}
AssistaApplication.java
package com.github.mesayah.assista;
import com.github.mesayah.assista.model.Course;
import com.github.mesayah.assista.model.Exam;
import com.github.mesayah.assista.repository.CourseRepository;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.util.List;
#SpringBootApplication
#EnableJpaRepositories("com.github.mesayah.assista.model")
public class AssistaApplication {
private final static Logger logger = LoggerFactory.getLogger(AssistaApplication.class);
public static void main(String[] args) {
SpringApplication.run(AssistaApplication.class, args);
}
#Bean
#Transactional
public CommandLineRunner commandLineRunner(CourseRepository courseRepository, ExamRepository examRepository) {
return (args) -> {
Course course = new Course("Dancing Course");
Exam exam = new Exam("Dancing Test", course);
// testing save
courseRepository.save(course);
examRepository.save(exam);
course.getGrades().add(4.0);
course.getGrades().add(4.5d);
course.getGrades().add(3.5d);
// testing update
courseRepository.save(course);
// using Spring Data JPA automated repositories
List<Course> courses = (List<Course>) courseRepository.findAll();
List<Exam> result = examRepository.findByCourse(course);
Exam theExam = result.get(0);
// testing relations
logger.info("Courses in database: " + courses.size() + "\nExam's Course Id: " + theExam.getCourse().getId() + "\nCourse grades: " + theExam.getCourse().getGrades());
};
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
}

Categories

Resources