Unable to save model with Many-to-Many relationship: form returns JSF Validation Error: Value is not valid [duplicate] - validation

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I have stayed on this issue for sometimes now. Can someone tell me what I am getting wrong
Groupp.java
public class Groupp implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Basic(optional = false)
#NotNull
private String name;
#Basic(optional = false)
#NotNull
private String description;
#JoinTable(name = "group_role", joinColumns = {
#JoinColumn(name = "group_id", referencedColumnName = "id", nullable = false)}, inverseJoinColumns = {
#JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false)})
#ManyToMany
private List<Role> roles;
//getters and setters
}
GroupController.java
#Named("groupController")
#SessionScoped
public class GroupController implements Serializable {
private Groupp current;
#EJB
private GroupFacade ejbFacade;
public GroupController() {
}
public Groupp getSelected() {
if (current == null) {
current = new Groupp();
selectedItemIndex = -1;
}
return current;
}
public String createGroup() {
System.out.println("********Start Create Group***********");
try {
getFacade.create(current);
return null;
}
#FacesConverter(forClass = Groupp.class)
public static class GrouppControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
System.out.println("Groupp::Submitted: String: "+value);
if (value == null || value.length() == 0) {
return null;
}
GroupController controller = (GroupController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "grouppController");
System.out.println("Groupp::Object of Submitted: String: "+controller.getGroupp(getKey(value)));
return controller.getGroupp(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Groupp) {
Groupp o = (Groupp) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Groupp.class.getName());
}
}
}
}
RoleController.java
#Named("roleController")
#SessionScoped
public class RoleController implements Serializable {
private Role current;
#EJB
private RoleFacade ejbFacade;
public RoleController() {
}
public SelectItem[] getItemsAvailableSelectMany() {
for (Object x : ejbFacade.findAll()) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
#FacesConverter(forClass = Role.class)
public static class RoleControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
System.out.println("Role::Submitted: String: "+value);
if (value == null || value.length() == 0) {
return null;
}
RoleController controller = (RoleController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "roleController");
System.out.println("Role::Object of Submitted: String: "+controller.getRole(getKey(value)));
return controller.getRole(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Role) {
Role o = (Role) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Role.class.getName());
}
}
}
}
create.jsp
<f:view>
<h:form id="groupForm">
<h:inputText id="name" value="${groupController.selected.name}" />
<h:inputText id="description" value="${groupController.selected.description}" />
<h:selectManyListbox id="roles" value="${groupController.selected.roles}" >
<f:selectItems value="${roleController.itemsAvailableSelectMany}" var="role" itemValue="${role}" itemLabel="${role.label}" >
</h:selectManyListbox>
<b:commandButton action="${groupController.createGroup}" value="SAVE" />
</h:form>
</f:view>
Each time I click on the SAVE Button i get "groupForm:roles: Validation Error: Value is not valid" and "********Start Create Group***********" is never printed

Could you try it like this instead:
public List<Role> getItemsAvailableSelectMany() {
return roleFacade.findAll();
}
<f:selectItems value="${groupController.itemsAvailableSelectMany}"
var="role"
itemValue="${role}"
itemLabel="${role.xxx}"/>
(whatever property you want shown from role entity in the last line).
Plus the converter is needed, if in doubt this one seems nice.

Related

Mapstruct mapping with condition and nullValuePropertyMappingStrategy

