NullPointerException in dao.save method - java

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.

Related

No property XXX for type String! in JPA derived query with set from composite primary key item

I have a problem with JPA derived Queries in a repository for which I use two items of a composite Primary Key that I defined with #EmbededId. The main difficulty is that I try to use a set of string of one item of the Primary Key and at runtime, I get the following error:
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract void ca.hydro.publication.repository.PublicationChangementDateRepository.deleteBychangementDatePKSourceAndchangementDatePKNoPaIn(java.lang.String,java.util.List)! No property andchangementDatePKNoPa found for type String! Traversed path: ChangementDate.changementDatePK.source.
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.2.5.RELEASE.jar:2.2.5.RELEASE]
Blockquote
Caused by: org.springframework.data.mapping.PropertyReferenceException: No
property andchangementDatePKNoPa found for type String! Traversed
path: ChangementDate.changementDatePK.source. at
org.springframework.data.mapping.PropertyPath.(PropertyPath.java:94)
~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE] at
org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:381)
~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE] at
java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
~[na:1.8.0_192] at
java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
~[na:1.8.0_192] at
java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
~[na:1.8.0_192] at
java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
~[na:1.8.0_192] at
java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
~[na:1.8.0_192] at
java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
~[na:1.8.0_192] at
java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
~[na:1.8.0_192] at
java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
~[na:1.8.0_192] at
org.springframework.data.repository.query.parser.PartTree$Predicate.(PartTree.java:382)
~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE] at
org.springframework.data.repository.query.parser.PartTree.(PartTree.java:97)
~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE] at
org.springframework.data.jpa.repository.query.PartTreeJpaQuery.(PartTreeJpaQuery.java:89)
~[spring-data-jpa-2.2.5.RELEASE.jar:2.2.5.RELEASE] ... 73 common
frames omitted
Blockquote
Here is my code. What am I doing wrong? I'm sure it's a simple mistake that I made but I don't see anything wrong... :-(
Entity class:
#Entity
#Table(name = "CHANGEMENT_DATE", catalog="rapports", schema="dbo")
public class ChangementDate {
private static final long serialVersionUID = 1L;
#EmbeddedId
private ChangementDatePK changementDatePK;
private Date valeurDate;
private String projectUID;
private UUID extractionUID;
private LocalDateTime dateExtraction;
private String typeAction;
private LocalDateTime dateAction;
private String ancienNomMes;
private String noTacheMes;
#GenericGenerator(name = "generator", strategy = "guid", parameters = {})
#GeneratedValue(generator = "generator" , strategy = GenerationType.AUTO)
#Column(name = "EXTRACTION_UID" , columnDefinition="uniqueidentifier")
public UUID getExtractionUID() {
return extractionUID;
}
#Column(name="VALEUR_DATE")
public Date getValeurDate() {
return valeurDate;
}
#Column(name="PROJECTUID")
public String getProjectUID() {
return projectUID;
}
#Column(name="DATE_EXTRACTION")
public LocalDateTime getDateExtraction() {
return dateExtraction;
}
#Column(name="TYPE_ACTION")
public String getTypeAction() {
return typeAction;
}
#Column(name="DATE_ACTION")
public LocalDateTime getDateAction() {
return dateAction;
}
#Column(name="ANCIEN_NOM_MES")
public String getAncienNomMes() {
return ancienNomMes;
}
#Column(name="NO_TACHE_MES")
public String getNoTacheMes() {
return noTacheMes;
}
public ChangementDate(){
super();
}
public void setExtractionUID(UUID extractionUID) {
this.extractionUID = extractionUID;
}
public ChangementDatePK getChangementDatePK() {
return changementDatePK;
}
public void setChangementDatePK(ChangementDatePK changementDatePK) {
this.changementDatePK = changementDatePK;
}
public void setValeurDate(Date valeurDate) {
this.valeurDate = valeurDate;
}
public void setProjectUID(String projectUID) {
this.projectUID = projectUID;
}
public void setDateExtraction(LocalDateTime dateExtraction) {
this.dateExtraction = dateExtraction;
}
public void setTypeAction(String typeAction) {
this.typeAction = typeAction;
}
public void setDateAction(LocalDateTime dateAction) {
this.dateAction = dateAction;
}
public void setAncienNomMes(String ancienNomMes) {
this.ancienNomMes = ancienNomMes;
}
public void setNoTacheMes(String noTacheMes) {
this.noTacheMes = noTacheMes;
}
}
Embeddable Entity:
#Embeddable
public class ChangementDatePK implements Serializable {
#Column(name="SOURCE")
protected String source;
#Column(name="NO_PA")
protected String noPa;
#Column(name="CODE_ARRIMAGE")
protected String codeArrimage;
#Column(name="TYPE_DATE")
protected String typeDate;
public ChangementDatePK() {
}
public ChangementDatePK(String source, String noPa, String codeArrimage, String typeDate) {
this.source = source;
this.noPa = noPa;
this.codeArrimage = codeArrimage;
this.typeDate = typeDate;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getNoPa() {
return noPa;
}
public void setNoPa(String noPa) {
this.noPa = noPa;
}
public String getCodeArrimage() {
return codeArrimage;
}
public void setCodeArrimage(String codeArrimage) {
this.codeArrimage = codeArrimage;
}
public String getTypeDate() {
return typeDate;
}
public void setTypeDate(String typeDate) {
this.typeDate = typeDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ChangementDatePK)) return false;
ChangementDatePK that = (ChangementDatePK) o;
return Objects.equals(getSource(), that.getSource()) &&
Objects.equals(getNoPa(), that.getNoPa()) &&
Objects.equals(getCodeArrimage(), that.getCodeArrimage()) &&
Objects.equals(getTypeDate(), that.getTypeDate());
}
#Override
public int hashCode() {
return Objects.hash(getSource(), getNoPa(), getCodeArrimage(), getTypeDate());
}
}
Repository:
You can see in the code below that I try to call derived Query using the Items of my composite primary key. The items are "Source" and "noPa". But I try to find or delete rows that have specific "source" for all "noPa" of my Set passed as parameter.
#Repository
public interface PublicationChangementDateRepository extends JpaRepository<ChangementDate, ChangementDatePK>{
List<ChangementDate> findBychangementDatePKSourceAndchangementDatePKNoPaIn(String source, Set<String> noPa);
void deleteBychangementDatePKSourceAndchangementDatePKNoPaIn(String source, Set<String> noPa);
}
Thank you in advance for your responses!

