i have the following RESTfull method :
#RequestMapping(value = "/budgetLines",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public void create(#RequestBody BudgetLine budgetLine) {
System.out.println("Before Persisting in the repository " + budgetLine);
budgetLineRepository.save(budgetLine);
}
I'am consuming this method inside a web application, i checked using the network analysis tool (in the web developper tool of chrome) that the object sended is valid (all attribute except the id were set with a valid value), but then the object passed to the repository contains only null attributes.
here is an example body :
{
"Name":"testLabel",
"Label":"testName",
"AnnualBudget":9000
}
the class BudgetLine is defined as follows:
#Entity
#Table(name = "T_BUDGETLINE")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BudgetLine implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "label")
private String Label;
#Column(name = "name")
private String Name;
#Column(name = "annual_budget", precision=10, scale=2)
private BigDecimal AnnualBudget;
#OneToMany(mappedBy = "budgetLine")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Report> reportss = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return Label;
}
public void setLabel(String Label) {
this.Label = Label;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public BigDecimal getAnnualBudget() {
return AnnualBudget;
}
public void setAnnualBudget(BigDecimal AnnualBudget) {
this.AnnualBudget = AnnualBudget;
}
public Set<Report> getReportss() {
return reportss;
}
public void setReportss(Set<Report> Reports) {
this.reportss = Reports;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BudgetLine budgetLine = (BudgetLine) o;
if (id != null ? !id.equals(budgetLine.id) : budgetLine.id != null) return false;
return true;
}
#Override
public int hashCode() {
return (int) (id ^ (id >>> 32));
}
#Override
public String toString() {
return "BudgetLine{" +
"id=" + id +
", Label='" + Label + "'" +
", Name='" + Name + "'" +
", AnnualBudget='" + AnnualBudget + "'" +
'}';
}
public BudgetLine() {
}
}
Try with first letter in lowercase for parameters
{
"name":"testLabel",
"label":"testName",
"annualBudget":9000
}
Spring relies heavily on standard Java naming conventions, so I suggest you also follow them. In your example, you should name your class fields with lowercased first letter.
Related
I can’t set the discipline values for my semester, when I work out the controller, I get all the data I need, but I can’t connect them, can anyone tell me with an experienced eye what is the reason? I am getting this kind of error:
Request processing failed; nested exception is
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.kushnirmark.spring.project.entity.Discipline.id] by reflection for persistent property [com.kushnirmark.spring.project.entity.Discipline#id] : Higher mathematics
Here is my entity Semestr:
package com.kushnirmark.spring.project.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "semestr")
public class Semestr {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "duration")
private String duration;
#Column(name = "status")
private boolean status = true;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "semestr_discipline",
joinColumns = #JoinColumn(name = "id_semestr"),
inverseJoinColumns = #JoinColumn(name = "id_discipline")
)
private List<Discipline> disciplineList;
public void addDisciplineToSemester(Discipline discipline) {
if (disciplineList == null) {
disciplineList = new ArrayList<>();
}
disciplineList.add(discipline);
}
public Semestr() {
}
public Semestr(int id, String name, String duration, boolean status) {
this.id = id;
this.name = name;
this.duration = duration;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Discipline> getDisciplineList() {
return disciplineList;
}
public void setDisciplineList(List<Discipline> disciplineList) {
this.disciplineList = disciplineList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Semestr semestr = (Semestr) o;
if (id != semestr.id) return false;
if (status != semestr.status) return false;
if (name != null ? !name.equals(semestr.name) : semestr.name != null) return false;
return duration != null ? duration.equals(semestr.duration) : semestr.duration == null;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (duration != null ? duration.hashCode() : 0);
result = 31 * result + (status ? 1 : 0);
return result;
}
#Override
public String toString() {
return "Semestr{" +
"id=" + id +
", name='" + name + '\'' +
", duration='" + duration + '\'' +
", status=" + status +
'}';
}
}
Controller :
#RequestMapping("/saveNewSemester")
public String saveNewSemester(#ModelAttribute("semestr") Semestr semestr,
#RequestParam(name = "AllDiscipline") String[] AllDiscipline,
Model model) {
List<Integer> list = Arrays.stream(AllDiscipline).map(Integer::parseInt).collect(Collectors.toList());
List<Discipline> disciplineSemestrList = service.getDisciplineList(list);
semestr.setDisciplineList(disciplineSemestrList);
service.saveNewSemester(semestr);
return "redirect:/semestr";
}
Here is my entity Discipline :
package com.kushnirmark.spring.project.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "discipline")
public class Discipline {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "discipline")
private String discipline;
#Column(name = "status")
private boolean status = true;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "semestr_discipline",
joinColumns = #JoinColumn(name = "id_discipline"),
inverseJoinColumns = #JoinColumn(name = "id_semestr")
)
private List<Semestr> semestrList;
public void addSemesterToDiscipline(Semestr semestr) {
if (semestrList == null) {
semestrList = new ArrayList<>();
}
semestrList.add(semestr);
}
public Discipline() {
}
public Discipline(int id, String discipline, boolean status) {
this.id = id;
this.discipline = discipline;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiscipline() {
return discipline;
}
public void setDiscipline(String discipline) {
this.discipline = discipline;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Semestr> getSemestrList() {
return semestrList;
}
public void setSemestrList(List<Semestr> semestrList) {
this.semestrList = semestrList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Discipline that = (Discipline) o;
return id == that.id &&
status == that.status &&
Objects.equals(discipline, that.discipline);
}
#Override
public int hashCode() {
return Objects.hash(id, discipline, status);
}
#Override
public String toString() {
return "Discipline{" +
"id=" + id +
", discipline='" + discipline + '\'' +
", status=" + status +
'}';
}
}
Overview
I'm learning Angular Java and JHipster, and I'm trying to filter the Users by Role but im getting a infinity recursion.
this is my userRepository.java
#Query(value = "select user from User user inner join user.authorities authorities where authorities.name =:role")
List<User> findByRole(#Param("role") String role);
I trying to do a inner join between the user table and the user_authority table, im parsing the role like a String "ROLE_ADMIN"
Upadte
Found something in the model if i do this select user.login instead of select users don't get the recursion error, so I think is maybe cause in the model is calling itself several times.
I have a relationship 1:1 with a another entity called extendedUser (for save additional information) and in extendedUser i have another relationship with user called coordinator so I think the model is calling itself.
This is just a part of the recursion in the console:
2019-03-22 14:08:32.082 WARN 12044 --- [ XNIO-2 task-9] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain:["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]->com.gits.sigem.domain.ExtendedUser["usuario"]->com.gits.sigem.domain.User["extendedUser"]
And this is my DTO on extended user when i think I have the problem
/**
* A DTO for the ExtendedUser entity.
*/
public class ExtendedUserDTO extends UserDTO implements Serializable {
private final Logger log = LoggerFactory.getLogger(ExtendedUserDTO.class);
private Long id;
private String puesto;
private BigDecimal sueldo;
private LocalDate fechaIngreso;
private Long usuarioId;
//private Long coordinadorId;
private Set<Area> areas = new HashSet<>();
private Long coordinadorId;
private String coordinadorLogin;
private User coordinador;
private Set<Desarrollo> desarrollos = new HashSet<>();
public ExtendedUserDTO(){
}
public ExtendedUserDTO(User user){
super(user);
this.puesto = user.getExtendedUser().getPuesto();
this.sueldo = user.getExtendedUser().getSueldo();
this.fechaIngreso = user.getExtendedUser().getFechaIngreso();
this.id = user.getId();
this.usuarioId = user.getId();
this.coordinadorLogin = user.getExtendedUser().getCoordinador().getLogin();
this.coordinadorId = user.getExtendedUser().getCoordinador().getId();
this.coordinador = user.getExtendedUser().getCoordinador();
Hibernate.initialize(user.getExtendedUser().getAreas());
this.areas = user.getExtendedUser().getAreas();
Hibernate.initialize(user.getExtendedUser().getDesarrollos());
this.desarrollos = user.getExtendedUser().getDesarrollos();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPuesto() {
return puesto;
}
public void setPuesto(String puesto) {
this.puesto = puesto;
}
public BigDecimal getSueldo() {
return sueldo;
}
public void setSueldo(BigDecimal sueldo) {
this.sueldo = sueldo;
}
public LocalDate getFechaIngreso() {
return fechaIngreso;
}
public void setFechaIngreso(LocalDate fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
public Long getUsuarioId() {
return usuarioId;
}
public void setUsuarioId(Long userId) {
this.usuarioId = userId;
}
/* public void setCoordinadorId(Long userId) {
this.coordinadorId = userId;
}
public Long getCoordinadorId() {
return coordinadorId;
}*/
public User getCoordinador() {
return coordinador;
}
public void setCoordinador(User user) {
this.coordinador = user;
}
public Set<Area> getAreas() {
return areas;
}
public void setAreas(Set<Area> areas) {
this.areas = areas;
}
public Set<Desarrollo> getDesarrollos() {
return desarrollos;
}
public void setDesarrollos(Set<Desarrollo> desarrollos) {
this.desarrollos = desarrollos;
}
public Long getCoordinadorId() {
return coordinadorId;
}
public void setCoordinadorId(Long userId) {
this.coordinadorId = userId;
}
public String getCoordinadorLogin() {
return coordinadorLogin;
}
public void setCoordinadorLogin(String userLogin) {
this.coordinadorLogin = userLogin;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExtendedUserDTO extendedUserDTO = (ExtendedUserDTO) o;
if (extendedUserDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), extendedUserDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "ExtendedUserDTO{" +
"id=" + getId() +
", puesto='" + getPuesto() + "'" +
", sueldo=" + getSueldo() +
", fechaIngreso='" + getFechaIngreso() + "'" +
", usuario=" + getUsuarioId() +
", coordinador='" + getCoordinadorLogin() + "'" +
"}";
}
}
Notes
I'm really new on Angular, Java, and Jhipster.
Please if I missed something important, let me know on the comment
and I will added to the question.
Im just trying to get only the ADMIN users so if you have a better
way I really would like to know
I am trying to create two entities which have many-to-many relation between them. First entity is Person with PID as primary key, second is Serie with SID as primary key. In database there is a table TJV_5_SERIE_2_PERSON, which represents many to many relationship between these entities.
tables in database
The problem is when I retrieve any entity, Collection annotated with #ManyToMany is always empty. So I assume I've messed up something in my code that explains why my many-to-many relation doesn't work.
I retrieve these two entities by generating (in Netbeans 9.0) 'Restful Web Services from Entity classes'. This way I can use these services to retrieve all attributes succesfully, except Collection with #ManyToMany annotation is always empty.
Any idea why it is not woking appreciated. It is first time trying this, so pardon me for any dumm mistakes.
Person class:
#Entity
#Table(name = "TJV_5_PERSON")
#XmlRootElement
public class Person implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PID")
private Integer id;
#Column(name = "PNAME")
private String name;
#ManyToMany()
#JoinTable(
name = "TJV_5_SERIE_2_PERSON",
joinColumns = #JoinColumn(name = "PID", referencedColumnName = "PID"),
inverseJoinColumns = #JoinColumn(name = "SID", referencedColumnName = "SID")
)
// always empty
private Collection<Serie> favourites = new ArrayList<Serie>();
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public Collection<Serie> getFavourites() {
return favourites;
}
public void setFavourites(Collection<Serie> favourites) {
this.favourites = favourites;
}
#Override
public int hashCode() {
int hash = 5;
hash = 31 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Person{" + "id=" + id + ", name=" + name + ", favourites=" + favourites + '}';
}
}
Serie class:
#Entity
#Table(name = "TJV_5_SERIE")
#XmlRootElement
public class Serie implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SID")
private Integer id;
#Column(name = "STITLE")
private String title;
// always empty
#ManyToMany(mappedBy = "favourites")
private Collection<Person> fans = new ArrayList<Person>();
public Serie() {
}
public Serie(Integer id, String title) {
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#XmlTransient
public Collection<Person> getFans() {
return fans;
}
public void setFans(Collection<Person> fans) {
this.fans = fans;
}
#Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Serie other = (Serie) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Serie{" + "id=" + id + ", title=" + title + ", fans=" + fans + '}';
}
}
I am not 100% sure, but you may not retrieving any results beacuse of #XMLTransiet annotation above the Serie.class method
#XmlTransient
public Collection<Person> getFans() {
return fans;
}
Try to look in documentation https://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlTransient.html or in connected posts Hide an entity variable from xml message - #XmlTransient not working
The other issue is cascading data between two corresponding #ManyToMany tables. It means that you have intersection and the data appears in this table automatically when you use some type of cascade but you need send a POST request. It means in your service class layer you can create a method responsible for creating Person and assign a Serie to this Person object which is a foreign key. The article about cascading is here :) https://vladmihalcea.com/a-beginners-guide-to-jpa-and-hibernate-cascade-types/
I am beginner using java and spring jpa (expecially Jhipster). I want to create object in object like this :
But I always get like this :
property buildingsDTO always empty, this is my code, please correct my code in order I get like first picture.
location.java (Domain)
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "content_location", nullable = false)
private String content_location;
#OneToMany(mappedBy = "location")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_location() {
return content_location;
}
public Location content_location(String content_location) {
this.content_location = content_location;
return this;
}
public void setContent_location(String content_location) {
this.content_location = content_location;
}
public Set<Building> getBuildings() {
return buildings;
}
public Location buildings(Set<Building> buildings) {
this.buildings = buildings;
return this;
}
public Location addBuilding(Building building) {
this.buildings.add(building);
building.setLocation(this);
return this;
}
public Location removeBuilding(Building building) {
this.buildings.remove(building);
building.setLocation(null);
return this;
}
public void setBuildings(Set<Building> buildings) {
this.buildings = buildings;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Location location = (Location) o;
if (location.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), location.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Location{" +
"id=" + getId() +
", content_location='" + getContent_location() + "'" +
"}";
}}
locationDTO.java
public class LocationDTO implements Serializable {
private Long id;
#NotNull
private String content_location;
private Set<BuildingDTO> buildings = new HashSet<>();
public Set<BuildingDTO> getBuildingsDTO() {
return buildings;
}
public void setBuildingsDTO(Set<BuildingDTO> buildings) {
this.buildings = buildings;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_location() {
return content_location;
}
public void setContent_location(String content_location) {
this.content_location = content_location;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LocationDTO locationDTO = (LocationDTO) o;
if(locationDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), locationDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "LocationDTO{" +
"id=" + getId() +
", content_location='" + getContent_location() + "'" +
"}";
}}
locationMapper.java
public interface LocationMapper extends EntityMapper <LocationDTO, Location> {
#Mapping(target = "buildings", ignore = true)
Location toEntity(LocationDTO locationDTO);
default Location fromId(Long id) {
if (id == null) {
return null;
}
Location location = new Location();
location.setId(id);
return location;
}}
buildingDTO.java
public class BuildingDTO implements Serializable {
private Long id;
#NotNull
private String content_building;
private Long locationId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent_building() {
return content_building;
}
public void setContent_building(String content_building) {
this.content_building = content_building;
}
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BuildingDTO buildingDTO = (BuildingDTO) o;
if(buildingDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), buildingDTO.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "BuildingDTO{" +
"id=" + getId() +
", content_building='" + getContent_building() + "'" +
"}";
}}
please anyone help me.
thanks.
By default jHipster will mark any OneToMany entity relationships as #JsonIgnore so that the Set of buildings is not returned in the JSON:
#OneToMany(mappedBy = "location")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
If you want this to show up in the JSON then you should remove that annotation and also mark it with an eager loading strategy so that the set of buildings are loaded as you expect:
#OneToMany(mappedBy = "location", fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Building> buildings = new HashSet<>();
I have a table, and I want to change state field of mapped table from 1 to 0 when I press delete button. Here is the logic.
It is my mapped table
#Entity
#Table(name = "POSITION_ACCOUNT")
public class PositionAccount {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID", columnDefinition = "NUMERIC(15, 0)",unique = true,nullable = false)
private Long id;
public Long getId() {
return id;
}
#Column(name = "ACCT_NUMBER")
private String accountNumber;
public String getAccountNumber() { return accountNumber; }
#Column(name = "ACCT_NAME")
private String accountName;
public String getAccountName() {
return accountName;
}
#Column(name = "CURRENCY_CODE")
private String currencyCode;
public String getCurrencyCode() {
return currencyCode;
}
#Column(name = "BALANCE")
private BigDecimal balance = new BigDecimal("0");
public BigDecimal getBalance() {
return balance;
}
#Column(name = "ACCT_TYPE")
private String accountType;
public String getAccountType() { return accountType; }
#Column(name = "STATE")
private int state = 1;
public int getState() {
return state;
}
public void setId(Long id) {
this.id = id;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public void setState(int state) {
this.state = state;
}
public void setAccountType(String accountType) { this.accountType = accountType; }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PositionAccount that = (PositionAccount) o;
return !(id != null ? !id.equals(that.id) : that.id != null);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public String toString() {
return "PositionAccount{" +
"id=" + id +
", accountNumber='" + accountNumber + '\'' +
", accountName='" + accountName + '\'' +
", currencyCode='" + currencyCode + '\'' +
", balance=" + balance +
", state=" + state +
'}';
}
}
Here is my #ActionMethod
#Inject
private LoroNostroService service;
#Inject
private LoroNostroModel model;
#ActionMethod(ACTION_DELETE_ACCOUNT)
public void deleteAccount() {
PositionAccount account = tv_loro_nostro_accounts.getSelectionModel().getSelectedItem();
DeleteAccount input = new DeleteAccount();
input.setAccountId(account.getId());
input.setType(account.getAccountType());
input.setAccNum(account.getAccountNumber());
input.setAccName(account.getAccountName());
input.setCurrency(account.getCurrencyCode());
input.setBalance(account.getBalance());
input.setCurState(0);
service.deleteAccount(input, context.getTaskView(), result -> {
model.getAccounts().addAll(result.getAccount());
tv_loro_nostro_accounts.getSelectionModel().selectFirst();
});
}
where tv_loro_nostro_accounts is TableView from which I make a selection. DeleteAccount class is a class where I define all fields of my table with getters and setters. service.deleteAccount after some manipulations goes here:
#Path("deleteAccount")
#POST
public DeleteAccount deleteAccount(DeleteAccount model){
try {
model = operationService.execute(model,(result, userDetails) -> {
PositionAccount a = new PositionAccount();
a.setAccountType(result.getType());
a.setAccountNumber(result.getAccNum());
a.setAccountName(result.getAccName());
a.setCurrencyCode(result.getCurrency());
a.setState(0);
service.deleteAccount(a);
result.setState(OperationState.DONE);
return result;
});
}catch (AdcException e) {
logger.error("X: ", e);
model.setState(OperationState.ERROR);
model.setErrorText(e.getLocalizedMessage(model.getLocale()));
} catch (Exception e) {
logger.error("X: ", e);
model.setState(OperationState.ERROR);
model.setErrorText(e.getLocalizedMessage());
}
return model;
}
where service.deleteAccount is
public void deleteAccount(PositionAccount account){
repository.deleteAccount(account);
}
and repository.deleteAccount is
public void deleteAccount(PositionAccount account){
em.merge(account);
em.refresh(account);
}
When I run above, I receive error
Entity not managed; nested exception is java.lang.IllaegalArgumentException: Entity not managed
Please hrlp to fix above.
merge returnes the managed entity instance, so to make this not to throw exception do:
account = em.merge(account);
em.refresh(account);
However, refresh will overwrite all the changes, so it is not needed here. Your method should look like:
public void deleteAccount(PositionAccount account) {
em.merge(account);
}