Binding errors with list - java

I generated a form:
<form:form action="${contextPath}/draw/constraints.do" method="post" modelAttribute="order"> <c:forEach items="${order.myDrawsAsArray}" var="draw" varStatus="status">
<label class="radio-inline"><form:radiobutton path="myDrawsAsArray[${status.index}].readable" value="true" /> yes</label>
<label class="radio-inline"><form:radiobutton path="myDrawsAsArray[${status.index}].readable" value="false" /> no</label>
</c:forEach></form:form>
When I submit it to update my entities, I got the following exception:
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.beans.InvalidPropertyException: Invalid property
'myDrawsAsArray[0]' of bean class [com.entity.Order3d]: Getter
for property 'myDrawsAsArray' threw exception; nested exception is
java.lang.reflect.InvocationTargetException
org.springframework.beans.InvalidPropertyException: Invalid property
'myDrawsAsArray[0]' of bean class [com.entity.Order3d]: Getter
for property 'myDrawsAsArray' threw exception; nested exception is
java.lang.reflect.InvocationTargetException
java.lang.reflect.InvocationTargetException
java.lang.NullPointerException
com.entity.Order3d.getMyDrawsAsArray(Order3d.java:121)
My controller is like this:
#Controller
#RequestMapping("/draw")
public class PrintingController {
#RequestMapping(value="/constraints")
public String constraints(
#ModelAttribute Order3d order,
#RequestParam("order") int id,
#RequestParam(value="save", required=false) String save,
Model m) {
Session s=HibernateUtils.getSessionFactory().openSession();
if(save!=null) {
System.out.println(order.getMyDraws());
for(DrawFile df : order.getMyDraws())
s.saveOrUpdate(df);
}
Order3d o=(Order3d)s.createCriteria(Order3d.class).add(Restrictions.eq("id", id)).uniqueResult();
m.addAttribute("order", o);
s.close();
return "3dconstraints";
}
}
I also post my entities if you need them:
#Entity
#Table (name="order3d")
public class Order3d implements Serializable {
private static final long serialVersionUID = -2241346447352903470L;
public enum State {DEMAND, ESTIMATED, PAYED, PENDING, PRODUCED, SENT, DELIVERED};
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name="id")
private int id;
#OneToMany(mappedBy="order3d", fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private Set<DrawFile> myDraws;
public Set<DrawFile> getMyDraws() {
return myDraws;
}
public List<DrawFile> getMyDrawsAsList() {
return new ArrayList<DrawFile>(myDraws);
}
public Object[] getMyDrawsAsArray() {
return myDraws.toArray(); //line 121
}
//other getters & setters
public Order3d() {}
}
#Entity
#Table (name="draw", uniqueConstraints=#UniqueConstraint(columnNames="hashname"))
public class DrawFile implements Serializable {
private static final long serialVersionUID = -9024754876558087847L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name="id")
private int id;
#Column (name="hashname", columnDefinition="CHAR(64)")
private String hashname;
#Column (name="filename")
private String filename="";
#Column (name="readable", columnDefinition = "BIT", length = 1)
private Boolean readable;
//getters & setters
public DrawFile() {}
}
I searched on the web but I didn't find a solution. Any idea?

How about try adding getter/setter to the fields in both Order3d and DrawFile classes?
The getters and setters must match field name, if the field is
List<DrawFile> myDraws;
then the getter/setter must be: (it cannot be getMyDrawsAsList())
public List<DrawFile> getMyDraws() {
return myDraws;
}
public void setMyDraws(List<DrawFile> myDraws) {
this.myDraws = myDraws;
}

Related

Field error in object 'titulo' on field 'status': rejected value [Pendente];