I apologize if the title is not clear, let me make it clear by giving sample codes:
UpdateProfileDto
public class UpdateProfileDto {
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#Size(max = 20)
private String currentPassword;
#Size(max = 20)
private String newPassword;
#Size(max = 20)
private String confirmNewPassword;
// getters and setters
}
EncodedMapping
#Qualifier
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.CLASS)
public #interface EncodedMapping {
}
PasswordEncoderMapper
public class PasswordEncoderMapper {
protected final PasswordEncoder passwordEncoder;
public PasswordEncoderMapper(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
#EncodedMapping
public String encode(String value) {
return passwordEncoder.encode(value);
}
}
UserMapper
#Mapper(config = MapperConfig.class, componentModel = "spring", uses = PasswordEncoderMapper.class)
public interface UserMapper {
#Mappings({
#Mapping(target = "firstName", source = "firstName"),
#Mapping(target = "lastName", source = "lastName"),
#Mapping(target = "fullName", expression = "java(user.getFirstName() + \" \" + user.getLastName())"),
#Mapping(target = "password",
source = "newPassword",
nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
qualifiedBy = EncodedMapping.class)
})
void updateUserFromDto(UpdateUserProfileDto updateUserProfileDto, #MappingTarget User user);
}
Generated UserMapperImpl
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2020-03-11T13:51:34+0800",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_231 (Oracle Corporation)"
)
#Component
public class UserMapperImpl implements UserMapper {
#Autowired
private PasswordEncoderMapper passwordEncoderMapper;
#Override
public void updateUserFromDto(UpdateUserProfileDto updateUserProfileDto, User user) {
if ( updateUserProfileDto == null ) {
return;
}
if ( updateUserProfileDto.getFirstName() != null ) {
user.setFirstName( updateUserProfileDto.getFirstName() );
}
else {
user.setFirstName( null );
}
if ( updateUserProfileDto.getLastName() != null ) {
user.setLastName( updateUserProfileDto.getLastName() );
}
else {
user.setLastName( null );
}
if ( updateUserProfileDto.getNewPassword() != null ) {
user.setPassword( passwordEncoderMapper.encode( updateUserProfileDto.getNewPassword() ) );
}
user.setFullName( user.getFirstName() + " " + user.getLastName() );
}
}
From the generated UserMapperImpl, I would like to check not only if newPassword has value... but to check currentPassword and newPassword have values and proceed with user.setPassword().
I mean something like this:
...
if ( updateUserProfileDto.getCurrentPassword() != null && updateUserProfileDto.getNewPassword() != null ) {
user.setPassword( passwordEncoderMapper.encode( updateUserProfileDto.getNewPassword() ) );
}
...
Problem
How could I change my mapper interface UserMapper so that i will check both currentPassword and newPassword before it will set the target user.password and will still use PasswordEncoderMapper.encode(password)?
If I try to use expression instead of source and check both currentPassword and newPassword if both have values and then set user.password to newPassword. Otherwise, it will not do anything to user.passwordusing NullValuePropertyMappingStrategy... but it seems it is not allowede to mix expression and NullValuePropertyMappingStrategy.
Thanks!
I would start with following approach
#Mapper(config = MapperConfig.class, componentModel = "spring")
public abstract class UserMapper { // using class instead of interface to be able to inject beans
#Autowired
private PasswordEncoderMapper passwordEncoderMapper;
#Mappings({
// your non-password mappings
})
void updateUserFromDto(UpdateUserProfileDto updateUserProfileDto, #MappingTarget User user);
#AfterMapping
void setPassword(UpdateUserProfileDto updateUserProfileDto, #MappingTarget User user) {
if (updateUserProfileDto.getCurrentPassword() != null && updateUserProfileDto.getNewPassword() != null) {
user.setPassword(passwordEncoderMapper.encode( updateUserProfileDto.getNewPassword()));
}
}
}

DAO instance not working in service class - NullPointerException

