Edits to tableview cell are lost - jpa

I have a simple JavaFX TableView which is populated by a JPA database query. I have one column set as editable and that works. However, after a change is made in a cell, it disappears as soon as I sort or even navigate through the TableView. Also, how would you persist these edits back to the database?
Here is the FXML file and its controller:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="600.0" prefWidth="800.0" styleClass="mainFxmlClass" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.IXS.synergyixs.ingestor.ViewUsersController">
<stylesheets>
<URL value="#/styles/IssueTrackingLite.css" />
</stylesheets>
<children>
<TableView fx:id="loginsTable" editable="true" prefHeight="593.0" prefWidth="794.0">
<columns>
<TableColumn fx:id="idCol" editable="false" text="Id">
</TableColumn>
<TableColumn fx:id="loginCol" text="Login">
</TableColumn>
<TableColumn fx:id="partyCol" editable="false" text="Party ID">
</TableColumn>
<TableColumn fx:id="creatorCol" editable="false" text="Creator ID">
</TableColumn>
<TableColumn fx:id="modifierCol" editable="false" text="Modifier ID">
</TableColumn>
</columns>
</TableView>
</children>
</AnchorPane>
the controller:
package com.IXS.synergyixs.ingestor;
import com.IXS.synergyixs.ingestor.data.Usr;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.Pane;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* FXML Controller class
*
* #author Owner
*/
public class ViewUsersController implements Initializable {
public EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.mycompany_SynergyIXS-Ingestor_jar_1.0-SNAPSHOTPU");
public EntityManager em = emf.createEntityManager();
public ObservableList<Usr> tableData;
public Usr currentUsr;
/**
* Initializes the controller class.
*/
#FXML
private Pane rootPane;
#FXML
private TableView<Usr> loginsTable;
#FXML
private TableColumn<Usr, Number> idCol;
#FXML
private TableColumn<Usr, String> loginCol;
#FXML
private TableColumn<Usr, Number> partyCol;
#FXML
private TableColumn<Usr, Number> creatorCol;
#FXML
private TableColumn<Usr, Integer> modifierCol;
#Override
public void initialize(URL location, ResourceBundle resources) {
/* to verify query is returning data
for (Usr u : userList) {
System.out.println(u.getId() + " " + u.getLogin());
}
*/
idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
loginCol.setCellValueFactory(new PropertyValueFactory<>("login"));
loginCol.setCellFactory(TextFieldTableCell.forTableColumn‌());
partyCol.setCellValueFactory(new PropertyValueFactory<>("partyId"));
creatorCol.setCellValueFactory(new PropertyValueFactory<>("creatorId"));
modifierCol.setCellValueFactory(new PropertyValueFactory<>("modifierId"));
updateUserList();
loginsTable.setItems(tableData);
}
public void updateUserList() {
List<Usr> userList = em.createNamedQuery("Usr.findAll").getResultList();
if (tableData == null) {
tableData = FXCollections.observableArrayList(userList);
} else {
tableData.clear();
tableData.addAll(userList);
}
}
/*
public void saveUser()
{
em.getTransaction().begin();
em.persist(currentUsr);
em.getTransaction().commit();
updateUserList();
}
*/
}​
Usr class:
package com.IXS.synergyixs.ingestor.data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author Owner
*/
#Entity
#Table(name = "USR", catalog = "", schema = "ADMIN")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Usr.findAll", query = "SELECT u FROM Usr u")
, #NamedQuery(name = "Usr.findById", query = "SELECT u FROM Usr u WHERE u.id = :id")
, #NamedQuery(name = "Usr.findAllLogin", query = "SELECT u.login FROM Usr u")
, #NamedQuery(name = "Usr.findByLogin", query = "SELECT u FROM Usr u WHERE u.login = :login")
, #NamedQuery(name = "Usr.findByPwd", query = "SELECT u FROM Usr u WHERE u.pwd = :pwd")
, #NamedQuery(name = "Usr.findByPartyId", query = "SELECT u FROM Usr u WHERE u.partyId = :partyId")
, #NamedQuery(name = "Usr.findByCreatorId", query = "SELECT u FROM Usr u WHERE u.creatorId = :creatorId")
, #NamedQuery(name = "Usr.findByCreationDttm", query = "SELECT u FROM Usr u WHERE u.creationDttm = :creationDttm")
, #NamedQuery(name = "Usr.findByModifierId", query = "SELECT u FROM Usr u WHERE u.modifierId = :modifierId")
, #NamedQuery(name = "Usr.findByModificationDttm", query = "SELECT u FROM Usr u WHERE u.modificationDttm = :modificationDttm")})
public class Usr implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "ID")
private BigDecimal id;
#Basic(optional = false)
#Column(name = "LOGIN")
private String login;
#Basic(optional = false)
#Column(name = "PWD")
private String pwd;
#Column(name = "PARTY_ID")
private BigInteger partyId;
#Basic(optional = false)
#Column(name = "CREATOR_ID")
private BigInteger creatorId;
#Basic(optional = false)
#Column(name = "CREATION_DTTM")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDttm;
#Basic(optional = false)
#Column(name = "MODIFIER_ID")
private BigInteger modifierId;
#Basic(optional = false)
#Column(name = "MODIFICATION_DTTM")
#Temporal(TemporalType.TIMESTAMP)
private Date modificationDttm;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "usr")
private List<UsrAppRole> usrAppRoleList;
public Usr() {
}
public Usr(BigDecimal id) {
this.id = id;
}
public Usr(BigDecimal id, String login, String pwd, BigInteger creatorId, Date creationDttm, BigInteger modifierId, Date modificationDttm) {
this.id = id;
this.login = login;
this.pwd = pwd;
this.creatorId = creatorId;
this.creationDttm = creationDttm;
this.modifierId = modifierId;
this.modificationDttm = modificationDttm;
}
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public BigInteger getPartyId() {
return partyId;
}
public void setPartyId(BigInteger partyId) {
this.partyId = partyId;
}
public BigInteger getCreatorId() {
return creatorId;
}
public void setCreatorId(BigInteger creatorId) {
this.creatorId = creatorId;
}
public Date getCreationDttm() {
return creationDttm;
}
public void setCreationDttm(Date creationDttm) {
this.creationDttm = creationDttm;
}
public BigInteger getModifierId() {
return modifierId;
}
public void setModifierId(BigInteger modifierId) {
this.modifierId = modifierId;
}
public Date getModificationDttm() {
return modificationDttm;
}
public void setModificationDttm(Date modificationDttm) {
this.modificationDttm = modificationDttm;
}
#XmlTransient
public List<UsrAppRole> getUsrAppRoleList() {
return usrAppRoleList;
}
public void setUsrAppRoleList(List<UsrAppRole> usrAppRoleList) {
this.usrAppRoleList = usrAppRoleList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usr)) {
return false;
}
Usr other = (Usr) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.synergyixs.ingestor.Usr[ id=" + id + " ]";
}
}

