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
Related
I am trying to query the subclass by the parent attributes. However hibernate always try to map the query result to parent class.
Framework used: JPA 2.0, Hibernate 3, Spring 3
Exception thrown:
org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException: Object with id: com.hkbea.zpm.entity.PositionPk#1dee9de was not of the specified subclass: com.hkbea.zpm.entity.FundPosition (loaded object was of wrong class class com.hkbea.zpm.entity.Position); nested exception is org.hibernate.WrongClassException: Object with id: com.hkbea.zpm.entity.PositionPk#1dee9de was not of the specified subclass: com.hkbea.zpm.entity.FundPosition (loaded object was of wrong class class com.hkbea.zpm.entity.Position)
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:666)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.convertHibernateAccessException(AbstractSessionFactoryBean.java:303)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.translateExceptionIfPossible(AbstractSessionFactoryBean.java:282)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy93.getFundListByAccountNumber(Unknown Source)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.adjustCashForRedeemUT(OnlineInterfaceServiceImpl.java:1224)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.getTRB(OnlineInterfaceServiceImpl.java:248)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.getTRB(OnlineInterfaceServiceImpl.java:219)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.calculateHandler(OnlineInterfaceServiceImpl.java:158)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy94.calculateHandler(Unknown Source)
at com.hkbea.zpm.controller.OnlineInterfaceController.calculate(OnlineInterfaceController.java:90)
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.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at com.hkbea.zpm.ext.spring.ZPMAnnotationMethodHandlerAdapter.invokeHandlerMethod(ZPMAnnotationMethodHandlerAdapter.java:429)
at com.hkbea.zpm.ext.spring.ZPMAnnotationMethodHandlerAdapter.handle(ZPMAnnotationMethodHandlerAdapter.java:417)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.hkbea.zpm.session.ZPMLoginFilter.doFilter(ZPMLoginFilter.java:68)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1136)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I've set the hibernate.show_sql to true and checked the sql seems alright and is expected when i try to execute in sql client.
select
fundpositi0_.CATEGORY as CATEGORY49_,
fundpositi0_.MAIN_ACCOUNT_NUMBER as MAIN1_49_,
fundpositi0_.REFERENCE as REFERENCE49_,
fundpositi0_1_.ACCOUNT_NUMBER as ACCOUNT3_49_,
fundpositi0_1_.ACCOUNT_NUMBER_EXT as ACCOUNT4_49_,
fundpositi0_1_.ACTIVE_FLAG as ACTIVE5_49_,
fundpositi0_1_.BASE_MARKET_VALUE as BASE6_49_,
fundpositi0_1_.CREATE_TIMESTAMP as CREATE7_49_,
fundpositi0_1_.CREATE_USER as CREATE8_49_,
fundpositi0_1_.CURRENCY as CURRENCY49_,
fundpositi0_1_.DESCRIPTION as DESCRIP10_49_,
fundpositi0_1_.EXCHANGE_RATE as EXCHANGE11_49_,
fundpositi0_1_.LDS_TYPE as LDS12_49_,
fundpositi0_1_.MARKET_VALUE as MARKET13_49_,
fundpositi0_1_.NEW_RISK_RATING as NEW14_49_,
fundpositi0_1_.QUANTITY as QUANTITY49_,
fundpositi0_1_.RISK_RATING as RISK16_49_,
fundpositi0_1_.UNIT_PRICE as UNIT17_49_,
fundpositi0_1_.UPDATE_TIMESTAMP as UPDATE18_49_,
fundpositi0_1_.UPDATE_USER as UPDATE19_49_,
fundpositi0_.AVAILABLE_BALANCE as AVAILABLE1_75_,
fundpositi0_.AVERAGE_COST as AVERAGE2_75_,
fundpositi0_.BASE_PROFIT_LOSS as BASE3_75_,
fundpositi0_.INSTRUMENT_NAME as INSTRUMENT4_75_,
fundpositi0_.ISIN_CODE as ISIN5_75_,
fundpositi0_.LAST_QUANTITY as LAST6_75_,
fundpositi0_.PROFIT_LOSS as PROFIT7_75_,
fundpositi0_.QUANTITY_HELD as QUANTITY8_75_,
fundpositi0_.SCS_SECURITY_CODE as SCS9_75_
from
PBWMS_FUND_POS fundpositi0_,
PBWMS_POS fundpositi0_1_
where
fundpositi0_.CATEGORY=fundpositi0_1_.CATEGORY
and fundpositi0_.MAIN_ACCOUNT_NUMBER=fundpositi0_1_.MAIN_ACCOUNT_NUMBER
and fundpositi0_.REFERENCE=fundpositi0_1_.REFERENCE
and fundpositi0_1_.ACTIVE_FLAG='A'
and fundpositi0_1_.ACCOUNT_NUMBER=?
I've tried to change the parent class to abstract, but hibernate will throw exception for failed to instantiate object of abstract class.
Caused by: org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: com.hkbea.zpm.entity.Position
I've also searched some other post said, the cascade mode need to be set for many-to-one property. So i have tried but still not working.
Query:
(List<FundPosition>) sessionFactory.getCurrentSession()
.createQuery("from FundPosition where activeFlag='A' and accountNumber=?")
.setString(0, accountNumber)
.list();
Parent Class:
#Entity
#Table(name="PBWMS_POS")
#Inheritance(strategy=InheritanceType.JOINED)
public class Position extends BaseEntityObject
{
private static final long serialVersionUID = -5370267130957236544L;
#Id
protected PositionPk pk;
#ManyToOne(cascade = CascadeType.DETACH)
#JoinColumn(name="MAIN_ACCOUNT_NUMBER", insertable=false, updatable=false)
protected CustomerAccount customerAccount;
#Column(name="ACCOUNT_NUMBER", nullable=false)
protected String accountNumber;
#Column(name="ACCOUNT_NUMBER_EXT", nullable=false)
protected String accountNumberExt;
#Column(name="DESCRIPTION", nullable=false)
protected String description;
#Column(name="CURRENCY", nullable=false)
protected String currency;
#Column(name="QUANTITY")
protected BigDecimal quantity;
#Column(name="UNIT_PRICE")
protected BigDecimal unitPrice;
#Column(name="EXCHANGE_RATE", scale=6, precision=8)
protected BigDecimal exchangeRate;
#Column(name="MARKET_VALUE")
protected BigDecimal marketValue;
#Column(name="BASE_MARKET_VALUE")
protected BigDecimal baseMarketValue;
#Column(name="ACTIVE_FLAG", nullable=false, length=1)
protected String activeFlag;
#Column(name="CREATE_USER", nullable=false)
protected String createUser;
#Column(name="CREATE_TIMESTAMP")
protected Timestamp createTimestamp;
#Column(name="UPDATE_USER")
protected String updateUser;
#Column(name="UPDATE_TIMESTAMP")
protected Timestamp updateTimestamp;
#Column(name="RISK_RATING")
protected String riskRating;
#Column(name="NEW_RISK_RATING")
protected String newRiskRating;
#Column(name="LDS_TYPE")
protected String ldsType;
//getters and setters...
}
Child Class:
#Entity
#Table(name="PBWMS_FUND_POS")
public class FundPosition extends Position
{
private static final long serialVersionUID = -8143748295075339416L;
#Column(name="ISIN_CODE", nullable=false)
private String isinCode;
#Column(name="INSTRUMENT_NAME", nullable=false)
private String instrumentName;
#Column(name="SCS_SECURITY_CODE", nullable=false)
private String scsSecurityCode;
#Column(name="AVAILABLE_BALANCE", nullable=false)
private BigDecimal availableBalance;
#Column(name="QUANTITY_HELD", nullable=false)
private BigDecimal quantityHeld;
#Column(name="AVERAGE_COST")
private BigDecimal averageCost;
#Column(name="PROFIT_LOSS")
private BigDecimal profitLoss;
#Column(name="BASE_PROFIT_LOSS")
private BigDecimal baseProfitLoss;
#Column(name="LAST_QUANTITY")
private BigDecimal lastQuantity;
//getters and setters...
}
Composite Key Class:
#Embeddable
public class PositionPk implements Serializable
{
private static final long serialVersionUID = -9161644029517397019L;
#Column(name="MAIN_ACCOUNT_NUMBER")
protected String mainAccountNumber;
#ManyToOne(cascade = CascadeType.DETACH)
#JoinColumn(name="CATEGORY")
protected Category category;
#Column(name="REFERENCE")
protected String reference;
//equals, getters and setters...
}
BaseEntityObject Class:
...
import net.sf.gilead.pojo.java5.LightEntity;
public abstract class BaseEntityObject extends LightEntity
{
private static final long serialVersionUID = -7453050794164673008L;
#Transient
public Object getUnderlyingValue()
{
return null;
}
public void setUnderlyingValue(Object obj)
{
}
#Transient
public String getDebugString()
{
return null;
}
public void setDebugString(String str)
{
}
#Override
public abstract boolean equals(Object obj);
}
Update on 2019-08-15,
Also tried to add following annotations in subclass, still not working
#PrimaryKeyJoinColumns({
#PrimaryKeyJoinColumn(name="MAIN_ACCOUNT_NUMBER", referencedColumnName="MAIN_ACCOUNT_NUMBER"),
#PrimaryKeyJoinColumn(name="REFERENCE", referencedColumnName="REFERENCE"),
#PrimaryKeyJoinColumn(name="CATEGORY", referencedColumnName="CATEGORY")
})
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.
Entity class:
package com.rapid.admin.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* LoginHistory entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "login_history", catalog = "project")
public class LoginHistory implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private Timestamp loginTime;
private Timestamp logoutTime;
private Boolean status;
private String timeId;
// Constructors
/** default constructor */
public LoginHistory() {
}
/** full constructor */
public LoginHistory(String username, Timestamp loginTime,
Timestamp logoutTime, Boolean status, String timeId) {
this.username = username;
this.loginTime = loginTime;
this.logoutTime = logoutTime;
this.status = status;
this.timeId = timeId;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username", length = 45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "login_time", length = 19)
public Timestamp getLoginTime() {
return this.loginTime;
}
public void setLoginTime(Timestamp loginTime) {
this.loginTime = loginTime;
}
#Column(name = "logout_time", length = 19, updatable= true)
public Timestamp getLogoutTime() {
return this.logoutTime;
}
public void setLogoutTime(Timestamp logoutTime) {
this.logoutTime = logoutTime;
}
#Column(name = "status")
public Boolean getStatus() {
return this.status;
}
public void setStatus(Boolean status) {
this.status = status;
}
#Column(name = "time_id", length = 45)
public String getTimeId() {
return this.timeId;
}
public void setTimeId(String timeId) {
this.timeId = timeId;
}
Hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria =
sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = new LoginHistory();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
Error on console:
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.getUpdateId(DefaultSaveOrUpdateEventListener.java:272)
at org.hibernate.event.def.DefaultUpdateEventListener.getUpdateId(DefaultUpdateEventListener.java:69)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:240)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:580)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:572)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
at $Proxy21.update(Unknown Source)
at com.rapid.admin.daoimpl.LoginDaoImpl.updateLogoutTime(LoginDaoImpl.java:117)
at com.rapid.admin.serviceimpl.LoginServiceImpl.updateLogoutTime(LoginServiceImpl.java:53)
at com.rapid.admin.controller.LoginController.logout(LoginController.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
I guess you should write like this : (by considering you want to update LoginHistory which is already in DB having id that you are passing)
hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = (LoginHistory)criteria.uniqueResult();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
I am using primefaces pick list and getting the error as the question stated. Posting only problem relative code.
XHTML Page
<p:row>
<p:column>
<p:outputLabel style="font-size:12px;" styleClass="labelCaption"
for="bank" value="Bank(s) Name :" />
</p:column>
<p:column colspan="3">
<p:pickList id="bank" style="font-size:12px;" required="true" value="#{eipoIRBean.dualbanks}" var="dbanks" itemLabel="#{dbanks.name}" itemValue="#dbanks}">
<f:facet name="sourceCaption">Available Banks</f:facet>
<f:facet name="targetCaption">Selected Banks</f:facet>
</p:pickList>
</p:column>
</p:row>
<p:row>
<p:column colspan="4" align="left"
styleClass="panelGridFooter ui-widget-header">
<p:commandButton id="submit" ajax="false"
style="font-size:12px;" value="Save"
action="#{eipoIRBean.submit}"
icon="ui-icon-check">
</p:commandButton>
<p:commandButton icon="ui-icon-arrowreturnthick-1-w"
style="font-size:12px;" value="Cancel"
action="listMyGroupLifeClaim?faces-redirect=true"
immediate="true" global="true">
</p:commandButton>
</p:column>
</p:row>
Bean is
#ViewScoped
#ManagedBean(name = "eipoIRBean")
public class InvestorRegistrationBean implements Serializable{
private InvestorSetupBusinessObj businessObj = new InvestorSetupBusinessObj();
private DualListModel<Bank> dualbanks;
public DualListModel<Bank> getDualbanks() {
return dualbanks;
}
public void setDualbanks(DualListModel<Bank> dualbanks) {
this.dualbanks = dualbanks;
}
public InvestorSetupBusinessObj getBusinessObj() {
return businessObj;
}
public void setBusinessObj(InvestorSetupBusinessObj businessObj) {
this.businessObj = businessObj;
}
public InvestorRegistrationBean(){
dualList_of_banks();
}
public void dualList_of_banks(){
dualbanks = new DualListModel<Bank>(businessObj.getInvestor().getBanks(), new ArrayList<Bank>());
}
public void submit() {
businessObj.getInvestor().setBanks(dualbanks.getTarget());
businessObj.save();
}
}
Business object is
public class InvestorSetupBusinessObj extends BaseBusinessObject {
private Investor investor= new Investor();
private InvestorRequestInvoker invoker = new InvestorRequestInvoker(this);
private List<Map<String,Object>> dataGrid;
public Investor getInvestor() {
return investor;
}
public void setInvestor(Investor investor) {
this.investor = investor;
}
public InvestorRequestInvoker getInvoker() {
return invoker;
}
public void setInvoker(InvestorRequestInvoker invoker) {
this.invoker = invoker;
}
public InvestorSetupBusinessObj(){
getInvestor().setBanks(invoker.selectAllBank());
}
}
Bank.java class
public class Bank implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String name;
private List<BankBranch> bankBranches;
private List<Investor> investors;
private List<InvestorJointHolder> investorJointHolders;
private List<PoBank> poBanks;
private List<PoSubscription> poSubscriptions;
public Bank() {
}
#Id
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//bi-directional many-to-one association to BankBranch
#OneToMany(mappedBy="bank")
public List<BankBranch> getBankBranches() {
return this.bankBranches;
}
public void setBankBranches(List<BankBranch> bankBranches) {
this.bankBranches = bankBranches;
}
public BankBranch addBankBranches(BankBranch bankBranches) {
getBankBranches().add(bankBranches);
bankBranches.setBank(this);
return bankBranches;
}
public BankBranch removeBankBranches(BankBranch bankBranches) {
getBankBranches().remove(bankBranches);
bankBranches.setBank(null);
return bankBranches;
}
//bi-directional many-to-many association to Investor
#ManyToMany(mappedBy="banks")
public List<Investor> getInvestors() {
return this.investors;
}
public void setInvestors(List<Investor> investors) {
this.investors = investors;
}
//bi-directional many-to-one association to InvestorJointHolder
#OneToMany(mappedBy="bank")
public List<InvestorJointHolder> getInvestorJointHolders() {
return this.investorJointHolders;
}
public void setInvestorJointHolders(List<InvestorJointHolder> investorJointHolders) {
this.investorJointHolders = investorJointHolders;
}
public InvestorJointHolder addInvestorJointHolders(InvestorJointHolder investorJointHolders) {
getInvestorJointHolders().add(investorJointHolders);
investorJointHolders.setBank(this);
return investorJointHolders;
}
public InvestorJointHolder removeInvestorJointHolders(InvestorJointHolder investorJointHolders) {
getInvestorJointHolders().remove(investorJointHolders);
investorJointHolders.setBank(null);
return investorJointHolders;
}
//bi-directional many-to-one association to PoBank
#OneToMany(mappedBy="bank")
public List<PoBank> getPoBanks() {
return this.poBanks;
}
public void setPoBanks(List<PoBank> poBanks) {
this.poBanks = poBanks;
}
public PoBank addPoBanks(PoBank poBanks) {
getPoBanks().add(poBanks);
poBanks.setBank(this);
return poBanks;
}
public PoBank removePoBanks(PoBank poBanks) {
getPoBanks().remove(poBanks);
poBanks.setBank(null);
return poBanks;
}
//bi-directional many-to-many association to PoSubscription
#ManyToMany(mappedBy="banks")
public List<PoSubscription> getPoSubscriptions() {
return this.poSubscriptions;
}
public void setPoSubscriptions(List<PoSubscription> poSubscriptions) {
this.poSubscriptions = poSubscriptions;
}
}
My pick list is populating correctly with the above method public InvestorSetupBusinessObj() but when I select one bank and save it, it gives the following exception. Any help much appreciated.
Stack Trace is
javax.el.PropertyNotFoundException: /eipo/investorRegistration.xhtml #367,59 itemLabel="#{dbanks.name}": Property 'name' not found on type java.lang.String
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:111)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at org.primefaces.component.picklist.PickList.getItemLabel(PickList.java:130)
at org.primefaces.component.picklist.PickListRenderer.encodeOptions(PickListRenderer.java:226)
at org.primefaces.component.picklist.PickListRenderer.encodeList(PickListRenderer.java:192)
at org.primefaces.component.picklist.PickListRenderer.encodeMarkup(PickListRenderer.java:86)
at org.primefaces.component.picklist.PickListRenderer.encodeEnd(PickListRenderer.java:59)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:877)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1826)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1822)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeRow(PanelGridRenderer.java:148)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeStaticBody(PanelGridRenderer.java:110)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeBody(PanelGridRenderer.java:63)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeEnd(PanelGridRenderer.java:49)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:877)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:74)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:57)
at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:204)
at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:121)
at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:58)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:877)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1826)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:847)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1819)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1822)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1822)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:447)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
You must define a converter to make it work, it is necessary as guided in the primefaces manual when using picklist :
<p:pickList ... var="dbanks" itemValue="#{dbanks}" converter="BankConverter" >
Take a look here : Custom converter in JSF 2.0
I'm rather new to Hibernate and it turns out it's not a simple technology to learn... In the project I use hibernate version 4.2.0.CR1. I'm trying to create a base class for all database entities, as they all are supposed to contain some identifier and date of creation. What is weird is that at first, I crated class User and UserPicture without any base class and it worked perfectly fine and now that I added it, even though it's supposed to work just like before, it doesn't o_O and it keeps on throwing some weird exception about my list of pictures, that was not thrown before...
So I keep on getting following stacktrace:
org.hibernate.MappingException: Could not determine type for: java.util.List, at table: User, for columns: [org.hibernate.mapping.Column(profilePicture)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:314)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:292)
at org.hibernate.mapping.Property.isValid(Property.java:239)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:469)
at org.hibernate.mapping.UnionSubclass.validate(UnionSubclass.java:61)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1283)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1734)
at love.commons.database.DBManager.<init>(DBManager.java:28)
at love.commons.database.DBManagerTest.<clinit>(DBManagerTest.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
AbstractEntity:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractEntity implements Serializable{
private static final long serialVersionUID = 1L;
protected Long id;
protected Date creationDate = new Date();
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.TABLE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column
#NotNull
#Temporal(TemporalType.DATE)
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
User:
#Entity
#Table(name="User")
public class User extends AbstractEntity {
private static final long serialVersionUID = 1L;
#Column (unique=true, length=30)
#NotNull
private String login;
#Column (length=32)
#NotNull
private String password;
#NotNull
#Email
#Column (unique=true, length=80)
private String email;
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="owner")
private List<UserPicture> profilePictures = new LinkedList<UserPicture>();
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Transient
public void encryptPassword() {
this.password = md5(password);
}
public List<UserPicture> getProfilePicture() {
return Collections.unmodifiableList(profilePictures);
}
public void addProfilePicture(UserPicture profilePicture) {
profilePicture.setOwner(this);
profilePictures.add(profilePicture);
}
#Transient
private String md5(String input) {
String md5 = null;
if(null == input) return null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(input.getBytes(), 0, input.length());
md5 = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5;
}
}
UserPicture:
#Entity
public class UserPicture extends AbstractEntity {
private static final long serialVersionUID = 1L;
#Column(length=734004)
private byte [] picture = null;
#ManyToOne(fetch=FetchType.LAZY)
#Column(name="owner")
#JoinColumn(nullable=false,name="id")
private User owner;
public UserPicture() {
picture = null;
}
public UserPicture(InputStream stream) {
try {
this.picture = new byte[stream.available()];
stream.read(picture);
} catch (IOException e) {
e.printStackTrace();
}
}
public UserPicture(byte [] picture) {
this.picture = picture;
}
public byte[] getPicture() {
return picture;
}
public void setPicture(byte[] picture) {
this.picture = picture;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}
So what am I doing wrong? Why do I keep on getting the exception?
AbstractEntity must not be annotated with #Entity and #Inheritance. It must be annotated with #MappedSuperclass. Indeed, this inheritance is only used to inherit common attributes, and that's what MappedSuperclass is for.
The exception you get is caused by the lack of coherence in the position of your mapping annotations. The base superclass annotated the getters, and the subclasses annotate the fields. Hibernate uses the position of the Id annotation to determine the access type of the entity. Since #Id is on a getter, it only considers the annotations placed on getters, and ignores those placed on fields. Put all your annotations either on fields (which I would recommend) or on getters.
Moreover, your getter is badly named. It should be getProfilePictures() and not getProfilePicture().
From Hibernate 5.2 documentation:
By default, the placement of the #Id annotation gives the default
access strategy.
For your case, hibernate will use AccessType.PROPERTY both for UserPicture and User entities hence the exception, to use field mapping strategy, you should define #Access strategy explicitly :
#Entity
#Table(name="User")
#Access( AccessType.FIELD )
public class User extends AbstractEntity {
...
}
#Entity
#Access( AccessType.FIELD )
public class UserPicture extends AbstractEntity {
....
}
I had the same problem, i figured out that hibernate tried to use Parent using properties accessorso i solved the problem by using #Access annotation to force use fields
#Entity
#Table(name = "MyTable")
#Access(AccessType.FIELD)
public class MyEntity{
......
}
you can try to add #ElementCollection mapping above the List declaration.