I am trying to learn Spring Framework on the go. During runtime I get following stacktrace:
Validation failed for object='title'. Error count: 1
org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'title' on field 'status': rejected value
[Received];
I noticed that the problem is in the status, which is formatted by enum, but I can't any error.
My class Controller:
#Controller
#RequestMapping("/titles")
public class registerTitleController {
#RequestMapping("/title")
public String new() {
return "RegisterTitle";
}
#Autowired
private Titles titles;
#RequestMapping(method=RequestMethod.POST)
public String saveIn(Title title) {
titles.save(title);
return "RegisterTitle";
}
}
My class entity
#Entity
public class Title {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cod;
private String description;
#DateTimeFormat(pattern="dd/MM/yyyy")
#Temporal(TemporalType.DATE)
private Date dateV;
private BigDecimal val;
#Enumerated(value = EnumType.STRING)
private StatusTitle status;
//other accessor methods
My class enum
public enum StatusTitle {
PENDING("Pending"),
RECEIVED("Received");
private String description;
private StatusTitulo(String descricao){
this.description = description;
}
public String getDescription() {
return description;
}
}
My system work without the status of the attribute.
Can someone point out what is wrong? Your help will be much appreciated.
You probably are sending "Received", but you need to send "RECEIVED" string to properly convert to the ENUM by default.

ORM in Morphia for a Nested Class

My Json document in the Morphia DB looks like this -
{
"_id" : ObjectId("58fcdf7e"),
"status" : "ACTIVE",
"user" : {
"id" : NumberLong(228),
"email" : "testing#domian.com"
}
}
I have created a Java class for this collection which looks like this -
#Entity("member_offer")
public class MemberOffer {
#Id
private ObjectId objectId;
#Property("status")
private String status;
#Embedded("user")
private UserDetail user;
#Embedded
class UserDetail {
#Property("id")
public long memberId;
#Property("email")
public String email;
UserDetail() {
}
}
public ObjectId getObjectId() {
return objectId;
}
public void setObjectId(ObjectId objectId) {
this.objectId = objectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public UserDetail getUser() {
return user;
}
public void setUser(UserDetail user) {
this.user = user;
}
}
Now when I am trying to fetch the data I am getting this exception -
java.lang.RuntimeException:
org.mongodb.morphia.mapping.MappingException: No usable constructor
for vo.MemberSubscription$UserDetail
Caused by: org.mongodb.morphia.mapping.MappingException: No usable
constructor for vo.MemberSubscription$UserDetail
Caused by: org.mongodb.morphia.mapping.MappingException: No usable constructor for vo.MemberSubscription$UserDetail
Caused by: java.lang.NoSuchMethodException: vo.MemberSubscription$UserDetail.()
Any idea how I can resolve this issue? I want UserDetail to be nested class only, I know if I create it as an independent class this error can be resolved. But my question here is can something like this (having nested class) can be achieved in Morphia?
Also if there is some fundamental flaw in my design please educate me about it.
You should try to use public modifier for the constructor, also make UserDetail (inner class) is static.

Spring HATEOAS with nested resources and JsonView filtering

I am trying to add HATEOAS links with Resource<>, while also filtering with #JsonView. However, I don't know how to add the links to nested objects.
In the project on on Github, I've expanded on this project (adding in the open pull request to make it work without nested resources), adding the "Character" entity which has a nested User.
When accessing the ~/characters/resource-filtered route, it is expected that the nested User "player" appear with the firstNm and bioDetails fields, and with Spring generated links to itself, but without the userId and lastNm fields.
I have the filtering working correctly, but I cannot find an example of nested resources which fits with the ResourceAssembler paradigm. It appears to be necessary to use a ResourceAssembler to make #JsonView work.
Any help reconciling these two concepts would be appreciated. If you can crack it entirely, consider sending me a pull request.
User.java
//package and imports
...
public class User implements Serializable {
#JsonView(UserView.Detail.class)
private Long userId;
#JsonView({ UserView.Summary.class, CharacterView.Summary.class })
private String bioDetails;
#JsonView({ UserView.Summary.class, CharacterView.Summary.class })
private String firstNm;
#JsonView({ UserView.Detail.class, CharacterView.Detail.class })
private String lastNm;
public User(Long userId, String firstNm, String lastNm) {
this.userId = userId;
this.firstNm = firstNm;
this.lastNm = lastNm;
}
public User(Long userId) {
this.userId = userId;
}
...
// getters and setters
...
}
CharacterModel.java
//package and imports
...
#Entity
public class CharacterModel implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(CharacterView.Summary.class)
private Long characterId;
#JsonView(CharacterView.Detail.class)
private String biography;
#JsonView(CharacterView.Summary.class)
private String name;
#JsonView(CharacterView.Summary.class)
private User player;
public CharacterModel(Long characterId, String name, String biography, User player) {
this.characterId = characterId;
this.name = name;
this.biography = biography;
this.player = player;
}
public CharacterModel(Long characterId) {
this.characterId = characterId;
}
...
// getters and setters
...
}
CharacterController.java
//package and imports
...
#RestController
#RequestMapping("/characters")
public class CharacterController {
#Autowired
private CharacterResourceAssembler characterResourceAssembler;
...
#JsonView(CharacterView.Summary.class)
#RequestMapping(value = "/resource-filtered", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public Resource<CharacterModel> getFilteredCharacterWithResource() {
CharacterModel model = new CharacterModel(1L, "TEST NAME", "TEST BIOGRAPHY", new User(1L, "Fred", "Flintstone"));
return characterResourceAssembler.toResource(model);
}
...
}
CharacterResourceAssembler.java
//package and imports
...
#Component
public class CharacterResourceAssembler implements ResourceAssembler<CharacterModel, Resource<CharacterModel>>{
#Override
public Resource<CharacterModel> toResource(CharacterModel user) {
Resource<CharacterModel> resource = new Resource<CharacterModel>(user);
resource.add(linkTo(CharacterController.class).withSelfRel());
return resource;
}
}