The default onEditCommit handler assumes the table's model uses the JavaFX properties pattern (see TableView documentation, section titled "Editing"). Since your Usr class is essentially a plain JavaBean, with no property accessor methods, the default handler reduces to a no-op.
You either need to refactor your Usr class so that it uses JavaFX properties (see Using javafx.beans properties in model classes for a discussion on using JavaFX properties in JPA entities), or set an onEditCommit handler on the column:
loginCol.setOnEditCommit(e -> {
Usr usr = e.getRowValue();
usr.setLogin(e.getNewValue());
});
To store the value in the database, use merge(...):
loginCol.setOnEditCommit(e -> {
Usr usr = e.getRowValue();
usr.setLogin(e.getNewValue());
// merge change to database:
Usr mergedUsr = em.merge(usr);
// ensure table has same reference as ORM cache:
loginsTable.set(e.getTablePosition().getRow(), mergedUsr);
});

Related

Why does spring jpa ignore javax.persistence.FetchType.LAZY and javax.persistence.NamedEntityGraph?

I have a basic "Department"/"Employee" example.
Full example here (in master branch) : https://github.com/granadacoder/jpa-simple-example-one.git
If you setup 4 environment variables (listed in the README), the code is runnable/debuggable.
For my "findAll()" method, I am trying to only bring back the scalars of the Department entity. (key and name). Aka, I do NOT want any child Employees to be tacked onto the Department .. when I do a findAll().
I have tried using an name EntityGraph, but it is not working (I still get the full object graph)
I am using FetchType.LAZY as well. (which should have been enough IMHO)... And I am not calling (department) .getEmployees at all.
But I took the extra step of defining and using "departmentJustScalarsEntityGraphName".
#EntityGraph("departmentJustScalarsEntityGraphName")
List<Department> findAll();
The above is loading the entire graph (all department scalar AND the employees) and doing it in an N+1 manner. :(
The #EntityGraph should only be loading the key and name for the findAll() method.
If you find the code comment
/* right here, desperately hoping for each Department in the "entities" to NOT have employees hydrated */
you can put the debugger there and see the issue.
Note, that when I do a "find by single" (findById(key) or findDepartmentByDepartmentNameEquals(name))......I DO want the employees. So answers that broad stroke disassociate the Employees are not ideal.
No matter what I've tried, I'm getting the N+1 issue. (The sample seed data has three Departments.)
Hibernate: select department0_.DepartmentKey as departme1_0_, department0_.CreateOffsetDateTime as createof2_0_, department0_.DepartmentName as departme3_0_ from DepartmentTable department0_
Hibernate: select employees0_.DepartmentForeignKey as departme6_1_0_, employees0_.EmployeeKey as employee1_1_0_, employees0_.EmployeeKey as employee1_1_1_, employees0_.CreateOffsetDateTime as createof2_1_1_, employees0_.FirstName as firstnam3_1_1_, employees0_.LastName as lastname4_1_1_, employees0_.DepartmentForeignKey as departme6_1_1_, employees0_.Ssn as ssn5_1_1_ from EmployeeTable employees0_ where employees0_.DepartmentForeignKey=?
Hibernate: select employees0_.DepartmentForeignKey as departme6_1_0_, employees0_.EmployeeKey as employee1_1_0_, employees0_.EmployeeKey as employee1_1_1_, employees0_.CreateOffsetDateTime as createof2_1_1_, employees0_.FirstName as firstnam3_1_1_, employees0_.LastName as lastname4_1_1_, employees0_.DepartmentForeignKey as departme6_1_1_, employees0_.Ssn as ssn5_1_1_ from EmployeeTable employees0_ where employees0_.DepartmentForeignKey=?
Hibernate: select employees0_.DepartmentForeignKey as departme6_1_0_, employees0_.EmployeeKey as employee1_1_0_, employees0_.EmployeeKey as employee1_1_1_, employees0_.CreateOffsetDateTime as createof2_1_1_, employees0_.FirstName as firstnam3_1_1_, employees0_.LastName as lastname4_1_1_, employees0_.DepartmentForeignKey as departme6_1_1_, employees0_.Ssn as ssn5_1_1_ from EmployeeTable employees0_ where employees0_.DepartmentForeignKey=?
Here are the main code components:
Department.java
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.mycompany.organizationdemo.domain.constants.OrmConstants;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.OffsetDateTime;
import java.util.LinkedHashSet;
import java.util.Set;
#Entity
#NamedEntityGraphs({
#NamedEntityGraph(name = "departmentJustScalarsEntityGraphName", attributeNodes = {
#NamedAttributeNode("departmentKey"),
#NamedAttributeNode("departmentName")})
})
#Table(name = "DepartmentTable")
public class Department implements Serializable {
#Id
#Column(name = "DepartmentKey", unique = true)
#GeneratedValue(strategy = GenerationType.AUTO)
private long departmentKey;
#Column(name = "DepartmentName", unique = true)
private String departmentName;
#Column(name = "CreateOffsetDateTime", columnDefinition = OrmConstants.OffsetDateTimeColumnDefinition)
private OffsetDateTime createOffsetDateTime;
//region Navigation
#OneToMany(
mappedBy = "parentDepartment",
cascade = CascadeType.REMOVE,
orphanRemoval = true,
fetch = FetchType.LAZY /* Lazy or Eager here */
)
private Set<Employee> employees = new LinkedHashSet<>();
//endregion
public long getDepartmentKey() {
return departmentKey;
}
public void setDepartmentKey(long departmentKey) {
this.departmentKey = departmentKey;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public OffsetDateTime getCreateOffsetDateTime() {
return createOffsetDateTime;
}
public void setCreateOffsetDateTime(OffsetDateTime createOffsetDateTime) {
this.createOffsetDateTime = createOffsetDateTime;
}
//region Navigation
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
//endregion
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Department that = (Department) o;
return new org.apache.commons.lang3.builder.EqualsBuilder()
.append(departmentKey, that.departmentKey)
.append(departmentName, that.departmentName)
.isEquals();
}
#Override
public int hashCode() {
return new org.apache.commons.lang3.builder.HashCodeBuilder(17, 37)
.append(departmentKey)
.append(departmentName)
.toHashCode();
}
}
Employee.java
import com.mycompany.organizationdemo.domain.constants.OrmConstants;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.OffsetDateTime;
#Entity
#Table(name = "EmployeeTable")
public class Employee implements Serializable {
#Id
#Column(name = "EmployeeKey", unique = true)
#GeneratedValue(strategy = GenerationType.AUTO)
private long employeeKey;
#Column(name = "Ssn")
private String ssn;
#Column(name = "LastName")
private String lastName;
#Column(name = "FirstName")
private String firstName;
#Column(name = "CreateOffsetDateTime", columnDefinition = OrmConstants.OffsetDateTimeColumnDefinition)
private OffsetDateTime createOffsetDateTime;
//region Navigation
#ManyToOne(fetch = FetchType.LAZY, targetEntity = Department.class)//, cascade = CascadeType.REMOVE)
#JoinColumn(name = "DepartmentForeignKey")
private Department parentDepartment;
//endregion
public long getEmployeeKey() {
return employeeKey;
}
public void setEmployeeKey(long departmentKey) {
this.employeeKey = departmentKey;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public OffsetDateTime getCreateOffsetDateTime() {
return createOffsetDateTime;
}
public void setCreateOffsetDateTime(OffsetDateTime createOffsetDateTime) {
this.createOffsetDateTime = createOffsetDateTime;
}
//region Navigation
public Department getParentDepartment() {
return parentDepartment;
}
public void setParentDepartment(Department parentDepartment) {
this.parentDepartment = parentDepartment;
}
//endregion
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return new EqualsBuilder()
.append(employeeKey, employee.employeeKey)
.append(ssn, employee.ssn)
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(employeeKey)
.append(ssn)
.toHashCode();
}
}
Spring JPA
import com.mycompany.organizationdemo.domain.entities.Department;
import com.mycompany.organizationdemo.domaindatalayer.interfaces.IDepartmentRepository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.transaction.Transactional;
import java.time.OffsetDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public interface DepartmentJpaRepository extends JpaRepository<Department, Long>, IDepartmentRepository {
#EntityGraph("departmentJustScalarsEntityGraphName")
List<Department> findAll();
#Query("SELECT d FROM Department d LEFT JOIN FETCH d.employees WHERE d.departmentName = :departmentName") /* this works because departmentName is a UNIQUE constraint...otherwise it might give back duplicate parents (Departments) */
Optional<Department> findDepartmentByDepartmentNameEquals(#Param("departmentName") String departmentName);
/* note the below, this is "lookup strategy". see https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods */
Collection<Department> findByCreateOffsetDateTimeBefore(OffsetDateTime zdt);
//#Query("SELECT d FROM Department d LEFT JOIN FETCH d.employees WHERE d.departmentKey IN ?1") /* here a Query will bring back repeat parent (Department) rows */
#EntityGraph(attributePaths = {"employees"})
Collection<Department> findDepartmentByDepartmentKeyIn(Set<Long> departmentKeys);
#Modifying
#Transactional
int deleteDepartmentByDepartmentKey(long departmentKey); /* suffers from N+1 problem */
}
and the repository (plain jane) interface
import com.mycompany.organizationdemo.domain.entities.Department;
import java.time.OffsetDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public interface IDepartmentRepository {
List<Department> findAll();
Optional<Department> findById(long key);
Optional<Department> findDepartmentByDepartmentNameEquals(String departmentName);
Collection<Department> findByCreateOffsetDateTimeBefore(OffsetDateTime zdt);
Collection<Department> findDepartmentByDepartmentKeyIn(Set<Long> departmentKeys);
Department save(Department item);
int deleteDepartmentByDepartmentKey(long departmentKey);
}
I have found this:
Spring Data JPARepository: How to conditionally fetch children entites
and this:
https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs002.htm
Spring Boot is fairly new. (from gradle settings in the project)
spring_plugin_version = '2.2.6.RELEASE'
springBootVersion = '2.2.6.RELEASE'
slf4jVersion = "1.7.25"
javaxInjectVersion = "1"
javaxPersistenceApiVersion = "2.2"
junitVersion = "4.12"
mockitoVersion = "3.3.0"
jacksonAnnotationsVersion = "2.11.0"
modelMapperVersion = "2.3.7"
commonsLangVersion = '3.7'
PS
I'm also using the "convert to Dto" trick (as seen here) : https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application but the Department(orm-entity) is already hydrated by that point. :(

Spring JpaRepository save causes 100s of selects to be generated

Im getting very strange error when I call save on a JpaRepository.
The code seems trivial so i can only think its something to do with configuration.
Basically I call a findBy method on the repository, this returns a list of dao objects exactly as expected, I go through this list setting a timestamp then calling save() on each dao, as soon as the first save is called the log is filled with hundreds of identical select statements, selecting on the dao I'm just trying to save until eventually there is a stack overflow.
What could cause this ???
(note originally I called saveAll() on the list of dao objects - this, unsurprisingly has the same error )
public void triggerDeletion() {
ZonedDateTime expiryDate = ZonedDateTime.now().minus(daysAfterExpiry);
// Get list of conversations to delete
List<ConversationDao> conversationDaoList = conversationDatabaseService.retrieveExpiredConversations(expiryDate);
// Mark each conversation as deleted by setting its deletion timestamp to now.
conversationDaoList.stream().forEach(conversation->delete(conversation));
}
public void delete(ConversationDao conversationDao){
conversationDao.setDeletionTimestamp(new Timestamp(System.currentTimeMillis()));
conversationDatabaseService.save( conversationDao ); <------ This generates 100s of select statements.
}
...
// ConversationDatabaseService Interface
////////////////////////////////////////
public interface ConversationDatabaseService {
void save(ConversationDao conversationDao);
}
...
// Conversation DatabaseService Class
/////////////////////////////////////
#Service
public class ConversationDatabaseServiceImpl implements ConversationDatabaseService {
private final ConversationRepository conversationRepository;
public void save(ConversationDao conversationDao) {
conversationRepository.saveAndFlush(conversationDao); // Just save has also been tried.
}
}
...
// ConversationRepository interface
///////////////////////////////////
public interface ConversationRepository extends JpaRepository<ConversationDao, String> {
List<ConversationDao> findByExpiryDateLessThanAndDeletionTimestampIsNull(Timestamp expiryDate);
}
...
// ConversationDao
//////////////////////////////////
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.UpdateTimestamp;
#Entity
#Table(name = "DOCX_CONVERSATION")
public class ConversationDao {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2",
strategy = "uuid2")
#Column(name = "CONVERSATION_ID",
columnDefinition = "char")
private String conversationId;
#Column(name = "PROCESS_CODE")
private String processCode;
#Column(name = "PROFILE_ID",
columnDefinition = "char")
private String profileId;
#Column(name = "REMINDER_EMAIL_SENT",
columnDefinition = "char")
private String reminderEmailSent;
#Column(name = "EXPIRY_DATE")
private Date expiryDate;
#Column(name = "DELETION_TIMESTAMP")
private Timestamp deletionTimestamp;
#Column(name = "LAST_LOGIN_TIMESTAMP")
private Timestamp lastLoginTimestamp;
#Column(name = "CREATED_USER_ID",
columnDefinition = "char")
private String colleagueId;
#Column(name = "CREATED_TIMESTAMP",
updatable = false)
#CreationTimestamp
private Timestamp createdTimestamp;
#Column(name = "LAST_UPDATED_USER_ID",
columnDefinition = "char")
private String lastUpdatedUserId;
#Column(name = "LAST_UPDATED_TIMESTAMP")
#UpdateTimestamp
private Timestamp lastUpdatedTimestamp;
#OneToMany(mappedBy = "conversation",
cascade = CascadeType.ALL)
private Set<MessageDetailDao> messageDetailDaoSet = new HashSet<>();
#OneToMany(mappedBy = "fileDetailId.conversation",
cascade = CascadeType.ALL)
private Set<FileDetailDao> fileDetailDaoSet = new HashSet<>();
#OneToMany(mappedBy = "conversation",
cascade = CascadeType.ALL)
private Set<ParameterDao> parameterDaoSet = new HashSet<>();
#OneToMany(mappedBy = "conversation",
cascade = CascadeType.ALL)
private Set<NotificationDao> notificationDaoSet = new HashSet<>();
public ConversationDao() {
}
public ConversationDao(String processCode, Date expiryDate,
String colleagueId, String lastUpdatedUserId) {
this.processCode = processCode;
this.reminderEmailSent = "N";
this.expiryDate = expiryDate;
this.colleagueId = colleagueId;
this.lastUpdatedUserId = lastUpdatedUserId;
}
public String getConversationId() {
return conversationId;
}
public void setConversationId(String conversationId) {
this.conversationId = conversationId;
}
public String getProcessCode() {
return processCode;
}
public void setProcessCode(String processCode) {
this.processCode = processCode;
}
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getReminderEmailSent() {
return reminderEmailSent;
}
public void setReminderEmailSent(String reminderEmailSent) {
this.reminderEmailSent = reminderEmailSent;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public Timestamp getDeletionTimestamp() {
return deletionTimestamp;
}
public void setDeletionTimestamp(Timestamp deletionTimestamp) {
this.deletionTimestamp = deletionTimestamp;
}
public Timestamp getLastLoginTimestamp() {
return lastLoginTimestamp;
}
public void setLastLoginTimestamp(Timestamp lastLoginTimestamp) {
this.lastLoginTimestamp = lastLoginTimestamp;
}
public String getColleagueId() {
return colleagueId.trim();
}
public void setColleagueId(String colleagueId) {
this.colleagueId = colleagueId;
}
public Timestamp getCreatedTimestamp() {
return createdTimestamp;
}
public void setCreatedTimestamp(Timestamp createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
public String getLastUpdatedUserId() {
return lastUpdatedUserId;
}
public void setLastUpdatedUserId(String lastUpdatedUserId) {
this.lastUpdatedUserId = lastUpdatedUserId;
}
public Timestamp getLastUpdatedTimestamp() {
return lastUpdatedTimestamp;
}
public void setLastUpdatedTimestamp(Timestamp lastUpdatedTimestamp) {
this.lastUpdatedTimestamp = lastUpdatedTimestamp;
}
public void addMessageDetailDao(MessageDetailDao messageDetailDao) {
messageDetailDaoSet.add(messageDetailDao);
messageDetailDao.setConversation(this);
}
public Set<MessageDetailDao> getMessageDetailDao() {
return messageDetailDaoSet;
}
public void addFileDetailDao(FileDetailDao fileDetailDao) {
fileDetailDaoSet.add(fileDetailDao);
fileDetailDao.getId().setConversation(this);
}
public Set<FileDetailDao> getFileDetailDao() {
return fileDetailDaoSet;
}
public void addParameterDao(ParameterDao parameterDao) {
parameterDaoSet.add(parameterDao);
parameterDao.setConversation(this);
}
public Set<ParameterDao> getParameterDao() {
return parameterDaoSet;
}
public void addNotificationDao(NotificationDao notificationDao) {
notificationDaoSet.add(notificationDao);
notificationDao.setConversation(this);
}
public Set<NotificationDao> getNotificationDao() {
return notificationDaoSet;
}
}
}
This generates these same select statements 100s of times before blowing the stack :-
1TS="20190411.075004.028" 4MSG="binding parameter [1] as [VARCHAR] - [6df49d6f-216b-460d-9282-2d25c098f9fe]" 1EVC="TRACE" 2CLS="BasicBinder"
1TS="20190411.075004.065" 4MSG="extracted value ([convers16_10_0_] : [VARCHAR]) - [6df49d6f-216b-460d-9282-2d25c098f9fe]" 1EVC="TRACE" 2CLS="BasicExtractor"
1TS="20190411.075004.069" 4MSG="extracted value ([file_met1_10_0_] : [VARCHAR]) - [4E90FD20-FC59-41B8-BF8E-88B7D682A87C]" 1EVC="TRACE" 2CLS="BasicExtractor"
1TS="20190411.075004.074" 4MSG="select conversati0_.conversation_id as conversa1_5_1_, conversati0_.created_user_id as created_2_5_1_, conversati0_.created_timestamp as created_3_5_1_, conversati0_.deletion_timestamp as deletion4_5_1_, conversati0_.expiry_date as expiry_d5_5_1_, conversati0_.last_login_timestamp as last_log6_5_1_, conversati0_.last_updated_timestamp as last_upd7_5_1_, conversati0_.last_updated_user_id as last_upd8_5_1_, conversati0_.process_code as process_9_5_1_, conversati0_.profile_id as profile10_5_1_, conversati0_.reminder_email_sent as reminde11_5_1_, filedetail1_.conversation_id as convers16_10_3_, filedetail1_.file_metadata_id as file_met1_10_3_, filedetail1_.conversation_id as convers16_10_0_, filedetail1_.file_metadata_id as file_met1_10_0_, filedetail1_.application_id as applicat2_10_0_, filedetail1_.case_id as case_id3_10_0_, filedetail1_.created_user_id as created_4_10_0_, filedetail1_.content_type as content_5_10_0_, filedetail1_.created_by as created_6_10_0_, filedetail1_.created_timestamp as created_7_10_0_, filedetail1_.document_code as document8_10_0_, filedetail1_.document_owner as document9_10_0_, filedetail1_.document_repository_state as documen10_10_0_, filedetail1_.file_name as file_na11_10_0_, filedetail1_.file_size_bytes as file_si12_10_0_, filedetail1_.file_state as file_st13_10_0_, filedetail1_.file_version as file_ve14_10_0_, filedetail1_.updated_by as updated15_10_0_ from docx_conversation conversati0_ left outer join docx_file_detail filedetail1_ on conversati0_.conversation_id=filedetail1_.conversation_id where conversati0_.conversation_id=?" 1EVC="DEBUG" 2CLS="SQL"
What is going on ??
Some more information, the cause is definitely connected to this part of the dao :-
#OneToMany(mappedBy = "fileDetailId.conversation",cascade = CascadeType.ALL)
private Set<FileDetailDao> fileDetailDaoSet = new HashSet<>();
The FileDetailDao contains an embedded reference to a FileDetailId
#EmbeddedId
private FileDetailId fileDetailId;
And this FileDetailId contains a reference to the conversationId of the join :-
#Embeddable
public class FileDetailId implements Serializable {
#Column(name = "FILE_METADATA_ID", columnDefinition = "char")
private String fileMetadataId;
#ManyToOne
#JoinColumn(name = "CONVERSATION_ID")
private ConversationDao conversation;
//etc
}
Im not sure why but if I change the cascade type to REMOVE it works ok....
#OneToMany(mappedBy = "fileDetailId.conversation",cascade = CascadeType.REMOVE)
private Set<FileDetailDao> fileDetailDaoSet = new HashSet<>();

