I'm working with my hospital project with java spring and angular.
When I try to insert a new Doctor(Medico.java) in a Hospital (called StrutturaSanitaria.java)
with a #OneToOne Relationship mapping a customed relation class, called MedicoStrutturaSanitaria.java. This class is created because I needed an extra column which is dataAssunzione (hireDate).
As long as I add just the Doctor the Post request works just fine, it adds the instance of the Doctor in the database (I'm using MySql).
THE PROBLEM IS: When I try to add the relation instance to the DB for every value, except for the hireDate, it gives me null value.
I'm testing the post requests with Postman.
here is the code
Medico.java
#Entity
#Table(name = "medico")
public class Medico
{
#Id
private String codiceFiscale;
#Column(nullable = false)
private String nome;
#Column(nullable = false)
private String cognome;
#Column(nullable = false)
private String genere;
#Column(nullable = false)
private LocalDate dataNascita;
#Column(unique = true, nullable = false)
private String email_uno;
#Column(unique = true, nullable = false)
private String cellulare_uno;
#Column(nullable = false)
private String indirizzo;
#Column(nullable = false)
private String citta;
#Column(nullable = false)
private String provincia;
#OneToOne
private MedicoStrutturaSanitaria medicoStrutturaSanitaria;
public Medico()
{}
public Medico(String codiceFiscale, String nome, String cognome, String genere,
LocalDate dataNascita, String email_uno, String cellulare_uno,
String indirizzo, String citta, String provincia, MedicoStrutturaSanitaria medicoStrutturaSanitaria)
{
this.codiceFiscale = codiceFiscale;
this.nome = nome;
this.cognome = cognome;
this.genere = genere;
this.dataNascita = dataNascita;
this.email_uno = email_uno;
this.cellulare_uno = cellulare_uno;
this.indirizzo = indirizzo;
this.citta = citta;
this.provincia = provincia;
this.medicoStrutturaSanitaria = medicoStrutturaSanitaria;
}
//getters and setters
MedicoStrutturaSanitaria.java
#Entity
#Table(name = "medico_struttura_sanitaria")
#IdClass(MedicoStrutturaSanitariaID.class)
public class MedicoStrutturaSanitaria
{
#Id
#JoinColumn(name="medico",referencedColumnName = "codiceFiscale")
#ManyToOne
private Medico medico;
#Id
#JoinColumn(name="struttura_sanitaria", referencedColumnName = "codice")
#ManyToOne
private StrutturaSanitaria strutturaSanitaria;
#Id
private LocalDate dataAssunzione;
public MedicoStrutturaSanitaria()
{}
public MedicoStrutturaSanitaria(Medico medico, StrutturaSanitaria strutturaSanitaria, LocalDate dataAssunzione)
{
this.medico = medico;
this.strutturaSanitaria = strutturaSanitaria;
this.dataAssunzione = dataAssunzione;
}
//getters and setters
Postman request. The object passed as parameters are existing instances
Post request method. As you can see all the parameters thar are passed are null, excpet for hireDate
UPDATE 1
THIS IS MY CONTROLLER
#PostMapping("/inserisci-medico-struttura-sanitaria")
public ResponseEntity<MedicoStrutturaSanitaria> inserisciMedicoStrutturaSanitaria(#RequestBody MedicoStrutturaSanitaria medicoStrutturaSanitaria)
{
System.out.println("Inserendo medico struttura");
try
{
System.out.println("Inserendo medico");
this.medicoStrutturaSanitariaRepository.save(medicoStrutturaSanitaria);
return ResponseEntity.ok(medicoStrutturaSanitaria);
}
catch (Exception exception)
{
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
Before saving relation between doctors and Hospitals. Check if that hospital and Doctor exist in Database or not.(If doesn't not exists create a new one).
If not recommend to send the object of Joining table over the Post request.
Instead 1ts send a two get requests(Get Doctors and Hospitals).
Send one post request(addDoctorInHospital) with doctor_id and hostipal_id and date with provided by the server.
Related
I am working on a Spring project and I am using JPA to access database. I have two tables that have #ManyToMany property. And one other table (join table) that keeps the foreign keys of those two tables. I need to retrieve the join table with a given property of one of the tables. I tried to use JPA methods and queries but I couldn't find a solution.
I have an abstract class called Course:
#Data
#NoArgsConstructor
#MappedSuperclass
public abstract class Course {
#Id
#GeneratedValue(generator = "UUID")
#Column(name = "id", nullable = false)
private UUID courseId;
#NotBlank
#Column(name = "course_code", nullable = false)
private String courseCode;
#NotBlank
#Column(name = "course_name", nullable = false)
private String courseName;
#NotNull
#Column(name = "ects", nullable = false)
private Double ects;
public Course(
#JsonProperty("id") UUID id,
#JsonProperty("courseCode") String courseCode,
#JsonProperty("courseName") String courseName,
#JsonProperty("ects") Double ects) {
this.courseId = id;
this.courseCode = courseCode;
this.courseName = courseName;
this.ects = ects;
}
}
I have two database model classes that extends Course:
#Entity
#Data
#NoArgsConstructor
#EqualsAndHashCode(callSuper = true)
#Table(name = "uni_course")
public class UniCourse extends Course {
#NotNull
#Column(name = "department", nullable = false)
#Enumerated(EnumType.STRING)
private Department department;
#ManyToMany
#JoinTable(
name = "approved_courses",
joinColumns = #JoinColumn(name = "uni_course_id"),
inverseJoinColumns = #JoinColumn(name = "host_course_id"))
private Set<HostCourse> approvedCourses;
public UniCourse(
#JsonProperty("id") UUID id,
#JsonProperty("courseCode") String courseCode,
#JsonProperty("courseName") String courseName,
#JsonProperty("ects") Double ects,
#JsonProperty("department") Department department) {
super(id, courseCode, courseName, ects);
this.department = department;
this.bilkentCredit = bilkentCredit;
}
}
and,
#Entity
#Data
#NoArgsConstructor
#EqualsAndHashCode(callSuper = true)
#Table(name = "host_course")
public class HostCourse extends Course {
#NotBlank
#Column(name = "syllabus", nullable = false)
private String syllabus;
#NotBlank
#Column(name = "web_page", nullable = true)
private String webPage;
#NotNull
#Column(name = "university_id", nullable = false)
private UUID universityId;
#ManyToMany(mappedBy = "approvedCourses")
private Set<UniCourse> uniCourses;
public HostCourse(
#JsonProperty("id") UUID id,
#JsonProperty("courseCode") String courseCode,
#JsonProperty("courseName") String courseName,
#JsonProperty("ects") Double ects,
#JsonProperty("syllabus") String syllabus,
#JsonProperty("webPage") String webPage,
#JsonProperty("universityId") UUID universityId) {
super(id, courseCode, courseName, ects);
this.syllabus = syllabus;
this.webPage = webPage;
this.universityId = universityId;
this.courseApproval = courseApproval;
}
}
I want to get approvedCourses using universityId of HostCourse. How can I achieve this?
I tried using the findByApprovedCoursesUniversityId(UUID universityId) method and it returned the following:
{
"data": [
{
"courseCode": "CS315",
"courseName": "Programming Languages",
"ects": 5.0,
"department": "CS",
"courseId": "8a890716-aaf1-40bb-81b2-e0a638b878dd",
"approvedCourses": []
}
]
"timestamp": "2022.12.15 21.48.32",
"status": "OK"
}
I also want to get approved courses but it returns an empty array.
I'm a beginner with Spring, so I'm sorry if I make some dumb mistake.
Person.java
#Embeddable
#Data
public class Person {
#Column(nullable = false, length = 11)
private String cpf;
#Column(name = "full_name", nullable = false, length = 60)
private String fullName;
#Column(nullable = false)
private String birthdate;
#Column(name = "email", nullable = true, length = 30)
private String emailAddress;
#Column(name = "cellphone_number", nullable = true, length = 11)
private String cellphoneNumber;
#Embedded
private Address address;
}
Dentist.java
#Data
#Entity
#Table(name = "tb_dentists")
public class Dentist implements Serializable {
#Serial
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "dentist_id")
private UUID id;
#Column
private LocalDateTime registrationDate;
#Column(nullable = false, unique = true, length = 6)
private String croNumber;
#Embedded
private Person person;
}
DentistController.java
#PostMapping
public ResponseEntity<Object> saveDentist(#RequestBody #Valid Dentist dentistDto, Person person) {
if(dentistService.existsByCroNumber(dentistDto.getCroNumber())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("CONFLICT: CRO number is already in use!");
}
if(dentistService.existsByPerson_Cpf(person.getCpf())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("CONFLICT: CPF number is already in use!");
}
var dentistModel = new Dentist();
BeanUtils.copyProperties(dentistDto, dentistModel);
dentistModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(dentistService.save(dentistModel));
}
DentistService.java
public boolean existsByCroNumber(String croNumber) {
return dentistRepository.existsByCroNumber((croNumber));
}
public boolean existsByPerson_Cpf(String cpf) {
return dentistRepository.existsByCpf((cpf));
}
}
DentistRepository.java
#Repository
public interface DentistRepository extends JpaRepository<Dentist, UUID> {
boolean existsByCroNumber(String croNumber);
boolean existsByCpf(String cpf);
}
I'm trying to filter the query/code using existsBy and the CPF column of Person. Person is embedded in the Dentist entity. How can I can properly implement this code? I'm trying this as posted below but I'm getting anywhere.
Spring is returning this error for me
Caused by:
org.springframework.data.mapping.PropertyReferenceException: No
property 'cpf' found for type 'Dentist'
I posted just some part of my code, the query existsByCroNumber is working properly and the rest of the API is good too.
you should name your repo method existsByPersonCpf.
#Repository
public interface DentistRepository extends JpaRepository<Dentist, UUID> {
boolean existsByCroNumber(String croNumber);
boolean existsByPersonCpf(String cpf);
}
I have two tables\entities that are connected with a forging key.
#Entity
public class SwapEngineReport {
#Id
#Column(name = "FilePath")
private String filePath;
#Column(name = "FileName")
private String fileName;
#Column(name = "LastModifiedDate")
private LocalDate lastModifiedDate;
#Column(name = "LoadedDate")
private LocalDate loadedDate;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "SwapEngineReport2SwapEngineReportType", foreignKey = #ForeignKey(name =
"FK_SwapEngineReport_SwapEngineReportType"))
private SwapEngineReportType swapEngineReportType;
public SwapEngineReportType getSwapEngineReportType() {
return swapEngineReportType;
}
public void setSwapEngineReportType(SwapEngineReportType swapEngineReportType) {
this.swapEngineReportType = swapEngineReportType;
}
#Entity
public class SwapEngineReportType {
#Id
#Column(name = "Type")
private String type;
#Column(name = "Description")
private String description;
During the process stage, I am initiating the SEReport object and setting all the necessary values including the Type object.
#Override
public SwapEngineReport process(Resource resource) throws Exception {
SwapEngineReport swapEngineReport = new SwapEngineReport();
......
SwapEngineReportType type = new SwapEngineReportType();
if(inputReourceValue.equals("dailyex")){type.setType("DAILY_EX");}
if(inputReourceValue.equals("status")) {type.setType("STATUS");}
swapEngineReport.setSwapEngineReportType(type);
return swapEngineReport;
What I don’t understand is why the write method is not working.
This is the error message:
Bean property 'swapEngineReport2swapEngineReportType' is not readable
or has an invalid getter method: Does the return type of the getter
match the parameter type of the setter?
return new JdbcBatchItemWriterBuilder<SwapEngineReport>().beanMapped().dataSource(dataSource)
.sql(environment.getProperty("insertToSwapEngineReport")).build();
And SQL:
INSERT INTO SwapEngineReport
(filePath,fileName,lastModifiedDate,swapEngineReport2swapEngineReportType) VALUES
(:filePath,:fileName,:lastModifiedDate,:swapEngineReport2swapEngineReportType)
Can anyone, please assist me to understand what I am missing.
Thank you
(This question has a spanish version: Pregunta español StackOverflow)
Hello,
im creating a API-REST with springboot, hibernate ...
In one controller, im returning one entity, the point is, when i do this:
Empresa company= empresaManager.findById(2L);
return company;
returns exactly what i expect, (the object company has a list of students, and has only 2 vinculated).
But when instead of use a number, what i do is get the students, and afterwards, return the company of the students, the company that its returning me comes with 12 students (6 times repeated each student)
String token = request.getHeader("Authorization");
token = token.replace("Bearer ", "");
Usuario usuario = tokenManager.getUsuarioFromToken(token);
Long id = usuario.getEmpresa().getIdempresa();
Empresa empresaOriginal = empresaManager.findById(id);
return empresaOriginal;
Any chance you know why is happenning this ?
This is how should return the object company:
And this is how im actually getting it:
From here, to down, is what is asked in comments
This is my user entity :
#Entity
#Table(name = "usuario")
public class Usuario {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idusuario")
private Long idusuario;
#Column(name = "nombre", length = 30, nullable = false)
private String nombre;
#Column(name = "email", length = 80, nullable = false)
private String email;
#JsonIgnore
#Column(name = "contraseña", length = 300, nullable = false)
private String contraseña;
#JsonIgnore
#ManyToOne
#JoinColumn(foreignKey = #ForeignKey(name = "empresa_idempresa"), name = "empresa_idempresa")
private Empresa empresa;
#OneToMany(mappedBy = "usuario", orphanRemoval = true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Fichaje> fichajes;
public Usuario() {
}
public Empresa getEmpresa() {
return empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
}
This is my Company entity:
#Entity
#Table(name = "empresa")
public class Empresa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idempresa")
private Long idempresa;
#Column(name = "nombre", length = 100, nullable = false)
private String nombre;
#Column(name = "contacto", length = 300, nullable = false)
private String contacto;
#Column(name = "fecha_inicio_practicas", columnDefinition = "DATE")
private LocalDate inicioPracticas;
#Column(name = "direccion", length = 100)
private String direccion;
#Column(name = "foto_empresa")
private String fotoEmpresa;
#OneToMany(mappedBy = "empresa", orphanRemoval = true, cascade = CascadeType.ALL)
private List<EmpresaTieneDia> empresaTieneDias;
#OneToMany(mappedBy = "empresa", orphanRemoval = false, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Usuario> estudiantes;
public Empresa() {
}
public Long getIdempresa() {
return idempresa;
}
public void setIdempresa(Long idempresa) {
this.idempresa = idempresa;
}
public List<Usuario> getEstudiantes() {
return estudiantes;
}
public void setEstudiantes(List<Usuario> estudiantes) {
this.estudiantes = estudiantes;
}
}
This is the findById:
(Service or Manager)
public Empresa findById(Long id) {
return this.empresaRepository.findByIdempresa(id);
}
(Repository or DAO)
public interface EmpresaRepository extends CrudRepository<Empresa, Long> {
Empresa findByIdempresa(Long id);
}
SOLVED
I had to change my listo of users from a List<Usuario> to a Set<Usuario>.
Anyways, I understand why it fixes it using a Set (cause doesn't let duplicated values in it).
Anyways, if someone could try to explain my why in the first moment I'm having 6 times duplicated every item in the list i would apreciate it.
Thanks !! :D
I have a Production class and ProductionDetail entity class where Id of Production table is a foreignKey as production_id in ProductionDetail entity class so my both entity class with mapping has given bellow
Production Entity Class:
#Entity
#Table(name = "tbl_production")
#XmlRootElement
public class TblProduction implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "ID")
private String id;
#Column(name = "PRODUCTION_DATE")
#Temporal(TemporalType.DATE)
private Date productionDate;
#Column(name = "START_DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date startDatetime;
#Column(name = "END_DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date endDatetime;
#Size(max = 45)
#Column(name = "MACHINE_UUID")
private String machineUuid;
**Relation with Production Details Table**
#OneToMany(mappedBy = "production")
#XmlElement(name = "productionDetails")
private List<TblProductionDetail> productionDetailList;
#PrimaryKeyJoinColumn(name = "MACHINE_UUID", referencedColumnName = "UUID")
#ManyToOne(fetch = FetchType.LAZY)
private MstMachine mstMachine;
#XmlTransient
public MstMachine getMstMachine() {
return this.mstMachine;
}
}
Production Details Entity Class:
#Entity
#Table(name = "tbl_production_detail")
#XmlRootElement
public class TblProductionDetail implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "ID")
private String id;
#Size(max = 45)
#Column(name = "COMPONENT_ID")
private String componentId;
#Size(max = 45)
#Column(name = "PRODUCTION_ID")
private String productionId;
**Relation with Production Class**
#ManyToOne
#JoinColumn(name = "PRODUCTION_ID", referencedColumnName = "ID", insertable = false,
updatable = false)
private TblProduction production;
#Transient
public String componentCode;
#Transient
public String componentName;
#PrimaryKeyJoinColumn(name = "COMPONENT_ID", referencedColumnName = "ID")
#ManyToOne(fetch = FetchType.LAZY)
private MstComponent mstComponent;
#XmlTransient
public MstComponent getMstComponent() {
return this.mstComponent;
}
public void setMstComponent(MstComponent mstComponent) {
this.mstComponent = mstComponent;
}
}
ParentList Class:
public class TblProductionList {
private List<TblProduction> productionList;
public TblProductionList() {
productionList = new ArrayList<>();
}
public List<TblProduction> getTblProductions() {
return productionList;
}
public void setTblProductions(List<TblProduction> tblProductionList) {
this.productionList = tblProductionList;
}
}
BusinessLogic(DAO Class):
public TblProductionList getJson() {
TblProductionList response = new TblProductionList();
StringBuilder retrieveQuery = new StringBuilder();
retrieveQuery.append(" SELECT prod FROM TblProduction prod ");
retrieveQuery.append(" JOIN FETCH prod.productionDetailList ");
retrieveQuery.append(" WHERE prod.endDatetime IS NULL ");
retrieveQuery.append(" AND prod.machineUuid IS NOT NULL ");
retrieveQuery.append(" AND NOT EXISTS (SELECT tpt FROM
TblProductionThset tpt WHERE prod.id = tpt.productionId) ");
retrieveQuery.append(" AND EXISTS (SELECT mmfd FROM
MstMachineFileDef mmfd WHERE prod.machineUuid = mmfd.machineUuid
AND mmfd.hasThreshold = 1) ");
retrieveQuery.append(" ORDER BY prod.id ");
Query query =
entityManager.createQuery(retrieveQuery.toString());
List thresholdList = query.getResultList();
response.setTblProductions(thresholdList);
return response;
}
According to the database I am getting expected master child data like below
After designing this entity class I am expecting that I will get 3 master records where each record has 2 detail records. But I am getting 6 duplicate master records with 12 child records. Can anyone suggest to me please where is my code became wrong and why this situation raised? please check the JSON data that I am getting from API.
change your array list to hash set then records are not duplicate.