How to know if a column is surrounded by double-quotes when making an update in Hibernate? - spring

When I make an update through the aplication by submitting a form then I get invalid identifier exception. Here is the entity concerned :
#Entity
#Table(name = "pta")
public class Pta {
#Id()
#SequenceGenerator(name="s_pta", sequenceName="s_pta", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_pta")
#Column(name="pta_code")
private Long code;
#Column(name="pta_intitule")
#Lob
private String lib;
#Column(name="pta_ref")
private String ref;
#Column(name="pta_desc")
#Lob
private String descr;
#Column(name="owner")
private Long owner;
#Column(name="creation")
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date creation;
#Column(name="modification")
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date modification;
#Column(name = "deleted")
private Integer deleted;
#Column(name = "pta_definitif")
private Integer definitif;
#Column(name="pta_num_credit")
private String pta_num_credit;
#ManyToOne
#JoinColumn(name = "typ_proj_code")
private TypeProjet typ_proj_code;
#ManyToOne
#JoinColumn(name = "sect_code")
private Secteur sect_code;
#Column(name="pta_unite_execution")
private String pta_unite_execution;
#Column(name = "pta_activite")
private Integer pta_activite;
#Column(name="pta_signature")
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date pta_signature;
#Column(name="pta_vigueur")
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date pta_vigueur;
#Column(name="pta_limite_decaisse")
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date pta_limite_decaisse;
#Column(name="pta_cloture")
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date pta_cloture;
#Column(name="pta_resultat_annee")
#Lob
private String resultatAnnee;
#OneToMany(mappedBy="pta")
private List<Ressource> ressources;
#ManyToOne
#JoinColumn(name = "class_pta_code")
private ClassePta classePta;
#OneToMany(mappedBy="parent")
private List<Pta> sousPtas;
#OneToMany(mappedBy="pta")
private List<Objectif> objectifs;
#ManyToOne
#JoinColumn(name = "pta_pta_code")
private Pta parent;
#ManyToOne
#JoinColumn(name = "struct_code")
private Structure structure;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "responsable_tache" , joinColumns = {#JoinColumn(name = "pta_code")} , inverseJoinColumns = {#JoinColumn(name = "struct_code")} )
private Set<Structure> responsables_tache = new HashSet<Structure>();
#ManyToOne
#JoinColumn(name = "exer_code")
private Exer exercice;
#ManyToOne
#JoinColumn(name = "cdmt_code")
private Cdmt cdmt;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "pta_pnd" , joinColumns = {#JoinColumn(name = "pta_code")} , inverseJoinColumns = {#JoinColumn(name = "pnd_code")} )
private Set<Pnd> pnds = new HashSet<Pnd>();
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "pta_programme" , joinColumns = {#JoinColumn(name = "pta_code")} , inverseJoinColumns = {#JoinColumn(name = "prog_code")} )
private Set<Pmo> pmos = new HashSet<Pmo>();
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "pta_effet_pmo" , joinColumns = {#JoinColumn(name = "pta_code")} , inverseJoinColumns = {#JoinColumn(name = "obj_code")} )
private Set<Objectif> effets_pmo = new HashSet<Objectif>();
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "pta_produit_pmo" , joinColumns = {#JoinColumn(name = "pta_code")} , inverseJoinColumns = {#JoinColumn(name = "obj_code")} )
private Set<Objectif> produits_pmo = new HashSet<Objectif>();
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "pta_objectif_ddp" , joinColumns = {#JoinColumn(name = "pta_code")} , inverseJoinColumns = {#JoinColumn(name = "obj_code")} )
private Set<Objectif> ddps = new HashSet<Objectif>();
public Pta() {
super();
}
public Pta(Long code) {
super();
}
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
public Structure getStructure() {
return structure;
}
public void setStructure(Structure structure) {
this.structure = structure;
}
public Set<Structure> getResponsables_tache() {
return responsables_tache;
}
public void setResponsables_tache(Set<Structure> responsables_tache) {
this.responsables_tache = responsables_tache;
}
public Exer getExercice() {
return exercice;
}
public void setExercice(Exer exercice) {
this.exercice = exercice;
}
public Cdmt getCdmt() {
return cdmt;
}
public void setCdmt(Cdmt cdmt) {
this.cdmt = cdmt;
}
public String getLib() {
return lib;
}
public void setLib(String lib) {
this.lib = lib;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public Long getOwner() {
return owner;
}
public void setOwner(Long owner) {
this.owner = owner;
}
public Date getCreation() {
return creation;
}
public void setCreation(Date creation) {
this.creation = creation;
}
public Date getModification() {
return modification;
}
public void setModification(Date modification) {
this.modification = modification;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public Integer getDefinitif() {
return definitif;
}
public void setDefinitif(Integer definitif) {
this.definitif = definitif;
}
public List<Ressource> getRessources() {
return ressources;
}
public void setRessources(List<Ressource> ressources) {
this.ressources = ressources;
}
public ClassePta getClassePta() {
return classePta;
}
public void setClassePta(ClassePta classePta) {
this.classePta = classePta;
}
public List<Pta> getSousPtas() {
return sousPtas;
}
public void setSousPtas(List<Pta> sousPtas) {
this.sousPtas = sousPtas;
}
public List<Objectif> getObjectifs() {
return objectifs;
}
public void setObjectifs(List<Objectif> objectifs) {
this.objectifs = objectifs;
}
public Pta getParent() {
return parent;
}
public void setParent(Pta parent) {
this.parent = parent;
}
public Set<Pnd> getPnds() {
return pnds;
}
public void setPnds(Set<Pnd> pnds) {
this.pnds = pnds;
}
public Set<Pmo> getPmos() {
return pmos;
}
public void setPmos(Set<Pmo> pmos) {
this.pmos = pmos;
}
public Set<Objectif> getEffets_pmo() {
return effets_pmo;
}
public void setEffets_pmo(Set<Objectif> effets_pmo) {
this.effets_pmo = effets_pmo;
}
public Set<Objectif> getProduits_pmo() {
return produits_pmo;
}
public void setProduits_pmo(Set<Objectif> produits_pmo) {
this.produits_pmo = produits_pmo;
}
public Set<Objectif> getDdps() {
return ddps;
}
public void setDdps(Set<Objectif> ddps) {
this.ddps = ddps;
}
public String getPta_num_credit() {
return pta_num_credit;
}
public void setPta_num_credit(String pta_num_credit) {
this.pta_num_credit = pta_num_credit;
}
public TypeProjet getTyp_proj_code() {
return typ_proj_code;
}
public void setTyp_proj_code(TypeProjet typ_proj_code) {
this.typ_proj_code = typ_proj_code;
}
public String getPta_unite_execution() {
return pta_unite_execution;
}
public void setPta_unite_execution(String pta_unite_execution) {
this.pta_unite_execution = pta_unite_execution;
}
public Integer getPta_activite() {
return pta_activite;
}
public void setPta_activite(Integer pta_activite) {
this.pta_activite = pta_activite;
}
public Date getPta_signature() {
return pta_signature;
}
public void setPta_signature(Date pta_signature) {
this.pta_signature = pta_signature;
}
public Date getPta_vigueur() {
return pta_vigueur;
}
public void setPta_vigueur(Date pta_vigueur) {
this.pta_vigueur = pta_vigueur;
}
public Date getPta_limite_decaisse() {
return pta_limite_decaisse;
}
public void setPta_limite_decaisse(Date pta_limite_decaisse) {
this.pta_limite_decaisse = pta_limite_decaisse;
}
public Date getPta_cloture() {
return pta_cloture;
}
public void setPta_cloture(Date pta_cloture) {
this.pta_cloture = pta_cloture;
}
public String getResultatAnnee() {
return resultatAnnee;
}
public void setResultatAnnee(String resultatAnnee) {
this.resultatAnnee = resultatAnnee;
}
public Secteur getSectCode() {
return sect_code;
}
public void setSectCode(Secteur sectCode) {
this.sect_code = sectCode;
}
#Override
public String toString() {
return String.valueOf(code);
}
}
Here is the database table associated to it :
create table pta
(
pta_code number(15) not null,
sect_code number(15),
struct_code varchar2(15),
cdmt_code varchar2(15),
typ_proj_code number(5),
class_pta_code number(5) not null,
pta_pta_code number(15),
mode_real_code number(10),
exer_code varchar2(4) not null,
pta_ref varchar2(25),
pta_intitule clob,
pta_definitif smallint,
pta_desc clob,
pta_comment clob,
owner integer,
creation date,
modification date,
deleted smallint default 0,
pta_signature date,
pta_vigueur date,
pta_limite_decaisse date,
pta_cloture date,
pta_num_credit varchar2(50),
pta_unite_execution varchar2(255),
pta_activite smallint default 1,
pta_resultat_annee clob,
constraint pk_pta primary key (pta_code)
);
The invalid identifier exception is on the pta_resultat_annee column.
This exception occurs generally when making an update with column surrounded by double-quotes. So what in my code is wrong ?
update :
here is what is executed by the application by using Hibernate :
Hibernate: update pta set cdmt_code=?, class_pta_code=?, creation=?, pta_definitif=?, deleted=?, exer_code=?, modification=?, owner=?, pta_pta_code=?, pta_activite=?, pta_cloture=?, pta_limite_decaisse=?, pta_num_credit=?, pta_signature=?, pta_unite_execution=?, pta_vigueur=?, pta_ref=?, sect_code=?, struct_code=?, typ_proj_code=?, pta_desc=?, pta_intitule=?, pta_resultat_annee=? where pta_code=?

Related

How to do a ManyToMany relationship insert

I am studying spring boot data using this API SWAPI, I did almost things but now I dont know how to map the relationship about two lists, above you can see my code and entities.
Entity Film
#Data
#Entity
public class Film extends Persistent<Long> {
private String title;
#JsonProperty(value = "episode_id")
private int episodeId;
#JsonProperty(value = "opening_crawl")
#Column(columnDefinition = "CLOB")
private String openingCrawl;
private String director;
private String producer;
#JsonDeserialize(converter = StringToLocalDateConverter.class)
#JsonProperty(value = "release_date")
private LocalDate releaseDate;
#JsonDeserialize(converter = ApiURLToEntitiesConverter.class)
#ManyToMany(mappedBy = "films")
private List<Person> characters;
#JsonDeserialize(converter = StringToLocalDateTimeConverter.class)
private LocalDateTime created;
#JsonDeserialize(converter = StringToLocalDateTimeConverter.class)
private LocalDateTime edited;
private String url;
}
Entity Person
#Data
#Entity
public class Person extends Persistent<Long> {
private String name;
private String height;
private String mass;
#JsonProperty(value = "hair_color")
private String hairColor;
#JsonProperty(value = "skin_color")
private String skinColor;
#JsonProperty(value = "eye_color")
private String eyeColor;
#JsonProperty(value = "birth_year")
private String birthYear;
private String gender;
#JsonDeserialize(converter = ApiURLToEntityConverter.class)
#JoinColumn(name = "planet_id", foreignKey = #javax.persistence.ForeignKey(name = "none"))
#OneToOne(optional = true)
private Planet homeworld;
#JsonDeserialize(converter = ApiURLToEntitiesConverter.class)
#ManyToMany
#JoinTable(
name = "film_person",
joinColumns = #JoinColumn(name = "film_fk", referencedColumnName = "id", nullable = true),
inverseJoinColumns = #JoinColumn(name = "person_fk", referencedColumnName = "id", nullable = true))
private List<Film> films;
#JsonDeserialize(converter = StringToLocalDateTimeConverter.class)
private LocalDateTime created;
#JsonDeserialize(converter = StringToLocalDateTimeConverter.class)
private LocalDateTime edited;
private String url;
}
I am trying to use the spring jpa method to saveAll
#Override
public List<T> insertAll(List<T> entities) {
for (Persistent entity : entities) {
Set<ConstraintViolation<Persistent>> violations = validator.validate(entity);
if (violations != null && !violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
return repository.saveAll(entities);
}
Converter Method
#Override
public List convert(List<String> s) {
if (s == null || s.isEmpty()) {
return null;
}
List objetos = new LinkedList();
for (String url : s) {
if (url.contains("people")) {
objetos.add(Util.getPerson(url));
}
if (url.contains("planets")) {
objetos.add(Util.getPlanet(url));
}
if (url.contains("starships")) {
objetos.add(Util.getStarship(url));
}
if (url.contains("vehicles")) {
objetos.add(Util.getVehicle(url));
}
if (url.contains("species")) {
objetos.add(Util.getSpecie(url));
}
}
return objetos;
}
}
Util method
public static Person getPerson(String characterApiUrl) {
if (characterApiUrl == null || characterApiUrl.isEmpty()) {
return null;
}
Person person = new Person();
person.setId(StringUtil.getIdEntity(characterApiUrl, "people/"));
return person;
}
The relationship table is being created but no populated

Error mapping OneToMany or ManyToOne unmapped class

I have this problem :
Error creating bean with name 'ICustomerDao' defined in com.biblio.fr.biblio.repository.ICustomerDao defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.biblio.fr.biblio.entite.Book.loans[com.biblio.fr.biblio.entite.Loan]
this is my code :
#Entity
#Table(name = "BOOK")
public class Book {
private Integer id;
private String title;
private String isbn;
private LocalDate releaseDate;
private LocalDate registerDate;
private Integer totalExamplaries;
private String author;
private Category category;
Set<Loan> loans = new HashSet<Loan>();
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "BOOK_ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "TITLE", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "ISBN", nullable = false, unique = true)
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
#Column(name = "RELEASE_DATE", nullable = false)
public LocalDate getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(LocalDate releaseDate) {
this.releaseDate = releaseDate;
}
#Column(name = "REGISTER_DATE", nullable = false)
public LocalDate getRegisterDate() {
return registerDate;
}
public void setRegisterDate(LocalDate registerDate) {
this.registerDate = registerDate;
}
#Column(name = "TOTAL_EXAMPLARIES")
public Integer getTotalExamplaries() {
return totalExamplaries;
}
public void setTotalExamplaries(Integer totalExamplaries) {
this.totalExamplaries = totalExamplaries;
}
#Column(name = "AUTHOR")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#ManyToOne(optional = false)
#JoinColumn(name = "CAT_CODE", referencedColumnName = "CODE")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.book", cascade =
// CascadeType.ALL)
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk", cascade = CascadeType.ALL)
public Set<Loan> getLoans() {
return loans;
}
public void setLoans(Set<Loan> loans) {
this.loans = loans;
}
}
public class Loan implements Serializable {
private static final long serialVersionUID = 144293603488149743L;
private LoanId pk = new LoanId();
private LocalDate beginDate;
private LocalDate endDate;
private LoanStatus status;
#EmbeddedId
public LoanId getPk() {
return pk;
}
public void setPk(LoanId pk) {
this.pk = pk;
}
#Column(name = "BEGIN_DATE", nullable = false)
public LocalDate getBeginDate() {
return beginDate;
}
public void setBeginDate(LocalDate beginDate) {
this.beginDate = beginDate;
}
#Column(name = "END_DATE", nullable = false)
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
#Enumerated(EnumType.STRING)
#Column(name = "STATUS")
public LoanStatus getStatus() {
return status;
}
public void setStatus(LoanStatus status) {
this.status = status;
}
}
#Embeddable
public class LoanId implements Serializable {
private static final long serialVersionUID = 3912193101593832821L;
private Book book;
private Customer customer;
private LocalDateTime creationDateTime;
public LoanId() {
super();
}
public LoanId(Book book, Customer customer) {
super();
this.book = book;
this.customer = customer;
this.creationDateTime = LocalDateTime.now();
}
#ManyToOne
public Book getBook() {
return book;
}
public void setBook(Book bbok) {
this.book = bbok;
}
#ManyToOne
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#Column(name = "CREATION_DATE_TIME")
public LocalDateTime getCreationDateTime() {
return creationDateTime;
}
public void setCreationDateTime(LocalDateTime creationDateTime) {
this.creationDateTime = creationDateTime;
}
}
#Table(name = "CUSTOMER")
public class Customer {
private Integer id;
private String firstName;
private String lastName;
private String job;
private String address;
private String email;
private LocalDate creationDate;
Set<Loan> loans = new HashSet<Loan>();
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CUSTOMER_ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "FIRST_NAME", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "JOB")
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
#Column(name = "ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "EMAIL", nullable = false, unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "CREATION_DATE", nullable = false)
public LocalDate getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDate creationDate) {
this.creationDate = creationDate;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.customer", cascade = CascadeType.ALL)
public Set<Loan> getLoans() {
return loans;
}
public void setLoans(Set<Loan> loans) {
this.loans = loans;
}
}
public class Category {
public Category() {
}
public Category(String code, String label) {
super();
this.code = code;
this.label = label;
}
private String code;
private String label;
#Id
#Column(name = "CODE")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name = "LABEL", nullable = false)
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
#Repository
public interface ICategoryDao extends JpaRepository<Category, Integer> {
}
public interface ICustomerDao extends JpaRepository<Customer, Integer> {
public Customer findCustomerByEmailIgnoreCase(String email);
public List<Customer> findCustomerByLastNameIgnoreCase(String lastName);
}
I can't see where is the problem of my oneTomany annotation
Anyone can, i help me.

Getting ConstraintViolationException while saving a row with embedded key in the table with many-to-many mapping between two entities using Spring JPA

In our spring boot Restful WebService, we have two master tables with many-to-many relationship between them. But in the transaction table, we want one extra field (current_time) as part of the embedded key other than the primary keys of the two tables. Now, we’ve created a separate class for defining embedded primary key using #Embeddable. Now, while inserting one transaction row to transaction table using Spring JPA, I am manually setting the primary keys in the corresponding entity and calling the save method on corresponding repository. But It is giving me ConstraintViolationException as the current_time is going with null value even if I have manually set it. Any help would be highly appreciated.
First Entity is as follows :
#Entity
#Table(name = "project")
public class Project {
#Id
#GenericGenerator(name = "projectid", strategy = "com.sample.upload.entity.ProjectIDGenerator")
#GeneratedValue(generator = "projectid")
#Column(name = "projectid")
private String projectID;
#Column(name = "project_name")
private String projectName;
#Column(name = "project_descr")
private String projectDesc;
#Column(name = "project_input_path")
private String projectPath;
#Column(name = "project_creation_time")
private Calendar projectCreationTime;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "project_migration", joinColumns = #JoinColumn(name = "projectid", referencedColumnName = "projectid"), inverseJoinColumns = #JoinColumn(name = "migratorid", referencedColumnName = "migratorid"))
private List<Migrator> migrators;
#Column(name = "account_name")
private String accountName;
#Column(name = "account_group")
private String accountGroup;
public String getProjectID() {
return projectID;
}
public void setProjectID(String projectID) {
this.projectID = projectID;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountGroup() {
return accountGroup;
}
public void setAccountGroup(String accountGroup) {
this.accountGroup = accountGroup;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDesc() {
return projectDesc;
}
public void setProjectDesc(String projectDesc) {
this.projectDesc = projectDesc;
}
public String getProjectPath() {
return projectPath;
}
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
public Calendar getProjectCreationTime() {
return projectCreationTime;
}
public void setProjectCreationTime(Calendar projectCreationTime) {
this.projectCreationTime = projectCreationTime;
}
public List<Migrator> getMigrators() {
return migrators;
}
public void setMigrators(List<Migrator> migrators) {
this.migrators = migrators;
}
}
Second Entity :
#Entity
#GenericGenerator(name = "generatorName", strategy = "increment")
#Table(name = "migrator")
public class Migrator {
#Id
#GeneratedValue(generator = "generatorName")
#Column(name = "migratorid")
private String migratorId;
#Column(name = "src_tech_name")
private String srcTechName;
#Column(name = "dest_tech_name")
private String destTechName;
#Column(name = "migrator_name")
private String migratorName;
#Column(name = "migrator_type")
private String migratorType;
public String getMigratorId() {
return migratorId;
}
public void setMigratorId(String migratorId) {
this.migratorId = migratorId;
}
public String getSrcTechName() {
return srcTechName;
}
public void setSrcTechName(String srcTechName) {
this.srcTechName = srcTechName;
}
public String getDestTechName() {
return destTechName;
}
public void setDestTechName(String destTechName) {
this.destTechName = destTechName;
}
public String getMigratorName() {
return migratorName;
}
public void setMigratorName(String migratorName) {
this.migratorName = migratorName;
}
public String getMigratorType() {
return migratorType;
}
public void setMigratorType(String migratorType) {
this.migratorType = migratorType;
}
#Override
public String toString() {
return "Technology [migratorId=" + migratorId + ", srcTechName=" + srcTechName + ", destTechName="
+ destTechName + ", migratorName=" + migratorName + ", migratorType=" + migratorType + "]";
}
}
The join (transaction) table's entity :
#Entity
#Table(name = "project_migration")
public class ProjectMigration {
#EmbeddedId
private ProjectMigrationID migrationId;
#Column(name ="migration_finish_time")
private Calendar migrationFinishTime;
#Column(name ="time_in_millis_for_migration")
private long timeInMillisForMigration;
#Column(name ="migration_status")
private String migrationStatus;
#Column(name ="migrated_codebase_path")
private String migratedCodeBasePath;
The embedded Primary Key class is as follows:
#Embeddable
public class ProjectMigrationID implements Serializable {
private static final long serialVersionUID = -3623993529011381924L;
#Column(name = "projectid")
private String projectId;
#Column(name = "migratorid")
private String migratorId;
#Column(name = "migration_start_time")
private Calendar migrationStartTime;
public ProjectMigrationID() {
}
public ProjectMigrationID(String projectId, String migratorId, Calendar migrationStartTime) {
this.projectId = projectId;
this.migratorId = migratorId;
this.migrationStartTime = migrationStartTime;
}
The snippet from service Class :
for (String migratorId : data.getMigratorIds()) {
Migrator migrator = migratorRepository.findByMigratorId(migratorId);
migrators.add(migrator);
}
if (projectId != null) {
project = projectRepository.findByProjectID(projectId);
System.out.println(project==null);
project.setMigrators(migrators);
System.out.println("I am here");
if (project != null) {
//project.setMigrationStatus("In Progress");
ProjectMigrationID pmId = new ProjectMigrationID();
pmId.setProjectId(project.getProjectID());
pmId.setMigratorId(project.getMigrators().get(0).getMigratorId());
pmId.setMigrationStartTime(new GregorianCalendar());
ProjectMigration pm = new ProjectMigration();
pm.setMigrationId(pmId);
pm.setMigrationStatus("Pending");
projectMigrationRepository.save(pm);
That's because of the #JoinTable where the date is not included and it skips the insertion. If you include a column with all the primary keys needed, it will work as expected.
Only the columns mapped via #JoinTable will be included during insertion or update (defaults to true when mapped)
Either include the date time column in the Project class or use association without #JoinTable.
I'm editing via mobile. So please ignore typos if any.

Spring data repositories - performance issue

I'm using Spring , JPArepostories and hibernate, to save some entities to database.
My entities :
Users:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "CARDID",unique=true)
private String cardId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name ="SUPPLIERUSERID", nullable = true)
#JsonIgnore
private SupplierUser supplierUser;
#Column(name = "NAME")
private String name;
#Column(name = "SURENAME")
private String sureName;
#Column(name = "ACTIVE")
private Boolean active;
#Column(name = "SMS")
private String sms;
#Column(name = "EMAIL")
private String email;
#OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Box> boxList = new ArrayList<Box>();
#OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Notification> notificationList = new ArrayList<Notification>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public SupplierUser getSupplierUser() {
return supplierUser;
}
public void setSupplierUser(SupplierUser supplierUser) {
this.supplierUser = supplierUser;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSureName() {
return sureName;
}
public void setSureName(String sureName) {
this.sureName = sureName;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getSms() {
return sms;
}
public void setSms(String sms) {
this.sms = sms;
}
public List<Box> getBoxList() {
return boxList;
}
public void setBoxList(List<Box> boxList) {
this.boxList = boxList;
}
public List<Notification> getNotificationList() {
return notificationList;
}
public void setNotificationList(List<Notification> notificationList) {
this.notificationList = notificationList;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Users have boxes:
#Entity
#Table(name = "boxes")
public class Box {
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name ="USERID", nullable = true)
#JsonIgnore
private User user;
#Column(name = "BOXNUMBER",unique=true)
private int boxNumber;
#Column(name = "MODBUSADDRESS")
private int modbusAddress;
#Column(name = "MODBUSREGISTER")
private int modbusRegister;
#Column(name = "STATE")
private String state;
#OneToMany(mappedBy = "box", fetch =FetchType.EAGER,cascade = CascadeType.ALL)
private List<Transaction> transactionsList = new ArrayList<Transaction>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getModbusAddress() {
return modbusAddress;
}
public void setModbusAddress(int modbusAddress) {
this.modbusAddress = modbusAddress;
}
public int getModbusRegister() {
return modbusRegister;
}
public void setModbusRegister(int modbusRegister) {
this.modbusRegister = modbusRegister;
}
public List<Transaction> getTransactionsList() {
return transactionsList;
}
public void setTransactionsList(List<Transaction> transactionsList) {
this.transactionsList = transactionsList;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getBoxNumber() {
return boxNumber;
}
public void setBoxNumber(int boxNumber) {
this.boxNumber = boxNumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Boxes have transactions:
#Entity
#Table(name = "transactions")
public class Transaction {
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name ="BOXID", nullable = true)
#JsonIgnore
private Box box;
#Column(name = "TYPE")
private String type;
#Column(name = "SUPPLIERUSERCARDID")
private String supplierUserCardId;
#Column(name = "DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#OneToMany(mappedBy = "transaction", fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<Notification> notificationsList = new ArrayList<Notification>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Box getBox() {
return box;
}
public void setBox(Box box) {
this.box = box;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getSupplierUserCardId() {
return supplierUserCardId;
}
public void setSupplierUserCardId(String supplierUserCardId) {
this.supplierUserCardId = supplierUserCardId;
}
public List<Notification> getNotificationsList() {
return notificationsList;
}
public void setNotificationsList(List<Notification> notificationsList) {
this.notificationsList = notificationsList;
}
}
And transaction have notifications (notification refer as well to user):
#Entity
#Table(name = "notifications")
public class Notification {
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name ="TRANSACTIONID", nullable = true)
#JsonIgnore
private Transaction transaction;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name ="USERID", nullable = true)
#JsonIgnore
private User user;
#Column(name = "TYPE")
private String type;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED")
private Date created;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "SENDED")
private Date sended;
#Column(name = "RETRIES")
private Long retries;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getSended() {
return sended;
}
public void setSended(Date sended) {
this.sended = sended;
}
public Long getRetries() {
return retries;
}
public void setRetries(Long retries) {
this.retries = retries;
}
public Transaction getTransaction() {
return transaction;
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
And my question is - what I'm doing wrong, because following method for list with 150 boxes inside takes about 20 seconds to finish.
public void changeBoxOwners(ArrayList<Box> boxList){
String id = theSoftwareCore.getSupplierUser().getCardId();
ArrayList<Box> boxToSave = new ArrayList<Box>();
for (Box box : boxList){
Box existingBox = theSoftwareCore.boxServiceImp.findByBoxNumber(box.getBoxNumber());
existingBox.setState("full");
User user = theSoftwareCore.userServiceImp.findOneByCardId(box.getUser().getCardId());
//deleting not sent notifications
for (Transaction trans : existingBox.getTransactionsList()){
for (Notification notif: trans.getNotificationsList()){
if (notif.getSended()==null){
notif.setSended(new Date(0));
}
}
}
Transaction transaction = new Transaction();
transaction.setType("in");
transaction.setSupplierUserCardId(id);
transaction.setDate(new Date());
transaction.setBox(existingBox);
Notification notification = new Notification();
notification.setCreated(new Date());
notification.setType("smsTakeYourStaff");
notification.setTransaction(transaction);
notification.setUser(user);
existingBox.setUser(user);
transaction.getNotificationsList().add(notification);
existingBox.getTransactionsList().add(transaction);
boxToSave.add(existingBox);
}
System.out.println("Start saving" + new Date());
theSoftwareCore.boxServiceImp.saveAll(boxToSave);
System.out.println("End " + new Date());
}
Thanks for your time in advance.

Spring Data Paging and Sorting Repository not deleting data

So all I'm trying to do is allow users to delete their own comments and posts in my application, and I have a form that's supposed to run a controller method that should delete it, but it's not working.
I'll show you my controller and repository to show you guys what I'm trying to do.
So here's my Controller method
#RequestMapping(value="userEdits/editComment/{commentId}/deleteComment", method=RequestMethod.POST)
public String deleteComment (#PathVariable Long commentId, #AuthenticationPrincipal User user)
{
Comment comment = commentRepo.findOne(commentId);
User savedUser = userRepo.findUserByUsername(user.getUsername());
savedUser.getCourses().remove(comment);
commentRepo.delete(comment);
return "redirect:/userEdits";
}
And I can even run this in debug mode and see that the right comment is in the commentRepo.delete(comment); line. And it runs all the through and returns the userEdits screen, just like it should, without any errors, but the comment is still there after it runs through everything.
Here's my repository class, it's pretty simple, but who knows, I could be missing something.
public interface CommentRepository extends PagingAndSortingRepository <Comment, Long>{
public Page<Comment> findByPostOrderByIdDesc(Post post, Pageable pageable);
public List<Comment> findByUserOrderByIdDesc(User user);
}
I'm confused because this should be a simple task and it appears that it's running through and returning the view I tell it to, without error.
So if anyone can see where I'm going wrong that would be great. Thanks in advance.
UPDATE
User Entity
#Entity
#Table(name = "users")
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class User {
private Long id;
#ValidEmail
#NotNull
#NotEmpty
private String email;
private String username;
private String password;
private University university;
private Set<Authorities> authorities = new HashSet<>();
private Set<Course> courses = new HashSet<>();
private Set<Post> posts = new HashSet<>();
private Set<Comment> comments = new HashSet<>();
private Set<StudySet> studySet = new HashSet<>();
private Set<Course> myCourses = new HashSet<Course>();
public User() {
}
public User(User user) {
this.id = user.getId();
this.email = user.getEmail();
this.username = user.getUsername();
this.password = user.getPassword();
this.university = user.getUniversity();
this.authorities = user.getAuthorities();
this.courses = user.getCourses();
this.posts = user.getPosts();
this.comments = user.getComments();
this.studySet = user.getStudySet();
this.myCourses = user.getMyCourses();
}
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user", orphanRemoval = true)
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user", orphanRemoval = true)
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
#JsonManagedReference
#JsonIgnoreProperties(allowGetters = true, value = "user")
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
public Set<Authorities> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authorities> authorities) {
this.authorities = authorities;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user", orphanRemoval = true)
public Set<StudySet> getStudySet() {
return studySet;
}
public void setStudySet(Set<StudySet> studySet) {
this.studySet = studySet;
}
#ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
#JoinTable(name = "user_myCourses")
public Set<Course> getMyCourses() {
return myCourses;
}
public void setMyCourses(Set<Course> myCourses) {
this.myCourses = myCourses;
}
}
Comment Entity
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Comment {
public Long id;
#Size(min = 1, max = 140)
public String comment;
public Post post;
public User user;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "dd-MMM-YYYY")
private LocalDate date;
#Temporal(TemporalType.TIME)
#DateTimeFormat(pattern = "HH:mm:ss")
private LocalTime time;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "MM/dd/yyyy HH:mm:ss")
private LocalDateTime dateTime;
public Comment() {
}
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Size(min = 1, max = 140)
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#ManyToOne
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
#ManyToOne
#JsonBackReference
#JsonIgnoreProperties(value = { "comments" }, allowGetters = true)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalTime getTime() {
return time;
}
public void setTime(LocalTime time) {
this.time = time;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Comment other = (Comment) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Comment(Long id, String comment, Post post, User user, LocalDate date, LocalDateTime dateTime) {
this.id = id;
this.comment = comment;
this.post = post;
this.user = user;
this.date = date;
this.dateTime = dateTime;
}
}
UPDATE
So I realized I needed to addorphanRemoval = true to the comment of the user, now I get the error the entity must not be null when I run the controller method, however it does delete the comment. But I need my app to run the method and return the view I ask it to, without the error message popping up.
The problem is in your CascadeType. You've specified:
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user", orphanRemoval = true)
CascadeType.ALL means that comments are managed by user entity and you can't delete comment directly. You should read about cascade types and change it for your needs or you have orphanRemoval = true so you can simply save user after deletion and comment should be deleted for example
savedUser.getCourses().remove(comment);
userRepo.save(savedUser);

Resources