In my spring boot project I created a Repository interface (which extends CRUDRepository) and an Entity class of the Table in my DB.
This is my Repo:
#Repository
public interface AuthPaymentDao extends CrudRepository<TFraudCard,String> {
#Query("SELECT t FROM TFraudCard t where t.tokenNumber = (?1)")
TFraudCard findByTokenNumber(String tokenNumber);
}
This is my Entity Class (TOKEN_NUMBER is the primary Key in the TFRAUDCARD TABLE):
#Entity
#Table(name = "TFRAUDCARD")
public class TFraudCard {
#Id
#Column(name="TOKEN_NUMBER")
private String tokenNumber;
#Column(name="TRANSACTIONNUMBER")
private int transactionNumber;
#Column(name="CARDNUMBER")
private int cardNumber;
#Column(name="DATEADDED", insertable = false, updatable = false, nullable = false)
private Timestamp dateAdded;
#Column(name="CALLINGENTITY", nullable = false)
private String callingEntity;
#Column(name="ACCOUNTID")
private String accountId;
#Column(name="ROUTINGNUMBER")
private String routingNumber;
#Column(name="BANKACCOUNTNUMBER")
private String bankAccountNumber;
#Column(name="COMMENTS")
private String comments;
#Column(name="USERID")
private String userId;
#Column(name="REMOVEDATE")
private Timestamp removeDate;
public String getTokenNumber() {
return tokenNumber;
}
public void setTokenNumber(String tokenNumber) {
this.tokenNumber = tokenNumber;
}
public int getTransactionNumber() {
return transactionNumber;
}
public void setTransactionNumber(int transactionNumber) {
this.transactionNumber = transactionNumber;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
public Timestamp getDateAdded() {
return dateAdded;
}
public void setDateAdded(Timestamp dateAdded) {
this.dateAdded = dateAdded;
}
public String getCallingEntity() {
return callingEntity;
}
public void setCallingEntity(String callingEntity) {
this.callingEntity = callingEntity;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getRoutingNumber() {
return routingNumber;
}
public void setRoutingNumber(String routingNumber) {
this.routingNumber = routingNumber;
}
public String getBankAccountNumber() {
return bankAccountNumber;
}
public void setBankAccountNumber(String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getRemoveDate() {
return removeDate;
}
public void setRemoveDate(Timestamp removeDate) {
this.removeDate = removeDate;
}
public TFraudCard() {
super();
}
public TFraudCard(String tokenNumber, int transactionNumber, int cardNumber, Timestamp dateAdded,
String callingEntity, String accountId, String routingNumber, String bankAccountNumber, String comments,
String userId, Timestamp removeDate) {
super();
this.tokenNumber = tokenNumber;
this.transactionNumber = transactionNumber;
this.cardNumber = cardNumber;
this.dateAdded = dateAdded;
this.callingEntity = callingEntity;
this.accountId = accountId;
this.routingNumber = routingNumber;
this.bankAccountNumber = bankAccountNumber;
this.comments = comments;
this.userId = userId;
this.removeDate = removeDate;
}
#Override
public String toString() {
return "TFraudCard [tokenNumber=" + tokenNumber + ", transactionNumber=" + transactionNumber + ", cardNumber="
+ cardNumber + ", dateAdded=" + dateAdded + ", callingEntity=" + callingEntity + ", accountId="
+ accountId + ", routingNumber=" + routingNumber + ", bankAccountNumber=" + bankAccountNumber
+ ", comments=" + comments + ", userId=" + userId + ", removeDate=" + removeDate + "]";
}
}
My Service Class:
Autowiring the DAO instance inside my Service Class:
Implementing the DAO instance inside a Method in the Service Class:
private void fraudCheck(PaymentDetail paymentDetail) throws RegularPaymentBusinessException {
logger.info("INSIDE FRAUD CHECK METHOD");
String pmtInd=paymentDetail.getPmtInd();
logger.info("pmtInd: " + pmtInd);
String tokenizedCardNum=paymentDetail.getTokenizedCardNum();
logger.info("tokenizedCardNum: " + tokenizedCardNum);
if(pmtInd.equalsIgnoreCase(VepsConstants.GIFT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.CREDIT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.DEBIT_CARD_IDENTIFIER)) {
logger.info("INSIDE CARD CHECK");
TFraudCard fraudCard = authPaymentDao.findByTokenNumber(tokenizedCardNum);
logger.info("fraudCard Details: " + fraudCard.toString());
if(fraudCard!=null) {
logger.info("INSIDE EXCEPTION FLOW FOR CARD FRAUD CHECK");
throw new RegularPaymentBusinessException(VepsConstants._9966, VepsConstants._9966_MESSAGE, VepsConstants.FAILURE);
}
}
}
Even though I pass the same token Number (tokenizedCardNumber) in my method as the data in the TOKEN_NUMBER column of my TFRAUDCARD table I still get a NullPointerException when I try to print a toString() of the Entity Object.
Here is the NullPointerException on my cloudFoundry logs (Click on it to see zoomed image) :
I'm providing the DB details in my dev properties file:
I have gone over every scenario in my head for why it breaks but I still can't come up with an answer. I'm using my variable marked with #Id i.e. the Primary Key for my find() method in the Repository.
I'm also adding a #Query annotation just to be even more specific.
It still does not work.

hibernate/Spring/Jpa #oneToMany cascade update

I'm trying to add in the decorator cascade = CascadeType.ALL on the field one to many of my version modele in spring in order to update every hyper parameter when i update my version.Like you can see below.
#Entity
#Table(name = "version")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Version implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "num", nullable = false)
private Integer num;
#Column(name = "creation_date")
private ZonedDateTime creationDate;
#Column(name = "execution_date")
private ZonedDateTime executionDate;
#Column(name = "weights_uri")
private String weightsURI;
#OneToMany(mappedBy = "version", fetch = FetchType.EAGER, orphanRemoval = true)
#JsonIgnoreProperties({"version", "metricsType"})
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<ResultExecution> resultExecutions = new HashSet<>();
#OneToMany(mappedBy = "version", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL)
#JsonIgnoreProperties({"version"})
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<HyperParameter> hyperParameters = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNum() {
return num;
}
public Version num(Integer num) {
this.num = num;
return this;
}
public void setNum(Integer num) {
this.num = num;
}
public ZonedDateTime getCreationDate() {
return creationDate;
}
public Version creationDate(ZonedDateTime creationDate) {
this.creationDate = creationDate;
return this;
}
public void setCreationDate(ZonedDateTime creationDate) {
this.creationDate = creationDate;
}
public ZonedDateTime getExecutionDate() {
return executionDate;
}
public Version executionDate(ZonedDateTime executionDate) {
this.executionDate = executionDate;
return this;
}
public void setExecutionDate(ZonedDateTime executionDate) {
this.executionDate = executionDate;
}
public String getWeightsURI() {
return weightsURI;
}
public Version weightsURI(String weightsURI) {
this.weightsURI = weightsURI;
return this;
}
public void setWeightsURI(String weightsURI) {
this.weightsURI = weightsURI;
}
public Set<ResultExecution> getResultExecutions() {
return resultExecutions;
}
public Version resultExecutions(Set<ResultExecution> resultExecutions) {
this.resultExecutions = resultExecutions;
return this;
}
public Version addResultExecution(ResultExecution resultExecution) {
this.resultExecutions.add(resultExecution);
resultExecution.setVersion(this);
return this;
}
public Version removeResultExecution(ResultExecution resultExecution) {
this.resultExecutions.remove(resultExecution);
resultExecution.setVersion(null);
return this;
}
public void setResultExecutions(Set<ResultExecution> resultExecutions) {
this.resultExecutions = resultExecutions;
}
public Set<HyperParameter> getHyperParameters() {
return hyperParameters;
}
public Version hyperParameters(Set<HyperParameter> hyperParameters) {
this.hyperParameters = hyperParameters;
return this;
}
public Version addHyperParameter(HyperParameter hyperParameter) {
this.hyperParameters.add(hyperParameter);
hyperParameter.setVersion(this);
return this;
}
public Version removeHyperParameter(HyperParameter hyperParameter) {
this.hyperParameters.remove(hyperParameter);
hyperParameter.setVersion(null);
return this;
}
public void setHyperParameters(Set<HyperParameter> hyperParameters) {
this.hyperParameters = hyperParameters;
}
public Set<Data> getData() {
return data;
}
public Version data(Set<Data> data) {
this.data = data;
return this;
}
public Version addData(Data data) {
this.data.add(data);
data.getVersions().add(this);
return this;
}
public Version removeData(Data data) {
this.data.remove(data);
data.getVersions().remove(this);
return this;
}
public void setData(Set<Data> data) {
this.data = data;
}
public ModelConfiguration getModelConfiguration() {
return modelConfiguration;
}
public Version modelConfiguration(ModelConfiguration modelConfiguration) {
this.modelConfiguration = modelConfiguration;
return this;
}
public void setModelConfiguration(ModelConfiguration modelConfiguration) {
this.modelConfiguration = modelConfiguration;
}
// 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;
}
Version version = (Version) o;
if (version.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), version.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "Version{" +
"id=" + getId() +
", num='" + getNum() + "'" +
", creationDate='" + getCreationDate() + "'" +
", executionDate='" + getExecutionDate() + "'" +
", weightsURI='" + getWeightsURI() + "'" +
"}";
}
}
My hyperParameter model looks like this :
#Entity
#Table(name = "hyper_parameter")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class HyperParameter implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "parameter_value", nullable = false)
private String parameterValue;
#ManyToOne(optional = false)
#NotNull
#JsonIgnoreProperties({"resultExecutions", "hyperParameters", "data", "modelConfiguration"})
private Version version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getParameterValue() {
return parameterValue;
}
public HyperParameter parameterValue(String parameterValue) {
this.parameterValue = parameterValue;
return this;
}
public void setParameterValue(String parameterValue) {
this.parameterValue = parameterValue;
}
public Version getVersion() {
return version;
}
public HyperParameter version(Version version) {
this.version = version;
return this;
}
public void setVersion(Version version) {
this.version = version;
}
public HyperParameterType getHyperParameterType() {
return hyperParameterType;
}
public HyperParameter hyperParameterType(HyperParameterType hyperParameterType) {
this.hyperParameterType = hyperParameterType;
return this;
}
public void setHyperParameterType(HyperParameterType hyperParameterType) {
this.hyperParameterType = hyperParameterType;
}
// 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;
}
HyperParameter hyperParameter = (HyperParameter) o;
if (hyperParameter.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), hyperParameter.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
#Override
public String toString() {
return "HyperParameter{" +
"id=" + getId() +
", parameterValue='" + getParameterValue() + "'" +
"}";
}
}
I update a json and try a put with it .I change the value of the field parametervalue from 2 to 3 .
{
"id": 1,
"num": 1,
"creationDate": "2017-05-11T00:00:00+02:00",
"executionDate": null,
"weightsURI": "tests/scripts/sequential/weights/weights_le_net_5.h5py",
"resultExecutions": [
{
"id": 1,
"metricValues": "",
"executionType": "TRAIN",
"numPrediction": null
},
{
"id": 2,
"metricValues": "",
"executionType": "TRAIN",
"numPrediction": null
}
],
"hyperParameters": [
{
"id": 1,
"parameterValue": "2",
"hyperParameterType": {
"id": 1,
"name": "epochs",
"parameterType": "INTEGER",
"parameterDefaultValue": "0",
"isRequired": true
}
},
{
"id": 2,
"parameterValue": "32",
"hyperParameterType": {
"id": 2,
"name": "batch_size",
"parameterType": "INTEGER",
"parameterDefaultValue": "32",
"isRequired": true
}
}
],
"modelConfiguration": {
"id": 1,
"name": "Modele LeNet5",
"creationDate": "2017-05-11T00:00:00+02:00",
"updateDate": "2017-05-11T00:00:00+02:00",
"saveURI": "tests/scripts/sequential/models/le_net_5.json"
}
}
But when i do i got a 500 internal serveur error and stack trace like the one bellow about a null constraint violation.
<!-- What do you expect the result to be? -->
<!-- What is the actual result you get? (Please include any errors.) -->
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526)
[1:59]
t org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:75)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 153 common frames omitted
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [com.saagie.picsaagie2017_frontend.domain.HyperParameter] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='can not be null ', propertyPath=version, rootBeanClass=class com.saagie.picsaagie2017_frontend.domain.HyperParameter, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
How can i update my hyperParameters when i update my version whitout getting this error.
Use the #PreUpdate and #PrePersist callbacks in the HyperParameter class like so:
#PreUpdate
#PrePersist
public void setChildObjects() {
if (getVersions() != null)
{
for (Version version : getVersions())
{
version.setHyperParameters (this);
}
}
}
Refer to this for more information : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html#tutorial-associations-usingbidir
Both solution actually work i had a second error because of what is discussed in that topic : Spring data rest one to many cascade all . I just had to add #JsonManagedReference and #JsonBackReference because i had marshalling problem on the reference of version when i tried to update my HyperParameters in cascade.
You just have validation error. You try to put interpolatedMessage with null value. Ok but first remove #NotNull annotation on this field.