Transaction aborted in controller

I'm having troubles implementing JPA methods in my WebApp built in Java ee 7, its returned me "EJBException : Transaction aborted" , but the parameters "ID" and "Description" had send correctly.
package entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author Fede-Frost
*/
#Entity
#Table(name = "especialidad")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Especialidad.findAll", query = "SELECT e FROM Especialidad e")
, #NamedQuery(name = "Especialidad.findById", query = "SELECT e FROM Especialidad e WHERE e.id = :id")
, #NamedQuery(name = "Especialidad.findByDesc", query = "SELECT e FROM Especialidad e WHERE e.desc = :desc")})
public class Especialidad implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 45)
#Column(name = "desc")
private String desc;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "especialidad")
private List<Medico> medicoList;
public Especialidad() {
}
public Especialidad(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
#XmlTransient
public List<Medico> getMedicoList() {
return medicoList;
}
public void setMedicoList(List<Medico> medicoList) {
this.medicoList = medicoList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Especialidad)) {
return false;
}
Especialidad other = (Especialidad) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "MyHospital.Especialidad[ id=" + id + " ]";
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import entities.Estudiolab;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Fede-Frost
*/
#Stateless
public class EstudiolabFacade extends AbstractFacade<Estudiolab> implements EstudiolabFacadeLocal {
#PersistenceContext(unitName = "MyHospital-ejbPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public EstudiolabFacade() {
super(Estudiolab.class);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import entities.Especialidad;
import java.util.List;
import javax.ejb.Local;
/**
*
* #author Fede-Frost
*/
#Local
public interface EspecialidadFacadeLocal {
void create(Especialidad especialidad);
void edit(Especialidad especialidad);
void remove(Especialidad especialidad);
Especialidad find(Object id);
List<Especialidad> findAll();
List<Especialidad> findRange(int[] range);
int count();
}
And here it's the big deal, on the controller
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import entities.Especialidad;
import javax.inject.Named;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import model.EspecialidadFacadeLocal;
/**
*
* #author Fede-Frost
*/
#ViewScoped
#Named(value = "mediCon")
public class mediCon implements Serializable {
#EJB
private EspecialidadFacadeLocal especFac;
#Inject
private Especialidad espec;
/**
* Creates a new instance of MediCon
* #return
*/
public void addSpec() {
try {
especFac.create(espec);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Exito", "Se registro correctamente"));
} catch (EJBException e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Aviso", e.toString() ));
}
}
public Especialidad getEspec() {
return espec;
}
public void setEspec(Especialidad espec) {
this.espec = espec;
}
}
As I said, JSF sent me the correct parameters which I tested with FacesContext.addMessage, but I don't know why it doesn't work, thanks in advance.
If a SystemException(A system exception must be a subclass
of a RuntimeException or java.rmi.RemoteException) is thrown, the current transaction will be rollbacked
For more information about the Exception types in EJB, you could have a look at this link.
but the query it's from JPA standard created on especialidadFacade
with especialidaEntity
please have a look at JPA: Weird error when I try to persist an object
in your case, "desc" is a reserved keyword

Why does id of child entity return 0 in response message in EclipseLink?

I'm using a One-To-One association between my Member and MemberRoles tables. I wanted them to share the same id as PK and FK in the database and did it. But I've got another problem. When I insert a Member, a MemberRole record is being inserted with it and Member record has the correct id in return response but MemberRole id is incorrect. It returns 0 like this:
{
"result": "Bulk user member saving is successfull. Members' informations are:",
"memberList": [
{
"id": 2,
"firstName": "Michael",
"lastName": "Schumacher",
"email": "ilkay.gune2l#kod5.org",
"enabled": false,
"memberLanguageCode": "tr",
"roleOfMember": {
"id": 0,
"email": "ilkay.gune2l#kod5.org",
"role": "ROLE_USER"
}
}
]
}
My Member Entity Class:
package com.ilkaygunel.entities;
import java.time.LocalDateTime;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#JsonInclude(Include.NON_NULL)
#NamedQueries({ #NamedQuery(name = "Member.findAll", query = "select m from Member m"),
#NamedQuery(name = "Member.findByFirstName", query = "select m from Member m where m.firstName =:firstName"),
#NamedQuery(name = "Member.findPasswordOfMember", query = "select m.password from Member m where m.id =:id"),
#NamedQuery(name = "Member.findByActivationToken", query = "select m from Member m where m.activationToken =:activationToken"),
#NamedQuery(name = "Member.findByEmail", query = "select m from Member m where m.email =:email") })
#Table(name = "MEMBER")
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "MEMBER_ID")
private long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(nullable = false, updatable = false)
private String email;
#Column(nullable = false, updatable = false)
private boolean enabled;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String memberLanguageCode;
#Column(updatable = false)
#JsonIgnore
private String activationToken;
#Column(updatable = false)
#JsonIgnore
private LocalDateTime activationTokenExpDate;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "member", optional = false)
#PrimaryKeyJoinColumn(name = "MEMBER_ID")
private MemberRoles roleOfMember;
#Override
public String toString() {
return String.format("Member [id=%d, firstName='%s', lastName='%s', email='%s']", id, firstName, lastName,
email);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
if (null != roleOfMember) {
roleOfMember.setId(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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MemberRoles getRoleOfMember() {
return roleOfMember;
}
public void setRoleOfMember(MemberRoles roleOfMember) {
this.roleOfMember = roleOfMember;
}
public String getActivationToken() {
return activationToken;
}
public void setActivationToken(String activationToken) {
this.activationToken = activationToken;
}
public LocalDateTime getActivationTokenExpDate() {
return activationTokenExpDate;
}
public void setActivationTokenExpDate(LocalDateTime activationTokenExpDate) {
this.activationTokenExpDate = activationTokenExpDate;
}
public String getMemberLanguageCode() {
return memberLanguageCode;
}
public void setMemberLanguageCode(String memberLanguageCode) {
this.memberLanguageCode = memberLanguageCode;
}
}
And my MemberRoles Entity class:
package com.ilkaygunel.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#NamedQueries({
#NamedQuery(name = "MemberRoles.findByEmail", query = "select mr from MemberRoles mr where mr.email = :email") })
#Table(name = "MEMBERROLES")
public class MemberRoles {
#Id
#Column(name = "MEMBERROLES_ID")
private long id;
private String email;
private String role;
#MapsId
#OneToOne(optional = false)
#JoinColumn(name = "MEMBERROLES_ID", unique = true, nullable = false, updatable = false)
#JsonIgnore
private Member member;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
}
When I inserted a Member record, I check it on the database and see that Member and MemberRoles record have the same id. But why does MemberRoles area in response message has got id as 0?
My MemberSaveService class like this:
package com.ilkaygunel.service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.ilkaygunel.constants.ConstantFields;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.entities.MemberRoles;
import com.ilkaygunel.exception.CustomException;
import com.ilkaygunel.exception.ErrorCodes;
import com.ilkaygunel.pojo.MemberOperationPojo;
#Service
public class MemberSaveService extends BaseService {
public MemberOperationPojo addUserMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_USER.getConstantField());
}
public MemberOperationPojo addAdminMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_ADMIN.getConstantField());
}
public MemberOperationPojo addBulkMember(List<Member> memberList, String role) {
Logger LOGGER = loggingUtil.getLoggerForMemberSaving(this.getClass());
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingMethod", "en"));
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
List<Member> savedMemberList = new ArrayList<>();
try {
memberUtil.checkEmailAddressAndLanguageOnMemberList(memberList, LOGGER);
for (Member member : memberList) {
addOneMember(member, role, LOGGER);
savedMemberList.add(member);
}
memberOperationPojo.setResult(
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en"));
memberOperationPojo.setMemberList(memberUtil.removeFieldsFromReturningMember(savedMemberList));
LOGGER.log(Level.INFO,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en")
+ memberList);
} catch (CustomException customException) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ customException.getErrorCode() + " " + customException.getErrorMessage());
memberOperationPojo.setErrorCode(customException.getErrorCode());
memberOperationPojo.setResult(customException.getErrorMessage());
} catch (Exception e) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ e.getMessage());
memberOperationPojo.setErrorCode(ErrorCodes.ERROR_10.getErrorCode());
memberOperationPojo.setResult(e.getMessage());
}
return memberOperationPojo;
}
private void addOneMember(Member member, String role, Logger LOGGER) throws MessagingException {
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingMethod",
member.getMemberLanguageCode()));
member.setPassword(getHashedPassword(member.getPassword()));
member.setEnabled(false);
addMemberRolesObject(role, member);
addActivationToken(member);
memberFacade.create(member);
// mailUtil.sendActivationMail(member.getEmail(), member.getActivationToken());
memberOperationPojo.setResult(resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()));
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()) + member);
}
private String getHashedPassword(String rawPassword) {
return new BCryptPasswordEncoder().encode(rawPassword);
}
private void addMemberRolesObject(String role, Member member) {
MemberRoles rolesOfMember = new MemberRoles();
rolesOfMember.setRole(role);
rolesOfMember.setEmail(member.getEmail());
rolesOfMember.setMember(member);
member.setRoleOfMember(rolesOfMember);
}
private void addActivationToken(Member member) {
String activationToken = UUID.randomUUID().toString();
member.setActivationToken(activationToken);
LocalDateTime activationTokenExpDate = LocalDateTime.now().plusDays(1);
// LocalDateTime activationTokenExpDate = LocalDateTime.now();//Use for expire
// date test!
member.setActivationTokenExpDate(activationTokenExpDate);
}
}
My Web Service End Point Class like this:
package com.ilkaygunel.restservice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.pojo.MemberOperationPojo;
import com.ilkaygunel.service.MemberSaveService;
#RestController
#RequestMapping("/memberPostWebServiceEndPoint")
public class MemberSaveWebServiceEndPoint {
#Autowired
private MemberSaveService memberSaveService;
#RequestMapping(value = "/saveUserMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveUserMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addUserMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
#RequestMapping(value = "/saveAdminMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveAdminMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addAdminMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
}

