Can't bind a nested property along a BeanFieldGroup - java

I'm developing a vaadin application and now have the following trouble.
I'm trying to bind a nested property along BeanFieldGroup.
MyEntity Class
#Entity
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private MyEntityPK id;
//Others Property
public MyEntityPK getId() {
return this.id;
}
public void setId(MyEntityPK id) {
this.id = id;
}
}
MyEntityPK Class
#Embeddable
public class MyEntityPK implements Serializable {
#Column(name="CD_VARIABILE")
private String cdVariabile;
public String getCdVariabile() {
return this.cdVariabile;
}
public void setCdVariabile(String cdVariabile) {
this.cdVariabile = cdVariabile;
}
}
MyVaadinPanel
private BeanFieldGroup<MyEntity> binder;
binder = new BeanFieldGroup<MyEntity>(MyEntity.class);
binder.setItemDataSource(new BeanItem<MyEntity>(new MyEntity()));
variabileBinder.bind(new TextField(), "id.cdVariabile");
When, I try to bind the property "id.cdVariabile" to TextFiel, I get the following error:
Caused by: com.vaadin.data.util.MethodProperty$MethodException
at com.vaadin.data.util.NestedMethodProperty.getValue(NestedMethodProperty.java:205)
at com.vaadin.data.util.TransactionalPropertyWrapper.getValue(TransactionalPropertyWrapper.java:73)
at com.vaadin.ui.AbstractField.getDataSourceValue(AbstractField.java:299)
at com.vaadin.ui.AbstractField.setPropertyDataSource(AbstractField.java:629)
... 48 more
Caused by: java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.vaadin.data.util.NestedMethodProperty.getValue(NestedMethodProperty.java:201)
... 51 more
Where am I wrong ?

Looks like when you create your entity in binder.setItemDataSource(new BeanItem<MyEntity>(new MyEntity())); its id is null, hence trying to rerieve id.cdVariabile would result in NPE.
Try adding a PK:
BeanFieldGroup<MyEntity> binder;
binder = new BeanFieldGroup<MyEntity>(MyEntity.class);
MyEntity myEntity = new MyEntity();
myEntity.setId(new MyEntityPK());
binder.setItemDataSource(new BeanItem<MyEntity>(myEntity));
binder.bind(new TextField(), "id.cdVariabile");

Related

NullPointerException in dao.save method

I'm learning Spring framework and using DAO. When I use my dao.save method to persist new object to database I got NullPointerException. How can i solve this problem and correctly persist/delete/update objects to databases ? Thanks.
Entity Coffee.class :
#Entity
public class Coffee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String coffeeName;
private Integer costForCup;
private boolean isDisabled;
#OneToMany(mappedBy = "coffee")
private Set<Coffee> coffee;
public Coffee() {}
public Coffee(String coffeeName, Integer costForCup, boolean isDisabled) {
this.coffeeName = coffeeName;
this.costForCup = costForCup;
this.isDisabled = isDisabled;
}
*getters and setters*
CoffeeDAO :
public interface CoffeeDAO {
public Coffee findById(Long id);
public List<Coffee> findAll();
public void createCoffee(Coffee coffee);
}
CoffeeDAOImpl :
public class CoffeeImplementation implements CoffeeDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory){
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
***
#Override
#Transactional
public void createCoffee(Coffee coffee) {
hibernateTemplate.save(coffee);
}
}
OrderBean.class :
#ManagedBean
#SessionScoped
public class OrderBean {
#Autowired
private CoffeeDAO coffeeDAO;
public boolean createCoffee(){
Coffee coffee = new Coffee("Кофе", 4, true);
System.out.println(coffee.getCoffeeName()+" " + coffee.getCostForCup() + " " + coffee.isDisabled());
coffeeDAO.createCoffee(coffee);
return true;
}
Error logs:
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 32 more
Caused by: java.lang.NullPointerException
at javacoff.beans.OrderBean.createCoffee(OrderBean.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:329)
at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:342)
at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 33 more
Solve my problem with SpringBeanAutowiringSupport in my managed bean:public class OrderBean extends SpringBeanAutowiringSupport.

Why "alter table drop constraint" is executed before running table creation DDL with HSQLDB