Hibernate - #IdClass #ManyToOne - Primary key is also Foreign key

Im having a little problem when Saving an Entity, (this problem only occurs when saving, im saying that because I can get execute the normal operation when findAll)
As I said, when saving the entity (repository.save(entity)), Im getting the follow exception
//org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Integer' to required type 'net.lapasta.model.entity.Produto' for property 'produto';
//nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.Integer] to required type [net.lapasta.model.entity.Produto] for property 'produto': no matching editors or conversion strategy found
My entity is:
#Entity
#IdClass(ProdutoEstoqueRegra.PrimaryKey.class)
#Table(name = "PRODUTO_ESTOQUE_REGRA")
public class ProdutoEstoqueRegra extends BaseEntity
{
private static final long serialVersionUID = 2977957269715314234L;
public static class PrimaryKey extends BaseEntity
{
private static final long serialVersionUID = 5136771432344094321L;
private Produto produto;
private Produto produtoEstoque;
public PrimaryKey()
{
}
public PrimaryKey(Produto produto, Produto produtoEstoque)
{
this.produto = produto;
this.produtoEstoque = produtoEstoque;
}
public Produto getProduto()
{
return produto;
}
public void setProduto(Produto produto)
{
this.produto = produto;
}
public Produto getProdutoEstoque()
{
return produtoEstoque;
}
public void setProdutoEstoque(Produto produtoEstoque)
{
this.produtoEstoque = produtoEstoque;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result += prime * result + (produto == null ? 0 : produto.getProdutoId() == null ? 0 : produto.getProdutoId().hashCode());
result += prime * result + (produtoEstoque == null ? 0 : produtoEstoque.getProdutoId() == null ? 0 : produtoEstoque.getProdutoId().hashCode());
return result;
}
#Override
public boolean equals(Object object)
{
if(this == object)
{
return true;
}
if(!(object instanceof ProdutoEstoqueRegra))
{
return false;
}
ProdutoEstoqueRegra produtoEstoqueRegra = (ProdutoEstoqueRegra) object;
if(produto == null)
{
if(produtoEstoqueRegra.getProduto() != null)
{
return false;
}
}
else if(produto.getProdutoId() == null)
{
if(produtoEstoqueRegra.getProduto().getProdutoId() != null)
{
return false;
}
}
else if(!produto.equals(produtoEstoqueRegra.getProduto()))
{
return false;
}
if(produtoEstoque == null)
{
if(produtoEstoqueRegra.getProdutoEstoque() != null)
{
return false;
}
}
else if(produtoEstoque.getProdutoId() == null)
{
if(produtoEstoqueRegra.getProdutoEstoque().getProdutoId() != null)
{
return false;
}
}
else if(!produtoEstoque.getProdutoId().equals(produtoEstoqueRegra.getProdutoEstoque().getProdutoId()))
{
return false;
}
return true;
}
}
#Id
#ManyToOne
#JoinColumn(name = "ID_PRODUTO")
private Produto produto;
#Id
#ManyToOne
#JoinColumn(name = "ID_PRODUTO_ESTOQUE")
private Produto produtoEstoque;
#Column(name = "QUANTIDADE")
private BigDecimal quantidade;
}
I just got the same problem...and i solved it by myself last :)
In your case, i assume Produto's id type is Long, u need change your PrimaryKey class like following:
public static class PrimaryKey extends BaseEntity
{
private static final long serialVersionUID = 5136771432344094321L;
private Long produto;
private Long produtoEstoque;
public PrimaryKey()
{
}
public PrimaryKey(Long produto, Long produtoEstoque)
{
this.produto = produto;
this.produtoEstoque = produtoEstoque;
}
public Long getProduto()
{
return produto;
}
public void setProduto(Long produto)
{
this.produto = produto;
}
public Long getProdutoEstoque()
{
return produtoEstoque;
}
public void setProdutoEstoque(Long produtoEstoque)
{
this.produtoEstoque = produtoEstoque;
}
//...
}