Spring: detached entity passed to persist

It is a short time that I'm studying Spring,I'm a student
I have problems with dependency injection. In this project I have this error code in the method acquista.Why? Acquista in english is translated in "buy".If my Carrello (cart) is composed by more than one Articolo(Article) , in ArticoliOrdine(ArticlesOrder) I have only the first of them.Why?How can I solve it?
Error code:
Grave: Servlet.service() for servlet [applicationContext] in context with path [/SpringStore] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: bean.Ordine] with root cause
org.hibernate.PersistentObjectException: detached entity passed to persist: bean.Ordine
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:289)
at com.sun.proxy.$Proxy37.persist(Unknown Source)
at daoJPA.CarrelloDAOImpl.acquista(CarrelloDAOImpl.java:130)
CarrelloDAOImpl.java
#Transactional
public class CarrelloDAOImpl implements CarrelloDAO {
#PersistenceContext
private EntityManager em;
#Autowired
Carrello carrello;
#Autowired
private ArticoliOrdine articoliOrdine;
#Autowired
private Ordine ordine;
public void acquista(Cliente c){
ordine.setIdCliente(c);
ordine.setData(new Date(System.currentTimeMillis()));
ordine.setStato("In lavorazione");
em.persist(ordine);
Set<String> lista_articoli=carrello.getMappa_Articoli().keySet();
synchronized(lista_articoli){
Iterator<String> it=lista_articoli.iterator();
while(it.hasNext()){
String codice=it.next();
System.out.println("codice: "+codice);
Query q=em.createQuery("SELECT a FROM Articolo a WHERE a.codice =:codice");
q.setParameter("codice", codice);
Articolo a =(Articolo)q.getSingleResult();
ArticoliOrdinePK pk=articoliOrdine.getArticoliordinePK();
pk.setIdArticolo(a.getId());
pk.setIdOrdine(ordine.getId());
articoliOrdine.setArticolo(a);
articoliOrdine.setQuantita(carrello.getMappa_Articoli().get(codice));
em.persist(articoliOrdine);
//aggiorno la quantita' dell'articolo
Articolo articolo_update=em.find(Articolo.class,a.getId());
articolo_update.setQuantita(articolo_update.getQuantita()- articoliOrdine.getQuantita());
}//while
}//syncronized
}//acquista
}//CarrelloDAOImpl
Ordine.java
#Table(name="ordine")
#Entity
public class Ordine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="data")
private Date data;
#Column(name="stato")
private String stato;
#ManyToOne(optional=false)
#JoinColumn(name="idCliente",referencedColumnName="id")
private Cliente idCliente;
#OneToMany(mappedBy="ordine",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
Collection<ArticoliOrdine> articoliordineCollection;
public Ordine() {
}
public Ordine(Integer id) {
this.id = id;
}
public Ordine(Integer id, Date data, String stato) {
this.id = id;
this.data = data;
this.stato = stato;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getStato() {
return stato;
}
public void setStato(String stato) {
this.stato = stato;
}
public Cliente getIdCliente() {
return idCliente;
}
public void setIdCliente(Cliente idCliente) {
this.idCliente = idCliente;
}
public Collection<ArticoliOrdine> getArticoliordineCollection() {
return articoliordineCollection;
}
public void setArticoliordineCollection(
Collection<ArticoliOrdine> articoliordineCollection) {
this.articoliordineCollection = articoliordineCollection;
}
#Override
public boolean equals(Object o){
if(! (o instanceof Ordine) )
return false;
Ordine ordine=(Ordine)o;
return ordine.id==this.id;
}//equals
public String toString(){
return id+" cliente:"+idCliente.getId();
}//toString
}//Ordine
CarrelloController.java
#Controller
public class CarrelloController {
#Autowired
CarrelloDAO carrelloDAO;
#Autowired
Carrello carrello;
...
#RequestMapping(value="/acquista",method=RequestMethod.POST)
public String acquista(HttpServletRequest request,ModelMap model){
HttpSession session=request.getSession();
Cliente cliente=(Cliente)session.getAttribute("cliente");
carrelloDAO.acquista(cliente);
carrello.svuotaCarrello();
model.addAttribute("num_articoli",carrello.contaArticoliCarrello());
model.addAttribute("totale_carrello",carrello.getTotale());
return "redirect:/";
}//checkOut
}//CarrelloController
ApplicationContext.xml
<bean class="daoJPA.ClienteDAOImpl" id="clienteDAO"/>
<bean class="daoJPA.ArticoloDAOImpl" id="articoloDAO"/>
<bean class="bean.Carrello" id="carrello" scope="session">
<aop:scoped-proxy/>
</bean>
<bean class="daoJPA.CarrelloDAOImpl" id="carrelloDAO"/>
<bean class="bean.ArticoliOrdine" id="articoliOrdine" scope="prototype">
<property name="articoliordinePK">
<bean class="bean.ArticoliOrdinePK" id="articoliOrdinePK" scope="prototype"/>
</property>
</bean>
<bean class="bean.Ordine" id="ordine" scope="prototype"/>
You are not approaching this the right way. Your entities shouldn't be treated as Spring Beans.
#Autowired
private ArticoliOrdine articoliOrdine;
...
em.persist(articoliOrdine);
For long conversations you should either use:
Extended persistence context
detached objects saved in your Http Session
And detached entities shouldn't be passed to persist. You should merge them instead.
Persist is only meant for moving an entity state from TRANSIENT to PERSISTED. For DETACHED -> PERSISTED transitions you should always use EntityManager#merge() or Hibernate specific saveOrUpdate.