QueryDSL doesn't generate QType for specific entity

Really confused about this. I'm using Spring Data MongoAnnotationProcessor to generate QTypes for my domain models. Those mongo models happen to use some other models from a dependency that are jpa models. Even though I'm using the mongo processor, QueryDSL ends up generating QTypes for these jpa annotated #Entities except for a specific one. I tried comparing it to the other generated entities but didn't find any huge differences.
Here is the entity:
import com.fasterxml.jackson.annotation.JsonIgnore;
import base.lexicon.model.Literal;
import base.lexicon.model.Sport;
import base.lexicon.model.Tournament;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Cache(
usage = CacheConcurrencyStrategy.READ_WRITE,
region = "base.lexicon.model.Category"
)
#SequenceGenerator(
name = "CATEGORY_SEQ",
sequenceName = "CATEGORY_SEQ",
allocationSize = 1
)
public class Category implements Serializable {
private static final long serialVersionUID = 6989006403439170511L;
#Id
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "CATEGORY_SEQ"
)
#Column(
name = "CATEGORY_ID"
)
private int id;
private String description;
#OneToMany(
mappedBy = "category"
)
#Cascade({CascadeType.ALL})
#Cache(
usage = CacheConcurrencyStrategy.READ_WRITE,
region = "base.lexicon.model.Category.tournaments"
)
#XmlTransient
private List<Tournament> tournaments;
#ManyToOne
#ForeignKey(
name = "FK_SPORT_CATEGORY"
)
#JoinColumn(
name = "SPORT_ID",
nullable = false
)
#XmlTransient
private Sport sport;
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany
#Cascade({CascadeType.ALL})
#Cache(
usage = CacheConcurrencyStrategy.READ_WRITE,
region = "base.lexicon.model.Category.literals"
)
#JoinTable(
name = "CATEGORY_LITERAL",
joinColumns = { #JoinColumn(
name = "CATEGORY_ID",
referencedColumnName = "CATEGORY_ID"
)},
inverseJoinColumns = { #JoinColumn(
name = "LITERAL_ID",
referencedColumnName = "LITERAL_ID"
)}
)
private Set<Literal> literals;
public Category() {
}
public int getCategoryId() {
return this.id;
}
public void setCategoryId(int id) {
this.id = id;
}
#JsonIgnore
public List<Tournament> getTournaments() {
if(this.tournaments == null) {
this.tournaments = new ArrayList();
}
return this.tournaments;
}
public void setTournaments(List<Tournament> tournaments) {
if(tournaments != null) {
Iterator var2 = tournaments.iterator();
while(var2.hasNext()) {
Tournament tournament = (Tournament)var2.next();
if(tournament.getCategory() == null) {
tournament.setCategory(this);
}
}
this.tournaments = tournaments;
}
}
public Set<Literal> getLiterals() {
if(this.literals == null) {
this.literals = new HashSet();
}
return this.literals;
}
public void setLiterals(Set<Literal> literals) {
this.literals = literals;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#XmlTransient
public Sport getSport() {
return this.sport;
}
public void setSport(Sport sport) {
this.sport = sport;
}
public boolean equals(Object o) {
if(this == o) {
return true;
} else if(!(o instanceof Category)) {
return false;
} else {
Category category = (Category)o;
if(this.id != category.id) {
return false;
} else {
if(this.description != null) {
if(this.description.equalsIgnoreCase(category.description)) {
return this.sport != null?this.sport.equals(category.sport):category.sport == null;
}
} else if(category.description == null) {
return this.sport != null?this.sport.equals(category.sport):category.sport == null;
}
return false;
}
}
}
public int hashCode() {
int result = this.id;
result = 31 * result + (this.description != null?this.description.toLowerCase().hashCode():0);
result = 31 * result + (this.sport != null?this.sport.hashCode():0);
return result;
}
}
Does it contain any annotation or other thing that blocks the processor from generating it?