I have two tables
tbl_user_info
tbl_user_auth
I am trying to save data in both the tables sequentially but data is getting stored in first table and throwing me error as below :
{
"timestamp": "2020-06-15T11:17:06.540+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/user/register"
}
Entity classes are as follows :
UserAccount
#Entityd
#Table(name = "tbl_user_info")
public class UserAccount {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
#Column(name = "mobile_number")
private String mobileNumber;
#Column(name = "password")
private String password;
#Column(name = "token")
private String token;
#Column(name = "admin")
private Integer admin;
#Column(name = "country_code")
private String countryCode;
#Column(name = "serial_number")
private String serialNumber;
protected UserAccount() {
}
public UserAccount(Integer id, String name, String email, String mobileNumber, String password, String token, Integer admin, String countryCode, String serialNumber) {
this.id = id;
this.name = name;
this.email = email;
this.mobileNumber = mobileNumber;
this.password = password;
this.token = token;
this.admin = admin;
this.countryCode = countryCode;
this.serialNumber = serialNumber;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Integer getAdmin() {
return admin;
}
public void setAdmin(Integer admin) {
this.admin = admin;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserAccount that = (UserAccount) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(email, that.email) &&
Objects.equals(mobileNumber, that.mobileNumber) &&
Objects.equals(password, that.password) &&
Objects.equals(token, that.token) &&
Objects.equals(admin, that.admin) &&
Objects.equals(countryCode, that.countryCode) &&
Objects.equals(serialNumber, that.serialNumber);
}
#Override
public int hashCode() {
return Objects.hash(id, name, email, mobileNumber, password, token, admin, countryCode);
}
#Override
public String toString() {
return "UserAccount{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", mobileNumber='" + mobileNumber + '\'' +
", password='" + password + '\'' +
", token='" + token + '\'' +
", admin=" + admin +
", countryCode='" + countryCode + '\'' +
", serialNumber='" + serialNumber + '\'' +
'}';
}
}
UserAuthInfo
#Entity
#Table(name = "tbl_user_auth")
public class UserAuthInfo implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "client_id")
private String clientId;
#Column(name = "user_id")
private Integer userId;
#Column(name = "code")
private String code;
#Column(name = "access_token")
private String accessToken;
#Column(name = "refresh_token")
private String refreshToken;
#Column(name = "expires_in")
private Integer expiresIn;
#Column(name = "modified_datetime")
private String datetime;
public UserAuthInfo() {
}
public UserAuthInfo(Integer id, String clientId, Integer userId, String code, String accessToken, String refreshToken, Integer expiresIn, String datetime) {
this.id = id;
this.clientId = clientId;
this.userId = userId;
this.code = code;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.expiresIn = expiresIn;
this.datetime = datetime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public Integer getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserAuthInfo that = (UserAuthInfo) o;
return Objects.equals(id, that.id) &&
Objects.equals(clientId, that.clientId) &&
Objects.equals(userId, that.userId) &&
Objects.equals(code, that.code) &&
Objects.equals(accessToken, that.accessToken) &&
Objects.equals(refreshToken, that.refreshToken) &&
Objects.equals(expiresIn, that.expiresIn) &&
Objects.equals(datetime, that.datetime);
}
#Override
public int hashCode() {
return Objects.hash(id, clientId, userId, code, accessToken, refreshToken, expiresIn, datetime);
}
#Override
public String toString() {
return "UserAuthInfo{" +
"id=" + id +
", clientId='" + clientId + '\'' +
", userId=" + userId +
", code='" + code + '\'' +
", accessToken='" + accessToken + '\'' +
", refreshToken='" + refreshToken + '\'' +
", expiresIn=" + expiresIn +
", datetime=" + datetime +
'}';
}
}
Controller :
#PostMapping("register") // Needed parameter : All except id and token
public AuthResponse registerUser(#RequestBody UserAccount userAccount) throws NoSuchAlgorithmException {
if (userAccount == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Request Body can not be null");
jsonResponse = new JSONResponse();
if (!userAccountService.isEmailPresent(userAccount.getEmail())){
userAccount.setPassword(DigestUtils.md5Hex(userAccount.getPassword()));
return userAccountService.registerUser(userAccount);
}
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"Email ID Already Exists");
}
Service :
public AuthResponse registerUser(UserAccount userAccount) throws NoSuchAlgorithmException {
UserAccount ua = userAccountRepository.save(userAccount);
String token = tokenService.createToken((ua.getId()));
//Saving the user id and newly created token in tbl_token_info
ua.setToken(token);
UserAccount ua1 = userAccountRepository.save(ua);
UserAuthInfo userAuthInfo = new UserAuthInfo();
userAuthInfo.setClientId(UtilityMethods.clientId);
userAuthInfo.setUserId(ua.getId());
String code = UtilityMethods.getCode(userAccount.getEmail(), userAccount.getPassword());
userAuthInfo.setCode(code);
String accessToken = UtilityMethods.getAccessToken(code);
String refreshToken = UtilityMethods.getRefreshToken(code);
userAuthInfo.setAccessToken(accessToken);
userAuthInfo.setRefreshToken(refreshToken);
userAuthInfo.setExpiresIn(3600);
userAuthInfo = userAuthService.saveUserAuth(userAuthInfo);
AuthResponse authResponse = new AuthResponse();
authResponse.setAccessToken(userAuthInfo.getAccessToken());
authResponse.setRefreshToken(userAuthInfo.getRefreshToken());
authResponse.setExpiresIn(60);
authResponse.setCreatedDateTime(UtilityMethods.getCurrentDateTime());
return authResponse;
}
Please guide what is wrong.
you must use relations between tables:
#OneToMany for 1-N composition relation in tables.
#Embedded for 1-1 relations
#ManyToOne for N-1 association relations in tables.
Don´t use bidirectional relations. Always unidirectional.
if you don´t use this, the mapping of the database could be wrong.
Related
I created a small application in Spring Tool suite 4. I checked my code hundreds of times but didn't find any error. When application is executed it says:
"The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak."
My Code
Bootstrap
...
#Component
public class BootStrapData implements CommandLineRunner {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
private final PublisherRepository publisherRepository;
public BootStrapData(AuthorRepository authorRepository, BookRepository bookRepository, PublisherRepository publisherRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
this.publisherRepository = publisherRepository;
}
#Override
public void run(String... args) throws Exception {
System.out.println("Started in Bootstrap");
Publisher publisher = new Publisher();
publisher.setName("SFG Publishing");
publisher.setCity("St Petersburg");
publisher.setState("FL");
publisherRepository.save(publisher);
System.out.println("Publisher Count: " + publisherRepository.count());
Author eric = new Author("Eric", "Evans");
Book ddd = new Book("Domain Driven Design", "123123");
eric.getBooks().add(ddd);
ddd.getAuthors().add(eric);
ddd.setPublisher(publisher);
publisher.getBooks().add(ddd);
authorRepository.save(eric);
bookRepository.save(ddd);
publisherRepository.save(publisher);
Author rod = new Author("Rod", "Johnson");
Book noEJB = new Book("J2EE Development without EJB", "3939459459");
rod.getBooks().add(noEJB);
noEJB.getAuthors().add(rod);
noEJB.setPublisher(publisher);
publisher.getBooks().add(noEJB);
authorRepository.save(rod);
bookRepository.save(noEJB);
publisherRepository.save(publisher);
System.out.println("Number of Books: " + bookRepository.count());
System.out.println("Publisher Number of Books: " + publisher.getBooks().size());
}
}
Entity
...
#Entity
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String isbn;
#ManyToOne
private Publisher publisher;
#ManyToMany
#JoinTable(name = "author_book", joinColumns = #JoinColumn(name = "book_id"),
inverseJoinColumns = #JoinColumn(name = "author_id"))
private Set<Author> authors = new HashSet<>();
public Book() {
}
public Book(String title, String isbn) {
this.title = title;
this.isbn = isbn;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", isbn='" + isbn + '\'' +
", authors=" + authors +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return id != null ? id.equals(book.id) : book.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
...
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
#ManyToMany(mappedBy = "authors")
private Set<Book> books = new HashSet<>();
public Author() {
}
public Author(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
#Override
public String toString() {
return "Author{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", books=" + books +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Author author = (Author) o;
return id != null ? id.equals(author.id) : author.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
...
#Entity
public class Publisher {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String addressLine1;
private String city;
private String state;
private String zip;
#OneToMany
#JoinColumn(name = "publisher_id")
private Set<Book> books = new HashSet<>();
public Publisher() {
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
#Override
public String toString() {
return "Publisher{" +
"id=" + id +
", name='" + name + '\'' +
", addressLine1='" + addressLine1 + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
", zip='" + zip + '\'' +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Publisher publisher = (Publisher) o;
return id != null ? id.equals(publisher.id) : publisher.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}...
repositories
public interface AuthorRepository extends CrudRepository<Author, Long>{
}
public interface BookRepository extends CrudRepository<Book, Long>{
}
public interface PublisherRepository extends CrudRepository<Publisher, Long>{
}
package com.hashedin.employeemanagementsystem.entities;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Data
#Table(name="employee")
#Entity(name="User")
public class User{
public User(){
this.individual = new Individual();
this.workExperience = null;
this.experienceInMonths = null;
this.jobRole = null;
this.primaryContact = null;
this.secondaryContact = null;
this.employeeID = null;
this.joiningDate = null;
this.employeeCategory = null;
this.exitDate = null;
this.educationDetails = null;
}
#Id
//Employee 4 digit ID
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="employee_id")
private Long empID;
//employee ID Code
#Column(name = "employee_code_id")
private String employeeID;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="first_name", column = #Column(name="employee_first_name")),
#AttributeOverride(name="last_name", column = #Column(name="employee_last_name")),
#AttributeOverride(name="email", column = #Column(name="employee_email")),
#AttributeOverride(name="phone", column = #Column(name="employee_phone")),
})
private Individual individual;
//Primary and Secondary Contacts
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "email", column = #Column(name = "primary_contact_email")),
#AttributeOverride(name = "Individual.first_name", column = #Column(name = "primary_contact_first_name")),
#AttributeOverride(name = "last_name", column = #Column(name = "primary_contact_last_name")),
#AttributeOverride(name = "phone", column = #Column(name = "primary_contact_phone"))
})
private Individual primaryContact;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="email", column = #Column(name="secondary_contact_email")),
#AttributeOverride(name="first_name", column=#Column(name="secondary_contact_first_name")),
#AttributeOverride(name="last_name", column=#Column(name="secondary_contact_last_name")),
#AttributeOverride(name="phone", column=#Column(name="secondary_contact_phone"))
})
private Individual secondaryContact;
//jobRole
#Embedded
private JobRole jobRole;
//joining date and exit date (mentioned for Fixed Employees / probation period)
#Column(name="joining_date")
private Date joiningDate;
#Column(name="exit_date")
private Date exitDate;
//category, experience and highest degree
#OneToOne(cascade = CascadeType.ALL)
private Education educationDetails;
#Column(name="employee_category")
private String employeeCategory;
#Column(name="total_experience")
private Integer experienceInMonths;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name="employee_id")
private List<Employment> workExperience;
public User(String firstName, String lastName, Location location, String email, String phone, String employeeID, Individual primaryContact, Individual secondaryContact, Date joiningDate, String employeeCategory, Date exitDate, Integer experience, Education educationDetails, JobRole jobRole, List<Employment> exp) {
this.individual = new Individual(firstName, lastName, location, email, phone);
this.workExperience = exp;
this.experienceInMonths = experience;
this.jobRole = jobRole;
this.primaryContact = primaryContact;
this.secondaryContact = secondaryContact;
this.employeeID = employeeID;
this.joiningDate = joiningDate;
this.employeeCategory = employeeCategory;
this.exitDate = exitDate;
this.educationDetails = educationDetails;
}
public Individual getIndividual() {
return individual;
}
public void setIndividual(Individual individual) {
this.individual = individual;
}
public Long getEmpID() {
return empID;
}
public void setEmpID(Long empID) {
this.empID = empID;
}
public Integer getExperienceInMonths() {
return experienceInMonths;
}
public void setExperienceInMonths(Integer experienceInMonths) {
this.experienceInMonths = experienceInMonths;
}
public List<Employment> getWorkExperience() {
return workExperience;
}
public void setWorkExperience(List<Employment> workExperience) {
this.workExperience = workExperience;
}
public JobRole getJobRole() {
return jobRole;
}
public void setJobRole(JobRole jobRole) {
this.jobRole = jobRole;
}
public Education getEducationDetails() {
return educationDetails;
}
public void setEducationDetails(Education educationDetails) {
this.educationDetails = educationDetails;
}
public Integer getExperience() {
return experienceInMonths;
}
public void setExperience(Integer experience) {
this.experienceInMonths = experience;
}
public Date getExitDate() {
return exitDate;
}
public void setExitDate(Date exitDate) {
this.exitDate = exitDate;
}
public String getEmployeeCategory() {
return employeeCategory;
}
public void setEmployeeCategory(String employeeCategory) {
this.employeeCategory = employeeCategory;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID) {
this.employeeID = employeeID;
}
public Date getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(Date joiningDate) {
this.joiningDate = joiningDate;
}
public Individual getPrimaryContact() {
return primaryContact;
}
public void setPrimaryContact(Individual primaryContact) {
this.primaryContact = primaryContact;
}
public Individual getSecondaryContact() {
return secondaryContact;
}
public void setSecondaryContact(Individual secondaryContact) {
this.secondaryContact = secondaryContact;
}
#Override
public String toString() {
return "User{" +
"empID=" + empID +
", employeeID='" + employeeID + '\'' +
", individual=" + individual.toString() +
", primaryContact=" + primaryContact +
", secondaryContact=" + secondaryContact +
", jobRole=" + jobRole +
", joiningDate=" + joiningDate +
", exitDate=" + exitDate +
", educationDetails=" + educationDetails +
", employeeCategory='" + employeeCategory + '\'' +
", experienceInMonths=" + experienceInMonths +
", workExperience=" + workExperience +
'}';
}
}
Still getting this error, please help:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boo
t/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceU
nit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.hashedin.emplo
yeemanagementsystem.entities.User column: email (should be mapped with insert="false" update="false")
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5
.3.5.jar:5.3.5]
This is what my Individual class looks like:
package com.hashedin.employeemanagementsystem.entities;
import javax.persistence.*;
import java.lang.annotation.Target;
#Embeddable
public class Individual {
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Embedded
private Location location;
#Column(name="email")
private String email;
#Column(name="phone")
private String phone;
public Individual(){
this.firstName="";
this.lastName="";
this.location=null;
this.email=null;
this.phone=null;
}
public Individual(String firstName, String lastName, Location location, String email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.location = location;
this.email = email;
this.phone = phone;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public String toString() {
return "Individual{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", location=" + location +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
I want to implement an additive filter on a table of records (Student information). This is the breakdown of the problem
There are three parameters to filter with.
The method returns count, the result, the pageSize and pageNumber.
The table changes with change in the filter parameter.
I am new to criteriaBuilder in JPA. Have managed to write some codes with some information i read online about it. I hope someone help me with it.
The kind of search was implemented on this site : www.hdpopcorns.co
This is my code;
public Page<Student> findStudentByParam(FindStudentDTO findStudentDTO, Pageable pageable) {
String studentName = findStudentDTO.getStudentName();
Long levelId = findStudentDTO.getLevel();
Long sclassId = findStudentDTO.getSclass();
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<FindStudentDTO> studentQuery = cb.createQuery(FindStudentDTO.class);
Root<Student> studentRoot = studentQuery.from(Student.class);
Root<SClass> classRoot = studentQuery.from(SClass.class);
List<Predicate> filterPredicates = new ArrayList<>();
if((studentName != null && !studentName.isEmpty()) && ((levelId == null) && (sclassId == null))){
System.out.println("Ths is level 1");
filterPredicates.add(
cb.or(
cb.like(cb.lower(studentRoot.get("firstName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("middleName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("lastName")),"%" + studentName + "%")
)
);
}else if(levelId != null && ((studentName == null && studentName.isEmpty()) && sclassId == null)) {
filterPredicates.add(cb.equal(studentRoot.join("level").get("id"),findStudentDTO.getLevel()));
log.info("I am here");
}else if(sclassId != null && ((studentName == null && studentName.isEmpty()) && levelId == null)) {
System.out.println("2");
filterPredicates.add(cb.equal(studentRoot.join("sClass").get("id"),findStudentDTO.getSclass()));
}else if((levelId != null && sclassId != null) && ((studentName == null && studentName.isEmpty()))){
System.out.println("3");
filterPredicates.add(cb.and(
cb.equal(studentRoot.join("level").get("id"),levelId),
cb.equal(studentRoot.join("sClass").get("id"),sclassId)
));
}else if(((levelId != null) && (studentName != null)) && (sclassId == null)){
System.out.println("This is level 4");
filterPredicates.add(cb.and(
cb.equal(studentRoot.join("level").get("id"),levelId),
cb.or(
cb.like(cb.lower(studentRoot.get("firstName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("middleName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("lastName")),"%" + studentName + "%")
)
));
}else if(((sclassId != null) && (!studentName.isEmpty() && studentName != null)) && levelId == null){
System.out.println("5");
filterPredicates.add(cb.and(
cb.equal(studentRoot.get("sClass").get("id"),sclassId),
cb.or(
cb.like(cb.lower(studentRoot.get("firstName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("middleName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("lastName")),"%" + studentName + "%")
)
));
}else if((studentName != null && !studentName.isEmpty()) && (sclassId != null) && (levelId != null)){
System.out.println("6");
filterPredicates.add(cb.and(
cb.or(
cb.like(cb.lower(studentRoot.get("firstName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("middleName")),"%" + studentName + "%"),
cb.like(cb.lower(studentRoot.get("lastName")),"%" + studentName + "%")
),
cb.equal(studentRoot.join("sClass").get("id"),sclassId),
cb.equal(studentRoot.join("level").get("id"),levelId)
));
}
List<Predicate> predicateList = filterPredicates.stream().distinct().collect(Collectors.toList());
System.out.println("filtered records is: "+filterPredicates.size());
studentQuery.select(cb.construct(FindStudentDTO.class,studentRoot.get("id"),
studentRoot.get("firstName"),
studentRoot.get("lastName"),
studentRoot.get("gender"),
studentRoot.join("level").get("name"),
studentRoot.join("sClass").get("name"),
studentRoot.join("level").get("id"),
studentRoot.join("sClass").get("id")
))
.where(cb.and(predicateList.toArray(new Predicate[0])));
System.out.println("This is the size of the predicate" + filterPredicates.size());
TypedQuery q = emf.createQuery(studentQuery.distinct(true));
q.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
q.setMaxResults(pageable.getPageSize());
List<Student> list = (List) q.getResultList().stream().distinct().collect(Collectors.toList());
Collection result = (Collection) new LinkedHashSet(q.getResultList()).stream().distinct().collect(Collectors.toList());
return new PageImpl<>((List<Student>) result,pageable,getAllCount(studentName,levelId,sclassId));
}
private Long getAllCount(String studentName, Long levelId, Long
sClassId){
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery query = cb.createQuery(Long.class);
Root longRoot = query.from(Student.class);
List<Predicate> filterPredicates = new ArrayList<>();
if(studentName != null && !studentName.isEmpty()){
filterPredicates.add(cb.or(
cb.like(cb.lower(longRoot.get("firstName")),"%" + studentName + "%"),
cb.like(cb.lower(longRoot.get("middleName")),"%" + studentName + "%"),
cb.like(cb.lower(longRoot.get("lastName")),"%" + studentName + "%")
));
}else if(levelId != null) {
filterPredicates.add(cb.equal(longRoot.get("level").get("id"),levelId));
}else if(sClassId != null) {
filterPredicates.add(cb.equal(longRoot.get("sClass").get("id"),sClassId));
}
query.select(cb.count(longRoot)).where(cb.and
(filterPredicates.toArray(new Predicate[0])));
System.out.println("Count query" + emf.createQuery(query).getResultList());
return (Long) emf.createQuery(query).getSingleResult();
}
}
These are the models:
#Entity
#Table(name = "Class")
public class SClass extends AbstractSchoolEntity{
#NotBlank
private String name;
#NotEmpty(message = "description must not be empty")
private String description;
#JoinColumn(name = "level_id")
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
private Level level;
#OneToOne
private Period period;
#JsonIgnore
#OneToMany(mappedBy = "sClass",
cascade = CascadeType.ALL)
private List<Student> students;
#JsonIgnore
#OneToMany(mappedBy = "sClass",
cascade = CascadeType.ALL)
private List<ClassTeacher> teachers;
public SClass() {
}
public SClass(String name, String description, Level level) {
this.name = name;
this.description = description;
this.level = level;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public Period getPeriod() {
return period;
}
public void setPeriod(Period period) {
this.period = period;
}
public List<ClassTeacher> getTeachers() {
return teachers;
}
public void setTeachers(List<ClassTeacher> teachers) {
this.teachers = teachers;
}
public void addTeacher(ClassTeacher classTeacher) {
if(teachers == null)
teachers = new ArrayList<ClassTeacher>();
teachers.add(classTeacher);
classTeacher.setsClass(this);
}
#Override
public List<String> getDefaultSearchFields() {
return Arrays.asList("period.name");
}
#Override
public String toString() {
return "SClass{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", level=" + level +
", period=" + period +
", students=" + students +
", teachers=" + teachers +
'}';
}
}
#Entity
public class Level extends AbstractSchoolEntity{
#NotNull(message = "name must not be empty")
#Size(min=2, max=30)
private String name;
private int ordinal;
#JsonIgnore
#OneToMany(mappedBy = "level",
cascade = CascadeType.ALL)
private List<Student> studentList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getOrdinal() {
return ordinal;
}
public void setOrdinal(int ordinal) {
this.ordinal = ordinal;
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
#Override
public String toString() {
return "Level{" +
"name='" + name + '\'' +
", ordinal=" + ordinal +
", studentList=" + studentList +
'}';
}
}
#SuppressWarnings("serial")
#Entity
public class Student extends AbstractSchoolEntity {
private String admissionNumber;
#NotNull
#Size(min=2, max=40)
private String firstName;
private String middleName;
#NotNull
#Size(min=2, max=40)
private String lastName;
private String gender;
private String religion;
#OneToOne
private Image passport;
private String email;
private String phoneNumber;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-mm-dd")
private Date dateOfBirth;
#OneToOne
private User user;
#JsonManagedReference
#ManyToMany
private List<Parent> parents;
#JsonManagedReference
#ManyToOne(fetch = FetchType.EAGER)
private Level level;
#JsonManagedReference
#ManyToMany
private List<Guardian> guardians;
#OneToOne(cascade = CascadeType.ALL)
private Address address;
#JsonManagedReference
#ManyToOne(fetch = FetchType.EAGER)
private SClass sClass;
public Student() {
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public String getAdmissionNumber() {
return admissionNumber;
}
public void setAdmissionNumber(String admissionNumber) {
this.admissionNumber = admissionNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getReligion() {
return religion;
}
public void setReligion(String religion) {
this.religion = religion;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public void addParent(Parent p) {
if(parents == null)
parents = new ArrayList<Parent>();
parents.add(p);
p.addStudent(this);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Guardian> getGuardians() {
return guardians;
}
public void setGuardians(List<Guardian> guardians) {
this.guardians = guardians;
}
public List<Parent> getParents() {
return parents;
}
public void setParents(List<Parent> parents) {
this.parents = parents;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Image getPassport() {
return passport;
}
public void setPassport(Image passport) {
this.passport = passport;
}
public SClass getsClass() {
return sClass;
}
public void setsClass(SClass sClass) {
this.sClass = sClass;
}
#Override
public List<String> getDefaultSearchFields() {
return Arrays.asList("admissionNumber","firstName","lastName");
}
#Override
public String toString() {
return "Student{" +
"admissionNumber='" + admissionNumber + '\'' +
", firstName='" + firstName + '\'' +
", middleName='" + middleName + '\'' +
", lastName='" + lastName + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
Thanks in advance
Ensure that the Student, Level and SClass entities are joined by the right #OneToMany/#ManyToMany annotations.
Since you are using JPA, I would suggest you take a look at QueryDSL to generate dynamic query predicates. You will need to first generate the Predicate classes for your entities. Once generated, these classes provide a great way of chaining predicates in a builder pattern.
There are very useful quick-start articles that you can find here and here.
HTH!
I'm using JHipster and I'm running the following curl command:
POST/api/gang-users
with body:
{
"role": "member",
"gang": "3",
"user": "1"
}
but I get the following error:
JSON parse error: Cannot construct instance of
com.getgreetapp.greetapp.domain.User (although at least one Creator
exists): no String-argument constructor/factory method to deserialize
from String value ('1'); nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of com.getgreetapp.greetapp.domain.User (although
at least one Creator exists): no String-argument constructor/factory
method to deserialize from String value ('1')\n at [Source:
(PushbackInputStream); line: 4, column: 10] (through reference chain:
com.getgreetapp.greetapp.domain.GangUser[\"user\"])
GangUserResource createGangUser
#PostMapping("/gang-users")
#Timed
public ResponseEntity<GangUser> createGangUser(#Valid #RequestBody GangUser gangUser) throws URISyntaxException {
log.debug("REST request to save GangUser : {}", gangUser);
if (gangUser.getId() != null) {
throw new BadRequestAlertException("A new gangUser cannot already have an ID", ENTITY_NAME, "idexists");
}
User user = userRepository.findById(gangUser.getUser());
GangUser result = gangUserRepository.save(gangUser);
return ResponseEntity.created(new URI("/api/gang-users/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
GangUser
package com.getgreetapp.greetapp.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A GangUser.
*/
#Entity
#Table(name = "gang_user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class GangUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "jhi_role", nullable = false)
private String role;
#ManyToOne
private Gang gang;
#ManyToOne
private User user;
public GangUser() {
}
public GangUser(String role, Gang gang, User user)
{
this.role = role;
this.gang = gang;
this.user = user;
}
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRole() {
return role;
}
public GangUser role(String role) {
this.role = role;
return this;
}
public void setRole(String role) {
this.role = role;
}
public Gang getGang() {
return gang;
}
public GangUser gang(Gang gang) {
this.gang = gang;
return this;
}
public void setGang(Gang gang) {
this.gang = gang;
}
public User getUser() {
return user;
}
public GangUser user(User user) {
this.user = user;
return this;
}
public void setUser(User user) {
this.user = user;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GangUser gangUser = (GangUser) o;
if (gangUser.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), gangUser.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "GangUser{" +
"id=" + getId() +
", role='" + getRole() + "'" +
"}";
}
}
User
package com.getgreetapp.greetapp.domain;
import com.getgreetapp.greetapp.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.validation.constraints.Email;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.time.Instant;
/**
* A user.
*/
#Entity
#Table(name = "jhi_user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Pattern(regexp = Constants.LOGIN_REGEX)
#Size(min = 1, max = 50)
#Column(length = 50, unique = true, nullable = false)
private String login;
#JsonIgnore
#NotNull
#Size(min = 60, max = 60)
#Column(name = "password_hash", length = 60, nullable = false)
private String password;
#Size(max = 50)
#Column(name = "first_name", length = 50)
private String firstName;
#Size(max = 50)
#Column(name = "last_name", length = 50)
private String lastName;
#Email
#Size(min = 5, max = 254)
#Column(length = 254, unique = true)
private String email;
#NotNull
#Column(nullable = false)
private boolean activated = false;
#Size(min = 2, max = 6)
#Column(name = "lang_key", length = 6)
private String langKey;
#Size(max = 256)
#Column(name = "image_url", length = 256)
private String imageUrl;
#Size(max = 20)
#Column(name = "activation_key", length = 20)
#JsonIgnore
private String activationKey;
#Size(max = 20)
#Column(name = "reset_key", length = 20)
#JsonIgnore
private String resetKey;
#Column(name = "reset_date")
private Instant resetDate = null;
#JsonIgnore
#ManyToMany
#JoinTable(
name = "jhi_user_authority",
joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "authority_name", referencedColumnName = "name")})
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public User() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
Gang
package com.getgreetapp.greetapp.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
/**
* A Gang.
*/
#Entity
#Table(name = "gang")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Gang implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "name", nullable = false)
private String name;
#NotNull
#Column(name = "description", nullable = false)
private String description;
#NotNull
#Column(name = "longitude", precision = 10, scale = 2, nullable = false)
private BigDecimal longitude;
#NotNull
#Column(name = "latitude", precision = 10, scale = 2, nullable = false)
private BigDecimal latitude;
#NotNull
#Column(name = "membership_approval", nullable = false)
private String membershipApproval;
#NotNull
#Column(name = "privacy", nullable = false)
private String privacy;
public Gang() {}
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Gang name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public Gang description(String description) {
this.description = description;
return this;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getLongitude() {
return longitude;
}
public Gang longitude(BigDecimal longitude) {
this.longitude = longitude;
return this;
}
public void setLongitude(BigDecimal longitude) {
this.longitude = longitude;
}
public BigDecimal getLatitude() {
return latitude;
}
public Gang latitude(BigDecimal latitude) {
this.latitude = latitude;
return this;
}
public void setLatitude(BigDecimal latitude) {
this.latitude = latitude;
}
public String getMembershipApproval() {
return membershipApproval;
}
public Gang membershipApproval(String membershipApproval) {
this.membershipApproval = membershipApproval;
return this;
}
public void setMembershipApproval(String membershipApproval) {
this.membershipApproval = membershipApproval;
}
public String getPrivacy() {
return privacy;
}
public Gang privacy(String privacy) {
this.privacy = privacy;
return this;
}
public void setPrivacy(String privacy) {
this.privacy = privacy;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Gang gang = (Gang) o;
if (gang.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), gang.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Gang{" +
"id=" + getId() +
", name='" + getName() + "'" +
", description='" + getDescription() + "'" +
", longitude=" + getLongitude() +
", latitude=" + getLatitude() +
", membershipApproval='" + getMembershipApproval() + "'" +
", privacy='" + getPrivacy() + "'" +
"}";
}
}
In my humble opinion, there are a couple of things to check.
First, it isn't recommended to use the same object to store data in your database and response a request. The data object could be GangUser, User and Gang, while the response objects GangUserApi, UserApi, and GangApi. With this approach, you'll be able to amend a layer without modifying another.
Second, your service is expecting a GangUser with a User inside. The same User Object that you use to store it in the database. You're just sending a String ("1") instead of an object there.
A quick solution could be modifying the JSON:
{
"role": "member",
"gang": "3",
"user": {
"id":"1"
}
}
But I would like to know if you understand what was going on. That is more important than just give you a quick solution.
Cheers.
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);
}