How can I fixed java.lang.IllegalArgumentException which need correct entity id in jpa

I have got this exception :
java.lang.IllegalArgumentException: Provided id of the wrong type for class com.netizenbd.domain.staff.StaffRegiAddressInfo. Expected: class java.lang.Integer, got class com.netizenbd.domain.staff.StaffRegiAddressInfo
when I want to delete StaffRegiAddressInfo object,
I have used manyToOne mapping in this Entity.
Here are code flow:
view code:
<p:dataGrid value="#{staffUpdateMB.addressInfoList}"
id="addesList" var="address" columns="1" layout="grid"
styleClass="NoPadding NoIndent">
<p:panel>
<div
class="Container100 Responsive100 TealGreenBack BordRad5 White NoIndent">
<div class="Container50 Responsive100 NoIndent">
<h:outputText value="#{address.addressType}" styleClass="Fs22" />
</div>
<div class="Container50 Responsive100 TexAlRight NoIndent">
<p:commandButton class="TealGreenBack" icon="fa fa-edit"
onstart="PF('staffAddressEditDialog').show()">
<f:setPropertyActionListener value="#{address}"
target="#{staffUpdateMB.beanAddressInfo}"/>
</p:commandButton>
<p:commandButton styleClass="RedButton RaisedButton"
action="#{staffUpdateMB.removeAddress}" icon="fa fa-trash-o"
update="addesList" ajax="false">
<f:setPropertyActionListener value="#{address}"
target="#{staffUpdateMB.beanAddressInfo}" />
</p:commandButton>
</div>
</div>
... .... ....
</p:panel>
</p:dataGrid>
Here is ManageBean staffUpdateMB removeAddress(); method:
public void removeAddress() {
try {
System.out.println("Address ID :"+this.beanAddressInfo.getAddressID());
StaffRegiAddressInfo address=addressInfoDao.findById(this.beanAddressInfo.getAddressID());
System.out.println("Address ID :"+address.getAddressID());
addressInfoDao.remove(address);
context.addMessage(null, new FacesMessage(msg.getPropValue("deleteSuccess")));
} catch (Exception e) {
context.addMessage(null, new FacesMessage(msg.getPropValue("deleteError")));
logger.error("This is error : " + e);
logger.fatal("This is fatal : " + e);
}
}
Here is addressInfoDao which extend EntityDao:
public interface StaffRegiAddressInfoDao extends EntityDao<StaffRegiAddressInfo>{
}
public interface EntityDao<E> {
void persist(E e) throws Exception;
void merge(E e) throws Exception;
void remove(Object id) throws Exception;
}
Here is the implementation EntityDao:
public class EntityService<E> implements EntityDao<E> {
#PersistenceContext(unitName="persistenceUnit")
protected EntityManager entityManager;
protected E instance;
private Class<E> entityClass;
#Transactional
public void persist(E e) throws HibernateException{
getEntityManager().persist(e);
}
#Transactional
public void merge(E e) throws HibernateException{
getEntityManager().merge(e);
}
#Transactional
public void remove(Object id) throws Exception{
getEntityManager().remove((E)getEntityManager().find(getEntityClass(), id));
getEntityManager().flush();
}
And Here is the Exception below:
Address ID :33
Address ID :33
01/Mar/2016 18:14:05,440- StaffUpdateMB: This is error : java.lang.IllegalArgumentException: Provided id of the wrong type for class com.netizenbd.domain.staff.StaffRegiAddressInfo. Expected: class java.lang.Integer, got class com.netizenbd.domain.staff.StaffRegiAddressInfo
01/Mar/2016 18:44:57,091- StaffUpdateMB: This is fatal : java.lang.IllegalArgumentException: Provided id of the wrong type for class com.netizenbd.domain.staff.StaffRegiAddressInfo. Expected: class java.lang.Integer, got class com.netizenbd.domain.staff.StaffRegiAddressInfo
And Here also Entities:
#Entity
#Table(name="staffregi_addressinfo")
public class StaffRegiAddressInfo implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="addressID")
private int addressID;
#Column(name="addressType")
private String addressType;
#Column(name="village")
private String village;
#Column(name="postOffice")
private String postOffice;
#Column(name="postalCode")
private String postalCode;
#Column(name="thanaName")
private String thanaName;
#Column(name="districtName")
private String districtName;
#Column(name="divisionName")
private String divisionName;
#Column(name="countryName")
private String countryName;
#Column(name="instituteID")
private String instituteID;
#Column(name="recordNote")
private String recordNote;
#Column(name="userExecuted")
private String userExecuted;
#Column(name="dateExecuted")
#Temporal(TemporalType.TIMESTAMP)
private Date dateExecuted;
#Column(name="ipExecuted")
private String ipExecuted;
#Column(name="recordStatus")
private int recordStatus;
#ManyToOne
#JoinColumn(name="staffID")
private StaffRegiBasicInfo basicInfoAddress;
//setter, getter also...
}
#Entity
#Table(name="staffregi_basicinfo")
public class StaffRegiBasicInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="staffID")
private String staffID;
#Column(name="staffName")
private String staffName;
#OneToMany(cascade=CascadeType.ALL, mappedBy="basicInfoAddress")
#LazyCollection(LazyCollectionOption.FALSE)
private Set<StaffRegiAddressInfo> addressInfoList;
//setter, getter also
}
try to change in ManageBean staffUpdateMB removeAddress(); method:
addressInfoDao.remove(address);
by
addressInfoDao.remove(address.getAddressID());
in your DAO you have:
public void remove(Object id);
but you are passing an object, not ID