I intended to make use of Spring 4 and Hibernate with HSQLDB to create a in memory database with the assumption that each word has exactly one part of speech just for testing purpose.
I have two entity classes:
public class Word {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String word;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="PARTOFSPEECH_ID", insertable=false,updatable=false)
private PartOfSpeech partOfSpeech;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public PartOfSpeech getPartOfSpeech() {
return partOfSpeech;
}
public void setPartOfSpeech(PartOfSpeech partOfSpeech) {
this.partOfSpeech = partOfSpeech;
}
}
and
public class PartOfSpeech {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String partOfSpeech;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPartOfSpeech() {
return partOfSpeech;
}
public void setPartOfSpeech(String partOfSpeech) {
this.partOfSpeech = partOfSpeech;
}
}
With the code above I run the Spring with Hibernate and saw a very strange WARN:
Hibernate: alter table Word drop constraint FKp318rmy36es1v4gqwr8nkaxbs
Sep 01, 2017 8:42:09 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
...
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: PUBLIC.WORD
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.SchemaManager.getUserTable(Unknown Source)
at org.hsqldb.ParserDDL.compileAlterTable(Unknown Source)
at org.hsqldb.ParserDDL.compileAlter(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 111 more
I just can not understand why when the #ManyToOne and #JoinColumn annotations are added to the Word entity, the first SQL statement executed by the hibernate is alter table Word drop constraint out of my expectation :(
So anyone can help on this? How to remove the alter table pre-statement so that the obnoxious WARN stack trace disappear?

Hibernate: Facing "broken column mapping for id" using composite key referenced in another entity

I'm facing problem in creating one to one mapping in Hibernate. Following is how i'm trying to achieve it.
Following is my super class for SysEntity
#MappedSuperclass
public class BaseSysEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name="sysupdate")
private Date sysupdate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getSysupdate() {
return sysupdate;
}
public void setSysupdate(Date sysupdate) {
this.sysupdate = sysupdate;
}
}
Following class is the entity which will create oneToOne relation ship with "Project"
#Entity
#Table(name="sysproject")
public class SysProject extends BaseSysEntity implements Serializable {
#OneToOne(optional=true, fetch= FetchType.LAZY)
#PrimaryKeyJoinColumns({
#PrimaryKeyJoinColumn(name="sysClientId", referencedColumnName="sysClientId"),
#PrimaryKeyJoinColumn(name="pProject", referencedColumnName="pProject")
})
private Project project;
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
Following is Project class:
#Entity
#Table(name = "tproject")
public class Project {
#EmbeddedId
private ProjectID id; // It contains sysClientId and pProject as primary key
#OneToOne(optional=true, mappedBy="project")
private SysProject SysProject;
}
ProjectID Class:
#Embeddable
public class ProjectID implements Serializable{
#Column(name="pProject")
private String project;
#Column(name="sysClientId")
private String sysClientId;
public String getProject() {
return project;
}
public ProjectID(){
this.sysClientId="0";
}
public ProjectID(Integer number){
this();
this.project = number.toString();
}
public void setProject(String project) {
this.project = project;
}
public String getSysClientId() {
return sysClientId;
}
public void setSysClientId(String sysClientId) {
this.sysClientId = sysClientId;
}
}
Exception which i'm getting:
Caused by: org.hibernate.MappingException: broken column mapping for: SysProject.id of: com.spin.integration.dto.Project
at org.hibernate.persister.entity.AbstractPropertyMapping.initPropertyPaths(AbstractPropertyMapping.java:178)
at org.hibernate.persister.entity.AbstractPropertyMapping.initIdentifierPropertyPaths(AbstractPropertyMapping.java:249)
at org.hibernate.persister.entity.AbstractPropertyMapping.initPropertyPaths(AbstractPropertyMapping.java:222)
at org.hibernate.persister.entity.AbstractEntityPersister.initOrdinaryPropertyPaths(AbstractEntityPersister.java:2434)
at org.hibernate.persister.entity.AbstractEntityPersister.initPropertyPaths(AbstractEntityPersister.java:2471)
at org.hibernate.persister.entity.AbstractEntityPersister.postConstruct(AbstractEntityPersister.java:3766)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:451)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:386)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 18 more
NOTE: This oneToOne mapping is not present at database level (Unfortunately i can't make changes to database).
You can check this solution its working :
One Id of composite key to be referenced in another entity
he's facing the same issue
#OneToOne(optional=true, fetch= FetchType.LAZY)
#JoinColumns({
#JoinColumn(name="sysClientId", referencedColumnName="sysClientId"),
#JoinColumn(name="pProject", referencedColumnName="pProject")
})
Instead of using #PrimaryKeyJoinColumns I had to use #JoinColumns.

Spring BeanUtils couldn't instantiate generic class