JBoss Seam + jsf javax.ejb.EJBTransactionRolledbackException"

I am very new to JSF and I tried a crud operation first to proceed the further in my project.But I have a struck up here, while inserting data into table.Also spend lot of time in this, but cant get out from this. Hope some one could shoot my mistake. I am starting from my error report on console and followed by the classes.
My stack trace as follows:
Exception during request processing:
Caused by javax.ejb.EJBTransactionRolledbackException with message: ""
org.jboss.ejb3.tx.Ejb3TxPolicy.handleInCallerTx(Ejb3TxPolicy.java:87)
org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:210)
org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:84)
$Proxy256.saveOrUpdate(Unknown Source)
org.jboss.seam.intercept.ClientSideInterceptor.invoke(ClientSideInterceptor.java:54)
org.javassist.tmp.java.lang.Object_$$_javassist_seam_21.saveOrUpdate(Object_$$_javassist_seam_21.java)
com.ermms.clrp.loginhistory.LoginhistoryActionImpl.create(LoginhistoryActionImpl.java:47)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:84)
$Proxy165.create(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
org.primefaces.application.CleanupActionListener.processAction(CleanupActionListener.java:42)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
java.lang.Thread.run(Thread.java:662)
Caused by java.lang.NullPointerException with message: ""
com.ermms.clrp.dto.loginhistory.LoginhistoryMapper.mapLoginhistoryEntity(LoginhistoryMapper.java:17)
com.ermms.clrp.service.loginhistory.LoginhistoryServiceImpl.saveOrUpdate(LoginhistoryServiceImpl.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
sun.reflect.GeneratedMethodAccessor84.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:240)
org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:210)
org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:84)
$Proxy256.saveOrUpdate(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.javassist.tmp.java.lang.Object_$$_javassist_seam_21.saveOrUpdate(Object_$$_javassist_seam_21.java)
com.ermms.clrp.loginhistory.LoginhistoryActionImpl.create(LoginhistoryActionImpl.java:47)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
sun.reflect.GeneratedMethodAccessor84.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
$Proxy165.create(Unknown Source)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
java.lang.Thread.run(Thread.java:662)
The xhtml page I used for insert the date:
<ui:define name="main-container">
<div class="panel-content">
<h:form class="input-list" id="creatuser" style="width:100%;">
<h:panelGrid border="1" class="creatUserDetailsTable">
<f:facet name="header">
<h:outputText value="User Login History"
style="font-size: 23px; font-weight: bold; color: threeddarkshadow;" />
</f:facet>
<s:decorate id="nameDec" template="../../../secure/edit.xhtml">
<ui:define name="label">Name:</ui:define>
<h:inputText tabindex="1" id="amount" type="text"
class="miniusername clp"
value="#{loginhistoryAction.currentLoginhistory.name}" required="true">
<f:validateLength minimum="3" maximum="20" />
</h:inputText>
</s:decorate>
</h:panelGrid>
<h:commandButton value="Save" tabindex="20" class="usersubmit"
action="#{loginhistoryAction.create}">
</h:commandButton>
</h:form>
<h:messages globalOnly="true" />
</div>
</ui:define>
Interface used :
#Local
public interface LoginhistoryAction extends Serializable {
public String create();
public String initCurrentLoginhistory();
public void setCurrentLoginhistory(Loginhistory currentLoginhistory);
public Loginhistory getCurrentLoginhistory();
}
The action class implements the above interface:
#Name("loginhistoryAction")
#Stateless
#AutoCreate
public class LoginhistoryActionImpl implements LoginhistoryAction {
#Out(value = "currentLoginhistory", scope = ScopeType.CONVERSATION)
#In(value = "currentLoginhistory", scope = ScopeType.CONVERSATION, required = false)
private Loginhistory currentLoginhistory;
public Loginhistory getCurrentLoginhistory() {
return currentLoginhistory;
}
public void setCurrentLoginhistory(Loginhistory currentLoginhistory) {
this.currentLoginhistory = currentLoginhistory;
}
#In
private LoginhistoryService LoginhistoryService;
private static final long serialVersionUID = 8282995226262125676L;
public String create() {
currentLoginhistory.setRef("Test");
Integer id = LoginhistoryService.saveOrUpdate(this.currentLoginhistory);
return "/secure/userhome.xhtml";
}
#Override
public String initCurrentLoginhistory() {
currentLoginhistory = new Loginhistory();
return "/secure/common/history/loginHistory.xhtml";
}
}
Service interface:
#Local
public interface LoginhistoryService extends Serializable {
public abstract Integer saveOrUpdate(Loginhistory Loginhistory);
}
ServiceImpl class:
#Name("LoginhistoryService")
#Stateless
#AutoCreate
public class LoginhistoryServiceImpl implements LoginhistoryService {
private static final long serialVersionUID = 1L;
#In
private LoginhistoryDAO loginhistoryDAO;
public LoginhistoryServiceImpl() {
super();
}
#Override
// TODO what to do with lastmodified if it is modify
public Integer saveOrUpdate(Loginhistory loginhistory) {
LoginhistoryEntity loginhistoryEntity = LoginhistoryMapper.mapLoginhistoryEntity(loginhistory);
Integer loginhistoryId = loginhistoryDAO.saveOrUpdate(loginhistoryEntity);
return loginhistoryId;
}
}
Mapper class:
public class LoginhistoryMapper {
public static LoginhistoryEntity mapLoginhistoryEntity(
Loginhistory loginhistory) {
LoginhistoryEntity loginhistoryEntity = new LoginhistoryEntity();
loginhistoryEntity.setId(loginhistory.getId());
loginhistoryEntity.setName(loginhistory.getName());
loginhistoryEntity.setDate(loginhistory.getDate());
return loginhistoryEntity;
}
}
DAO interface:
#Local
public interface LoginhistoryDAO extends Serializable {
public Integer saveOrUpdate(LoginhistoryEntity newLoginhistory);
}
JPAclassDAOImpl class:
#Name("loginhistoryDAO")
#Stateless
#AutoCreate
public class JPALoginhistoryDaoImpl implements LoginhistoryDAO {
private static final long serialVersionUID = -6173881454668735683L;
#PersistenceContext(unitName = "clrp")
private EntityManager entityManager;
Logger logger = Logger.getLogger(this.getClass());
public void setEntityManager(EntityManager em) {
this.entityManager = em;
}
#Override
public Integer saveOrUpdate(LoginhistoryEntity newLoginhistory) {
entityManager.merge(newLoginhistory);
return newLoginhistory.getId();
}
}
My entity is as follows:
#Entity
#Table(name="loginhistory")
#NamedQueries(value = {
#NamedQuery(name = LoginhistoryEntity.fetchAll, query = "FROM LoginhistoryEntity" )})
public class LoginhistoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
public final static String fetchAll = "LoginhistoryEntity.fetchAll";
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false)
private int id;
#Column(name = "Date")
private Date date;
#Column(name = "Name")
private String name;
#Column(name = "Ref")
private String ref;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getRef() {
return ref;
}
}
Finally I found the mistake, trivial one and sorry for your time here..
My entity was previously
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "historyId", updatable = false)
private Integer historyId;
Problem here the integer type, it should be
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false)
private Integer id;
Cheers