EM can not resolve configured mapping [EclipseLink-197]

I have a problem with resolving entities during entity manager startup.
Now it falls with following error:
Exception [EclipseLink-197] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException Exception
Description: The mapping [an_div] is not the appropriate type for this
descriptor Mapping:
org.eclipse.persistence.mappings.DirectToFieldMapping[an_div-->div]
Descriptor:
EISDescriptor(com.cloudyle.paasplus.api.fhir.model.dstu2.composite.NarrativeDt
--> [DatabaseTable(DATATYPE), DatabaseTable(NARRATIVEDT)])
The abstract class configuration:
#MappedSuperclass
#UuidGenerator(name = "UUID_GEN_SQL")
#NoSql(dataFormat = DataFormatType.MAPPED)
public abstract class AbstractBaseResource
{
private static final long serialVersionUID = -1212459053211153257L;
protected static final Logger logger = LoggerFactory.getLogger(AbstractBaseResource.class);
public static final String DELIMITER = ", ";
#Id
#GeneratedValue(generator = "UUID_GEN_SQL")
#Column(name = "_id")
private String id;
#Version
#Field(name = "object_version")
private Long objectVersion;
#Embedded
#Field(name = "text")
private NarrativeDt text;
// getter and setter
// ...
}
A simple entity class:
#Entity
#NoSql(dataFormat = DataFormatType.MAPPED)
public class Account extends AbstractBaseResource
{
#Field(name = "name")
private String an_name;
// other fields + getter and setter
// ...
}
The embbedable entity where the problem could be:
#Embeddable
#NoSql(dataFormat = DataFormatType.MAPPED)
#Customizer(DtChildCustomizer.class)
public class NarrativeDt extends Datatype
{
#Field(name = "status")
private String an_status;
#Field(name = "div")
private String an_div;
// getter and setter
// ...
}
The extended embbedable:
#Embeddable
#NoSql(dataFormat = DataFormatType.MAPPED)
#Customizer(DtParentCustomizer.class)
public abstract class Datatype implements IDatatype, Serializable
{
#Field(name = "element_specific_id")
private String an_elementSpecificId;
// getter and setter
// ...
}
The child customizer:
public class DtChildCustomizer implements Serializable, DescriptorCustomizer
{
#Override
public void customize(final ClassDescriptor descriptor)
{
descriptor.getInheritancePolicy().setParentClass(Datatype.class);
}
}
And the parent customizer:
public class DtParentCustomizer implements Serializable, DescriptorCustomizer
{
#Override
public void customize(final ClassDescriptor descriptor) throws Exception
{
descriptor.getInheritancePolicy().setSingleTableStrategy();
final DatabaseField indicatorField = new DatabaseField();
indicatorField.setName("classType");
indicatorField.setLength(255);
indicatorField.setType(java.lang.String.class);
descriptor.getInheritancePolicy().setClassIndicatorField(indicatorField);
descriptor.getInheritancePolicy().useClassNameAsIndicator();
}
}
I can not understand why eclispeLink have a problem to resolve simple mapping an_div->div.
All suggestion will be appreciated, I already spent too much time working on it. I can not see the mapping problem :(
Kind regards

Categories