I am trying to implement something for converting between my Entities and DTO.
I have base class for my DTOs (called Models):
public class BaseModel<Entity> implements Model<Entity> {
#Override
public Entity toEntity(Class<Entity> entityClass) {
Entity entityInstance = BeanUtils.instantiate(entityClass);
BeanUtils.copyProperties(this, entityInstance);
return entityInstance;
}
}
But following test doesn't passes:
public class BaseModelTest {
#Entity
public class SomeEntity {
#Id
private Long id;
private String name;
public SomeEntity() {
}
public SomeEntity(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
#Test
public void toEntity_givenEntityClass_shouldCreateNewInstance() throws Exception {
//given
BaseModel<SomeEntity> model = new BaseModel();
//when
SomeEntity entity = model.toEntity(SomeEntity.class);
//then
assertNotNull(entity);
}
}
I got exception: (despite the fact, under debugger I see all ctors):
org.springframework.beans.BeanInstantiationException: Failed to instantiate [package.BaseModelTest$SomeEntity]: Is it an abstract class?; nested exception is java.lang.InstantiationException: package.BaseModelTest$SomeEntity
Caused by: java.lang.InstantiationException: package.BaseModelTest$SomeEntity
Caused by: java.lang.NoSuchMethodException: package.BaseModelTest$SomeEntity.<init>()
Currently to create a new SomeEntity instance you need an instance of the enclosing BaseModelTest class. SomeEntity should be an inner static class. Replace:
public class SomeEntity {
with
public static class SomeEntity {
BTW. There is no point in having a DTO class if it maps 1-1 to a model class, it does not add any value, it is only boilerplate code.

Error while Inserting into many to many relationship using hibernate

I am trying to insert into many to many relationship using hibernate but I am getting this error.
2014-04-24 14:50:47,820 ERROR [BasicPropertyAccessor.java:118] : IllegalArgumentException in class: com.jellboi.maniartyre.entities.AbstractEntity, setter method of property: pkey
2014-04-24 14:50:47,827 ERROR [BasicPropertyAccessor.java:122] : expected type: java.lang.Long, actual value: org.hibernate.id.IdentifierGeneratorHelper$2
Apr 24, 2014 2:55:25 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet applicationController threw exception
java.lang.IllegalArgumentException: java.lang.ClassCastException#17d66f6
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
Here is the code that I am trying.
VehicleProduct class
#Entity
#Table(name="m_vehicle_product")
#AssociationOverrides({
#AssociationOverride(name = "pk.vehicle",
joinColumns = #JoinColumn(name = "vehicle_id")),
#AssociationOverride(name = "pk.product",
joinColumns = #JoinColumn(name = "product_id")),
})
public class VehicleProduct extends AbstractEntity{
private String service;
private VehicleProductId pk = new VehicleProductId();
#Column(name = "service")
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
#EmbeddedId
public VehicleProductId getPk() {
return pk;
}
public void setPk(VehicleProductId pk) {
this.pk = pk;
}
#Transient
public Product getProduct(){
return getPk().getProduct();
}
public void setProduct(Product product){
getPk().setProduct(product);
}
#Transient
public Vehicle getVehicle(){
return getPk().getVehicle();
}
public void setVehicle(Vehicle vehicle){
getPk().setVehicle(vehicle);
}
}
VehicleProductId Class
#Embeddable
public class VehicleProductId implements java.io.Serializable {
private Vehicle vehicle;
private Product product;
#ManyToOne
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
#ManyToOne
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
And this is how I am Inserting.
for(int i=0;i<jobid.length;i++){
product = productService.findByPkey(jobid[i]);
vehicleProduct.setProduct(product);
vehicleProduct.setService(jobdesc[i]);
pkey2 = vehicleProductService.save(vehicleProduct);
}
Please guide me on this. Trying since hours to solve this problem.
EDIT
#MappedSuperclass
public class AbstractEntity implements IEntity, Serializable{
private static final long serialVersionUID = 1L;
private Long pkey;
private Boolean deleted;
private String creator;
private Date created;
private String changer;
private Date changed;
private Long version;
#Id
#GeneratedValue
#Column(name="pkey")
public Long getPkey() {
return pkey;
}
public void setPkey(Long pkey) {
this.pkey = pkey;
}
#Column(name="deleted")
#XmlTransient
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#Column(name="creator")
public String getCreator() {
return creator;
}
}........
It contains all of these getter and setters.
Your main problem is this:
2014-04-24 14:50:47,820 ERROR [BasicPropertyAccessor.java:118] : IllegalArgumentException in class: com.jellboi.maniartyre.entities.AbstractEntity, setter method of property: pkey
2014-04-24 14:50:47,827 ERROR [BasicPropertyAccessor.java:122] : expected type: java.lang.Long, actual value: org.hibernate.id.IdentifierGeneratorHelper$2
If you look at your code, you have an #Id defined on your AbstractEntity and an #EmbeddedId on your VehicleProduct
I am not sure how your database table is supposed to look, but it will seem to include the columns in AbstractEntity as well as those defined in VehicleProduct. If the columns are not meant to be there, then you shouldn't inherit from AbstractEntity. If they were meant to be there, then consider making the #EmbeddedId into an #Embedded and enforce a unique constraint for the business key.
2014-04-24 14:50:47,820 ERROR [BasicPropertyAccessor.java:118] : IllegalArgumentException in class: com.jellboi.maniartyre.entities.AbstractEntity, setter method of property: pkey
2014-04-24 14:50:47,827 ERROR [BasicPropertyAccessor.java:122] : expected type: java.lang.Long, actual value: org.hibernate.id.IdentifierGeneratorHelper$2
I do not know it this is your case, but taking a look to your trace I have to say hibernate does not support composite PK's with an identity part
Hibernate Jira composite PK identity part

Categories

Resources