Spring merge - java.sql.SQLException: Invalid column index

I have a table that has 2 columns that create the primary key:
#Entity
#Table(name="DW.DW$SF$MONTHLY")
public class DWMonthly implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId DWMonthlyPK monthlyPK;
#Id
#Column(name="AID", insertable=false, updatable=false)
#IndexColumn(name="DW$SF$MONTHLY_PK")
private Long id;
#Column(name="CHNG_STATUS")
private BigDecimal chngStatus;
#Column(name="NAR")
private BigDecimal nar;
#Column(name="SF_AMID")
private String sfAmid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="N_DATE", insertable=false, updatable=false)
#IndexColumn(name="DW$SF$MONTHLY_PK")
private Date nDate;
public DWMonthly() {}
public DWMonthly(Long id, String sfAmid, Date nDate) {
this.id = id;
this.sfAmid = sfAmid;
this.nDate = nDate;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getChngStatus() {
return this.chngStatus;
}
public void setChngStatus(BigDecimal chngStatus) {
this.chngStatus = chngStatus;
}
public BigDecimal getNar() {
return this.nar;
}
public void setNar(BigDecimal nar) {
this.nar = nar;
}
public String getSfAmid() {
return this.sfAmid;
}
public void setSfAmid(String sfAmid) {
this.sfAmid = sfAmid;
}
public Date getNDate() {
return nDate;
}
public void setNarDate(Date nDate) {
this.nDate = nDate;
}
}
Embeddable table:
#Embeddable
public class DWMonthlyPK implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="AID")
private long aid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="N_DATE")
private java.util.Date nDate;
public DWMonthlyPK() {
}
public long getAid() {
return this.aid;
}
public void setAid(long aid) {
this.aid = aid;
}
public java.util.Date getNDate() {
return this.narDate;
}
public void setNDate(java.util.Date nDate) {
this.nDate = nDate;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof DWMonthlyPK)) {
return false;
}
DWMonthlyPK castOther = (DWMonthlyPK)other;
return
(this.aid == castOther.aid)
&& this.nDate.equals(castOther.nDate);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + ((int) (this.aid ^ (this.aid >>> 32)));
hash = hash * prime + this.nDate.hashCode();
return hash;
}
}
Find the record and update:
#Repository(value="MonthlyNarDaoRepository")
#Import({JpaConfigurationImpl.class})
#Transactional(value="dwTransactionManager",readOnly = true, propagation=Propagation.REQUIRES_NEW)
public class MonthlyNarDaoImpl implements MonthlyNarDao {
#Override
#Transactional(value="dwTransactionManager")
public void findAndUpdateMonhtlyByAccountId(Map<DWAccount, UpsertResult> accountsLoadedResult) {
for (DWAccount dwAccount : accountsLoadedResult.keySet()){
try {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<DWMonthlyNar> criteriaQuery = criteriaBuilder.createQuery(DWMonthlyNar.class);
Root<DWMonthlyNar> root = criteriaQuery.from(DWMonthlyNar.class);
Predicate p = criteriaBuilder.conjunction();
p = criteriaBuilder.and(criteriaBuilder.equal(root.get("id"), dwAccount.getId()), criteriaBuilder.notEqual(root.get("nar").as(BigDecimal.class), new BigDecimal(0.0)), criteriaBuilder.isNull(root.get("sfAmid")));
criteriaQuery.select(root);
criteriaQuery.where(p);
for (DWMonthlyNar dwMonthlyNar : this.entityManager.createQuery(criteriaQuery).getResultList()){
if (dwMonthlyNar.getSfAmid()==null || !dwMonthlyNar.getSfAmid().equals(accountsLoadedResult.get(dwAccount).getId())){
dwMonthlyNar.setSfAmid(accountsLoadedResult.get(dwAccount).getId());
this.entityManager.merge(dwMonthlyNar);
}
}
} catch (Exception e) {
logger.error("MonthlyNarDaoImpl.findAndUpdateMonhtlyNarByAccountId(): " + e.getMessage());
}
}
}
}
Error:
Hibernate: update DW.DW$SF$MONTHLY set CHNG_STATUS=?, NAR=?,
SF_AMID=? where AID=? and NAR_DATE=? 16:04:58.864 [main] DEBUG
o.h.e.jdbc.spi.SqlExceptionHelper - Invalid column index [n/a]
java.sql.SQLException: Invalid column index

Resources