Can't bind a nested property along a BeanFieldGroup

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");

Hibernate + Spring exception: Unknown Entity

i am getting exception while the server starts. (Server is started using Intelij IDE).
i have no idea how to fix it. i am new to hibernate and spring. thanks in advance.
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationMgr' defined in URL [jar:file:/C:/Program%20Files%20(x86)/Apache%20Software%20Foundation/Tomcat%207.0/webapps/ROOT/WEB-INF/lib/dbservice-1.0-SNAPSHOT.jar!/ApplicationContext-Service.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 21 more
Authentication entity
/**
* Authentication Entity - Representation of the db table
*/
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "t_authentication")
public class Authentication extends LongBaseEntity implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "auth_id")
private Long mAuthId;
#Column(name = "authentication_id")
private Long mAuthenticationId;
#Column(name = "tcn")
private Long mTcn;
#Column(name = "audit_comment")
private String mAuditComment;
#Column(name = "last_timestamp")
private Date mLastTimeStamp;
#Column(name = "user_id")
private Long mUserId;
#Column(name = "authentication_date")
private Date mAuthenticationDate;
#Column(name = "hostname")
private String mHostname;
#Column(name = "ip_address")
private String mIpAddress;
#Column(name = "referrer_url")
private String mReferrerURL;
#Column(name = "session_id")
private String mSessionId;
public Long getAuthId() {
return mAuthId;
}
public void setAuthId(Long pAuthId) {
this.mAuthId = pAuthId;
mId = pAuthId;
}
public Long getAuthenticationId() {
return mAuthenticationId;
}
public void setAuthenticationId(Long pAuthenticationId) {
this.mAuthenticationId = pAuthenticationId;
}
public Long getTcn() {
return mTcn;
}
public void setTcn(Long pTcn) {
this.mTcn = pTcn;
}
public String getAuditComment() {
return mAuditComment;
}
public void setAuditComment(String pAuditComment) {
this.mAuditComment = pAuditComment;
}
public Date getLastTimeStamp() {
return mLastTimeStamp;
}
public void setLastTimeStamp(Date pLastTimeStamp) {
this.mLastTimeStamp = pLastTimeStamp;
}
public Long getUserId() {
return mUserId;
}
public void setUserId(Long pUserId) {
this.mUserId = pUserId;
}
public Date getAuthenticationDate() {
return mAuthenticationDate;
}
public void setAuthenticationDate(Date pAuthenticationDate) {
this.mAuthenticationDate = pAuthenticationDate;
}
public String getHostname() {
return mHostname;
}
public void setHostname(String pHostname) {
this.mHostname = pHostname;
}
public String getIpAddress() {
return mIpAddress;
}
public void setIpAddress(String pIpAddress) {
this.mIpAddress = pIpAddress;
}
public String getReferrerURL() {
return mReferrerURL;
}
public void setReferrerURL(String pReferrerURL) {
this.mReferrerURL = pReferrerURL;
}
public String getSessionId() {
return mSessionId;
}
public void setSessionId(String pSessionId) {
this.mSessionId = pSessionId;
}
public String toString() {
return "Payment{" +
"mId=" + getId() +
", mIpaddress=" + mIpAddress +
'}';
}
}
DAO class:
/**
* Implementation for AuthenticationMgr DAO layer.
*
*/
import com.jsi.core.dbservice.model.Authentication;
import com.jsi.core.dbservice.model.JSIException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.sql.SQLException;
import java.util.List;
public class AuthenticationDao extends HibernateDaoSupport implements IAuthenticationDao {
#Override
public List<Authentication> list() {
final String query = "Select a from Authentication a order by a.id desc";
return (List<Authentication>) getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.createQuery(query).list();
}
});
}
#Override
public void save(Authentication authentication) throws JSIException {
getHibernateTemplate().save(authentication);
}
#Override
public Authentication load(Long id) {
return getHibernateTemplate().load(Authentication.class, id);
}
#Override
public void update(Authentication authentication) throws JSIException {
getHibernateTemplate().update(authentication);
}
#Override
public void delete(Long id) {
getHibernateTemplate().delete(load(id));
}
}
If you are happened to use HibernateUtil to manipulate the data, you need to add annotated class to your configuration.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().addAnnotatedClass(Authentication.class)
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html
thanks everyone for your reply. i managed to solve it. it was my mistake. i forgot to add the mapping tag in xml.
<hibernate-configuration>
<session-factory>
<mapping class="com.model.Authentication"/> // i missed this line. after i added it. it worked fine.
</session-factory>
</hibernate-configuration>
thanks again.

Categories

Resources