I am getting NullPointerException when getFacade().create(current) is executed - jpa

My PujaController.java:
public class PujaController implements Serializable {
private Puja current;
private DataModel items = null;
#EJB
private jpa.sessions.PujaFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PujaController() {
}
public Puja getSelected() {
if (current == null) {
current = new Puja();
current.setPujaPK(new jpa.entities.PujaPK());
selectedItemIndex = -1;
}
return current;
}
private PujaFacade getFacade() {
return ejbFacade;
}
public String creaPuja(Subasta subasta) {
try {
current = new Puja();
current.setPujaPK(new jpa.entities.PujaPK());
selectedItemIndex = -1;
current.getPujaPK().setNroDePuja(0); //AUTO_INCREMENT
Postor postor = AuthenticationPhaseListener.getLoggedInPostor();
current.getPujaPK().setEmail(postor.getEmail());
current.getPujaPK().setSubastaId(subasta.getSubastaId());
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
current.setFechaDePuja(new java.sql.Timestamp(now.getTime()));
current.setMontoAPagar(BigDecimal.ONE);
current.setMontoDePuja(BigDecimal.TEN);
current.setNroDePujas(0);
current.setPagoAcumulado(BigDecimal.ONE);
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PujaCreated"));
return "Puja";
} catch (Exception e) {
System.out.println(e);
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareCreate() {
current = new Puja();
current.setPujaPK(new jpa.entities.PujaPK());
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
current.getPujaPK().setNroDePuja(0); //AUTO_INCREMENT
current.getPujaPK().setEmail(current.getPostor().getEmail());
current.getPujaPK().setSubastaId(current.getSubasta().getSubastaId());
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PujaCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
}
My SubastaController.java:
public class SubastaController implements Serializable {
private Subasta current;
private DataModel items = null;
#EJB
private jpa.sessions.SubastaFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public SubastaController() {
}
public Subasta getSelected() {
if (current == null) {
current = new Subasta();
selectedItemIndex = -1;
}
return current;
}
private SubastaFacade getFacade() {
return ejbFacade;
}
public String preparePuja() {
current = (Subasta) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Puja";
}
public String pujar() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SubastaUpdated"));
PujaController pc = new PujaController();
pc.creaPuja(current);
return "Puja";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareCreate() {
current = new Subasta();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SubastaCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
}
Hi, trying to learn some JSF, EntityManager API, I getting stuck here: When pujar() is executed, the subasta get updated successfully and then the creaPuja(current) in pujaController is executed. The creaPuja(current) is ok until getFacade().create(current); is execute and give me a NullPointerException. The current object is created and the key are set. I do not find the way to get the references to the Entity Manager to get successfully create puja. I include the Facade java file also. If you can provide some code to explain the problem would be great!!!
The pujaFacade.java:
public class PujaFacade extends AbstractFacade<Puja> {
#PersistenceContext(unitName = "subasta701WPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public PujaFacade() {
super(Puja.class);
}
}
The abstractFacade.java:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
#PostConstruct
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
#PostConstruct
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Here is the Exception:
INFO: java.lang.NullPointerException
at jsf.PujaController.creaPuja(PujaController.java:146)
at jsf.SubastaController.pujar(SubastaController.java:96)
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 com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Yes, the getFacade() in null. My question is how I move or assign the current object to getFacade(). There are a member ejbFacade of type PujaFacade, but I need ejbFacade get the value of current (Puja object) so getFacade will not be null. Thank you ...

What are the values of getFacade() and current at the point that the exception is thrown.
Also, can you please post the stack trace from the exception.
Note: In my experience NullPointerException are the result of accessing a method from a null object. In this case, that would mean getFacade() is returning null.
Update:
After reviewing your code I am not sure. You never set ejbFacade in PujaController or SubastaController, but are able to access it in SubastaController but not in PujaController.
Try comparing the jpa.sessions.SubastaFacade implementation with the jpa.sessions.PujaFacade implementation and see if you are missing anything.
For example, does PujaFacade need a #Stateless before the class definition? Should the unit name in #PersistenceContext(unitName = "subasta701WPU") be changed?
You may also want to read these:
Getting Started with Java EE 6 Applications
The Java Persistence API - A Simpler Programming Model for Entity Persistence
A Wikipedia page with some good samples
Let us know how it turns out.

Related

How to create mock object of such method which return type is List<Tuple>

I am trying to write test case for Account Controller. At very first My I am creating mock object but that methods return type is List<Tuple>. I am not getting how to create mock object of following method which return type is List
Can any one tell me how to create mock object for following method?
AccountController
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "1122";
String sAcctDesc = "SRI";
String sInvestigatorName = "Ram";
String sClientDeptId = "1200";
Tuple mockedTuple = Mockito.mock(Tuple.class);
List<Tuple> accountObj = new ArrayList<>();
accountObj.add(mockedTuple);
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(accountObj);
mockMvc.perform(
get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "1122")
.param("sAcctDesc", "SRI")
.param("sInvestigatorName", "Ram")
.param("sClientDeptId", "1200")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);
}
Stack Trace
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.spacestudy.controller.AccountControllerTest.populateGridViewsTest(AccountControllerTest.java:57)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class TestAccountController {
#Autowired
private MockMvc mockMvc;
#Autowired
private AccountService accountService;
#Autowired
private AccountController accountController;
#Test
#Transactional
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "1122";
String sAcctDesc = "SRI";
String sInvestigatorName = "Ram";
String sClientDeptId = "1200";
Tuple mockedTuple = Mockito.mock(Tuple.class);
List<Tuple> accountObj = new ArrayList<>();
accountObj.add(mockedTuple);
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(accountObj);
mockMvc.perform(
get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "1122")
.param("sAcctDesc", "SRI")
.param("sInvestigatorName", "Ram")
.param("sClientDeptId", "1200")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);
}
#AutoConfigureMockMvc
public class TickServiceTest {
#Autowired
private MockMvc mockMvc;
}
First you have to try this..instead of using Mockito use MockMvc object. And just tell me u want to create AccountController object or Account bean object?
You can implements Tuple interface and use it in thenReturn method.
import java.util.Arrays;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
public class MockedTuple implements Tuple {
private final Object[] a;
public MockedTuple(Object[] a) {
this.a = a;
}
#SuppressWarnings("unchecked")
#Override
public <T> T get(int index, Class<T> type) {
return (T) a[index];
}
#Override
public <T> T get(Expression<T> expr) {
return null;
}
#Override
public int size() {
return a.length;
}
#Override
public Object[] toArray() {
return a;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Tuple) {
return Arrays.equals(a, ((Tuple) obj).toArray());
} else {
return false;
}
}
#Override
public int hashCode() {
return Arrays.hashCode(a);
}
#Override
public String toString() {
return Arrays.toString(a);
}
}
Example of test:
Object[] myReturnedObject = new Object[1];
myReturnedObject[0] = value;
when(myService.getTuples(...params)).thenReturn(
List.of(new MockedTuple(myReturnedObject))
)

JPA Entity not stored OneToMany relationship

i trie to run the following code.
But the child is not created to the parent Entity 'Erfasser'.
If i comment out the line erfasser.getErfasst().add(neu) everything works fine.
#PostConstruct
public void init() {
Erfasser erfasser = new Erfasser();
erfasser.setEmail("benjamin.koubik#auditweb.de");
erfasser.setPasswort("counting88");
gesamtAnzahl.einfuegenErfasser(erfasser);
Erfasst neu = new Erfasst();
neu.setDatum(new Date());
neu.setJuristische(1);
neu.setNatuerliche(0);
gesamtAnzahl.einfuegen(neu);
erfasser.getErfasst().add(neu);
gesamtAnzahl.update(erfasser);
}
Only the Erfasser itself is stored correctly in the DB.
#Entity
public class Erfasser implements Serializable {
private static final long serialVersionUID = 1L;
public Erfasser() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int erfasser_id;
#Column(length = 50)
#Email(message = "Inkorrekt EMail")
private String email;
#Column(length = 30)
private String passwort;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(referencedColumnName = "erfasser_id", name = "erfasst_id_referenz")
private List<Erfasst> erfasst;
public int getErfasser_id() {
return erfasser_id;
}
public void setErfasser_id(int erfasser_id) {
this.erfasser_id = erfasser_id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswort() {
return passwort;
}
public void setPasswort(String passwort) {
this.passwort = passwort;
}
public List<Erfasst> getErfasst() {
return erfasst;
}
public void setErfasst(List<Erfasst> erfasst) {
this.erfasst = erfasst;
}
}
And here my SessionBeans:
AnzahlErfasstGesamtLocal.java
#Local
public interface AnzahlErfasstGesamtLocal {
public abstract List<Integer> gesamt();
public abstract List<Erfasst> gesamtNatuerlich();
public abstract List<Erfasst> gesamtJuristisch();
public abstract void einfuegenErfasser(Erfasser e);
public abstract void einfuegen(Erfasst e);
public abstract void update(Erfasser e);
public abstract void loeschen(Erfasst e);
}
AnzahlErfasstGesamt.java
#Stateless
#LocalBean
public class AnzahlErfasstGesamt implements AnzahlErfasstGesamtLocal {
#PersistenceContext
private EntityManager em;
public AnzahlErfasstGesamt() {
}
#Override
public List<Integer> gesamt() {
return null;
}
#Override
public List<Erfasst> gesamtNatuerlich() {
try {
TypedQuery<Erfasst> q = em.createQuery(
"SELECT COUNT(e) FROM Erfasst e WHERE e.natuerliche = 1 AND e.juristische = 0; ", Erfasst.class);
List<Erfasst> liste = q.getResultList();
if (!liste.isEmpty()) {
return liste;
} else {
return null;
}
} catch (NoResultException e) {
return null;
}
}
#Override
public List<Erfasst> gesamtJuristisch() {
try {
TypedQuery<Erfasst> q = em.createQuery(
"SELECT COUNT(e) FROM Erfasst e WHERE e.juristische = 1 AND e.natuerliche = 0; ", Erfasst.class);
List<Erfasst> liste = q.getResultList();
if (!liste.isEmpty()) {
return liste;
} else {
return null;
}
} catch (NoResultException e) {
return null;
}
}
#Override
public void einfuegen(Erfasst e) {
em.persist(e);
}
#Override
public void update(Erfasser e) {
em.merge(e);
}
#Override
public void loeschen(Erfasst e) {
em.remove(em.merge(e));
}
#Override
public void einfuegenErfasser(Erfasser e) {
em.persist(e);
}
}
There is nothing wrong with JPA - something is wrong in external code (and certainly with your description of the problem). For example I don't see where the actual erfasst list is created - if nothing happens in einfuegenErfasser (whatever that means), then you will get a NullPointerException while trying to add an element to a null list. Is that what happens?
The problem is the combination of JPA entity setup and the code using it. The JPA entity Erfasser has CascadeType.ALL, therefore the gesamtAnzahl.update(erfasser); updates the child entities erfasst with it. At the same time you do not setup the erfasser reference on the neu instance. You need to do something alog the line neu.setErfasser(erfasser) before gesamtAnzahl.update(erfasser);.
On separated line of concern, using the native German naming drives my head crazy, even though I am more German then English speaker.

Team Foundation Server 2012 subscribe to events

In my case I need subscribe to TFS events (create/delete team project, workitem, checkin, iteration, areas) for realization some business logic. I based on this manual. Now I can catch only workitem and checkin events, but I need more (team project, iteration, areas). In this list, I did not find the right events.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.Integration.Server;
using Microsoft.TeamFoundation.VersionControl.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
public class WorkItemChangedEventHandler : ISubscriber
{
public string Name
{
get { return "WorkItemChangedEventHandler"; }
}
public SubscriberPriority Priority
{
get { return SubscriberPriority.Normal; }
}
public Type[] SubscribedTypes()
{
var types = new List<Type>
{
typeof(Microsoft.TeamFoundation.WorkItemTracking.Server.WorkItemChangedEvent),// working
typeof(Microsoft.TeamFoundation.VersionControl.Server.CheckinNotification),// working
typeof(Microsoft.TeamFoundation.Integration.Server.ProjectCreatedEvent)// NOT working
};
return types.ToArray();
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType,
object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
statusCode = 0;
properties = null;
statusMessage = String.Empty;
try
{
EventLog.WriteEntry("WorkItemChangedEventHandler", string.Format("Entity: {0} was modified", notificationEventArgs.GetType()));
}
catch (Exception ex)
{
EventLog.WriteEntry("WorkItemChangedEventHandler", ex.Message + ex.StackTrace);
}
return EventNotificationStatus.ActionPermitted;
}
}
I have one class for CheckinNotificationEventHandler:
public class CheckinNotificationEventHandler : ISubscriber
{
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(CheckinNotification) };
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
if (notificationType == NotificationType.Notification && notificationEventArgs is CheckinNotification)
{
...
}
return EventNotificationStatus.ActionPermitted;
}
}
and a second class for WorkItemChangedEventHandler:
public class WorkItemChangedEventHandler : ISubscriber
{
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(Microsoft.TeamFoundation.WorkItemTracking.Server.WorkItemChangedEvent) };
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
...
}
return EventNotificationStatus.ActionPermitted;
}
}

JPA Eclipselink JOIN FETCH LAZY relation returning null

I am always getting NULL from a JOIN FETCH clause in my JPA Query, even though I have everything configured as expected:
#XmlRootElement
#XmlAccessorType(XmlAccessType.PROPERTY)
#Entity
#Table(name = "TB_BANNER_IMAGE")
public class BannerImage extends BaseEntity<Integer> {
protected FileReference fileReference;
private String type;
private String labelTitle;
protected BannerImage() {}
#Id
#TableGenerator(name="genBannerImage", table="TB_ID_GENERATOR",
pkColumnName="ID_NAME", valueColumnName="ID_VAL",
pkColumnValue="TB_BANNER_IMAGE", allocationSize=1)
#GeneratedValue(strategy=GenerationType.TABLE, generator="genBannerImage")
#Column(name = "ID_BANNER_IMAGE", unique = true, nullable = false)
public Integer getId() {
return super.getId();
}
#Override
public void setId(Integer id) {
super.setId(id);
}
#Column(name="TYPE")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#OneToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
#JoinColumn(name="ID_FILE_REFERENCE", nullable=false)
public FileReference getFileReference() {
return fileReference;
}
public void setFileReference(FileReference fileReference) {
this.fileReference = fileReference;
}
#Column(name="LABEL_TITLE")
public String getLabelTitle() {
return labelTitle;
}
public void setLabelTitle(String labelTitle) {
this.labelTitle = labelTitle;
}
}
for File Reference Class:
#Entity
#Table(name = "TB_FILE_REFERENCE")
public class FileReference extends BaseNamedEntity<String> {
private String type;
public FileReference() {}
#Id
#TableGenerator(name="genFileReference", table="TB_ID_GENERATOR",
pkColumnName="ID_NAME", valueColumnName="ID_VAL",
pkColumnValue="TB_FILE_REFERENCE", allocationSize=1)
#GeneratedValue(strategy=GenerationType.TABLE, generator="genFileReference")
#Column(name = "ID_FILE_REFERENCE", unique = true, nullable = false)
public String getId() {
return super.getId();
}
#Override
public void setId(String id) {
super.setId(id);
}
#Column(name = "TYPE")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Service class:
#Path("/banner")
public class BannerImageService extends BaseServiceFacade<BannerImage, Integer> {
#SuppressWarnings("unchecked")
#Override
public Crud<BannerImage, Integer> lookupService() throws ServiceLocatorException {
return ServiceLocator.getInstance()
.getLocalHome(ServicesConstants.BANNER_IMAGE_SERVICE);
}
#Override
protected String getDefaultGetQuery() {
return BannerImageDAO.GET_BY_ID_FETCH_FILE_REF;
}
#Override
protected String getDefaultQuery() {
return BannerImageDAO.GET_ALL_FETCH_FILE_REF;
}
}
get REST method of BaseServiceFacade:
#Override
#GET
#Consumes(MediaType.APPLICATION_JSON)
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("/{id}")
public T get(#PathParam("id") ID id) {
try {
if (!validateID(id)) {
logMessage("Invalid Entity ID: " + id);
return null;
}
String defaultGetQuery = getDefaultGetQuery();
if (defaultGetQuery != null) {
Map<String, Object> mapParams = new HashMap<String, Object>();
mapParams.put("id", id);
List<T> entityList = getService().search(defaultGetQuery, mapParams);
if (entityList != null && entityList.size() == 1) {
T ent = entityList.get(0);
return ent;
} else {
logMessage("Invalid search by Entity ID: " + id);
}
} else {
return getService().findById(clazz, id);
}
} catch (ServiceException e) {
serviceException(e);
} catch (Exception ex) {
logException(ex);
}
return null;
}
And finally the Service Bean EJB which reads from entityManager:
public class BaseServiceBean<T extends IEntity<ID>, ID extends Serializable> implements Crud<T,ID> {
// ... generic methods to be reused by subclasses
#Override
public List<T> search(String queryOrNamedQuery) throws ServiceException {
return search(queryOrNamedQuery, null, 0, 0);
}
#SuppressWarnings("unchecked")
public List<T> search(String namedQueryOrHql, Map<String, Object> parameters, int start, int chunkSize) {
try {
Query query = createQuery(namedQueryOrHql, getQueryType(namedQueryOrHql));
if (start > 0) {
query.setFirstResult(start);
}
if (chunkSize > 0) {
query.setMaxResults(chunkSize);
}
addParameters(query, parameters);
List<T> result = query.getResultList();
afterSearch(result);
return result;
} catch (NoResultException nre) {
nre.printStackTrace();
} catch (ClassCastException cce) {
cce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void afterSearch(List<T> result) {
}
// etc...
implementation specific class for BannerImageService:
#Stateless(mappedName="ejb/BannerImageService")
public class BannerImageServiceBean extends BaseServiceBean<BannerImage, Integer> implements BannerImageServiceBeanRemote, BannerImageServiceBeanLocal {
#Override
protected void afterSearch(List<BannerImage> result) {
if (result != null && result.size() == 1) {
BannerImage bannerImage = result.get(0);
bannerImage.getFileReference();
}
super.afterSearch(result);
}
// additional code ...
When I try to fetch my BannerImage class together with it's corresponding FileReference member I always get NULL even though in my DB there is an existing foreign key present:
JPQL:
"SELECT a FROM BannerImage a join fetch a.fileReference WHERE a.id = :id";
Generated SQL:
SELECT t1.ID_BANNER_IMAGE, t1.LABEL_TEXT, t1.LABEL_TITLE, t1.TYPE,
t1.ID_FILE_REFERENCE, t0.ID_FILE_REFERENCE, t0.NAME,
t0.TYPE FROM TB_FILE_REFERENCE t0, TB_BANNER_IMAGE
t1 WHERE (t0.ID_FILE_REFERENCE = t1.ID_FILE_REFERENCE) AND t1.ID_BANNER_IMAGE = 1
in my DB the record shows a correct reference:
BANNER_IMAGE:
1;"";"main";"2bdbb063d0d0ee2939c89763945d9d9e";"banner1.png";"image/png"
If I execute :
select * from TB_FILE_REFERENCE where ID_FILE_REFERENCE = '2bdbb063d0d0ee2939c89763945d9d9e'
I can find the record in the DB, although my EclipseLink JPA Implementation always returns null:
EclipseLink Version 2.5.2-M1
This is how the Entity gets passed from Service Layer to the
Can someone help pointing why the JOIN FETCH is not properly working?
I faced a similar issue and looking closely I see that this issue was happening only to entities recently created/saved. Then I figured that it has something to do with eclipselink cache. I solved this problem by adding this line before making a join fetch JPQL query,
em.getEntityManagerFactory().getCache().evictAll();
em.createQuery("SELECT a FROM BannerImage a join fetch a.fileReference WHERE a.id = :id").getResultList();
HTH!

EntityManager persist() method does not insert record to database => SEVERE: javax.persistence.TransactionRequiredException

I have problem with using EntityManager persist() method.
I am using JSF2.0, glassfish 3, JPA and hibernate, i am not using spring.
I try to add events in an events table with the method persist, but EntityManager persist() method does not insert record to database and i have this error message =>
SEVERE: javax.persistence.TransactionRequiredException
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:163)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.flush(EntityManagerWrapper.java:411)
at dao.EvenementDao.addEvenement(EvenementDao.java:128).
#ManagedBean
#Stateless
public class EvenementDao implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3343483942392617877L;
/**
*
*/
private List<TEvenement> listeEvenement;
private List<SelectItem> listeSelectItemEvnt;
private TEvenement tevenement ;
public EvenementDao() {
}
#PersistenceUnit(unitName="GA2010-ejbPU-dev")
private EntityManagerFactory emf;
#PostConstruct
private void init() {
tevenement = new TEvenement();
}
public List<TEvenement> getListeEvenement() {
EntityManager em = emf.createEntityManager();
TypedQuery<TEvenement> requete = m.createNamedQuery("TEvenement.findPrivateOther",
TEvenement.class);
listeEvenement = requete.getResultList();
return listeEvenement;
}
public TEvenement getEvenement() {
return tevenement;
}
public void setEvenement(TEvenement evenement) {
this.tevenement = evenement;
}
public void addEvenement(){
EntityManager em = emf.createEntityManager();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().
getExternalContext().getSession(false);
Integer codeUser = (Integer) session.getAttribute("codeUser");
tevenement.setUtilCreation(codeUser);
System.out.println("je rentre dans addevenemnt");
try{
System.out.println("i persist "+ em);
em.persist(tevenement);
em.flush();
System.out.println(tevenement.getDetailsEvenement());
FacesMessage message = new FacesMessage("Evenement ajouté avec succès.");
FacesContext.getCurrentInstance().addMessage(null, message);
}catch(Exception e){
e.printStackTrace();
}
}
}
So, this is not working, but the progam enter in the fonction addEvenement , FacesMessage message = new FacesMessage("Evenement ajouté avec succès."); returns me the message as if it was working.
i thouht it was due to my entityMAnager but in fact an ohter function works fine with the same Entity manager so i dont understand.
**public List<TEvenement> getListeEvenement()** {
EntityManager em = emf.createEntityManager();
TypedQuery<TEvenement> requete = em.createNamedQuery("TEvenement.findPrivateOther", TEvenement.class);
listeEvenement = requete.getResultList();
return listeEvenement;
}
this one works fine, the only difference is that in this case the query is a select and in the other case it's a persist so a query that impact the database.
the code of the entity :
#Entity
#Table(name="t_evenements")
#NamedQueries({#NamedQuery(name="TEvenement.findAll", query="SELECT evnt FROM TEvenement evnt"),
#NamedQuery(name="TEvenement.findPrivateOther", query="SELECT evnt FROM TEvenement evnt WHERE evnt.typeEvenement = 6 OR evnt.typeEvenement = 7")})
public class TEvenement implements Serializable {
private static final long serialVersionUID = -1908959833491896991L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="REF_EVENEMENT", unique=true, nullable=false)
private Integer refEvenement;
#Temporal(TemporalType.DATE)
#Column(name="DATE_DEBUT_EVENEMENT")
private Date dateDebutEvenement;
#Temporal(TemporalType.DATE)
#Column(name="DATE_FIN_EVENEMENT")
private Date dateFinEvenement;
#Column(name="DETAILS_EVENEMENT")
private String detailsEvenement;
#Column(name="IS_EVERYDAY")
private byte isEveryday;
#Column(name="RAPPEL_EVENEMENT")
private int rappelEvenement;
public Integer getUtilEvenement() {
return utilEvenement;
}
public void setUtilEvenement(Integer utilEvenement) {
this.utilEvenement = utilEvenement;
}
#Column(name="TITRE_EVENEMENT")
private String titreEvenement;
#Column(name="TYPE_EVENEMENT")
private String typeEvenement;
#Column(name="UTIL_COPIE_EVENEMENT")
private Integer utilCopieEvenement;
#Column(name="UTIL_EVENEMENT")
private Integer utilEvenement;
#Column(name="HEURE_EVENEMENT")
private String heureEvenement;
#Column(name="UTIL_CREATION")
private Integer utilCreation;
public String getHeureEvenement() {
return heureEvenement;
}
public void setHeureEvenement(String heureEvenement) {
this.heureEvenement = heureEvenement;
}
public TEvenement() {
}
public Integer getRefEvenement() {
return this.refEvenement;
}
public void setRefEvenement(int refEvenement) {
this.refEvenement = refEvenement;
}
public Date getDateDebutEvenement() {
return this.dateDebutEvenement;
}
public Integer getUtilCreation() {
return utilCreation;
}
public void setUtilCreation(Integer utilCreation) {
this.utilCreation = utilCreation;
}
public void setUtilCopieEvenement(Integer utilCopieEvenement) {
this.utilCopieEvenement = utilCopieEvenement;
}
public void setDateDebutEvenement(Date dateDebutEvenement) {
this.dateDebutEvenement = dateDebutEvenement;
}
public Date getDateFinEvenement() {
return this.dateFinEvenement;
}
public void setDateFinEvenement(Date dateFinEvenement) {
this.dateFinEvenement = dateFinEvenement;
}
public String getDetailsEvenement() {
return this.detailsEvenement;
}
public void setDetailsEvenement(String detailsEvenement) {
this.detailsEvenement = detailsEvenement;
}
public byte getIsEveryday() {
return this.isEveryday;
}
public void setIsEveryday(byte isEveryday) {
this.isEveryday = isEveryday;
}
public int getRappelEvenement() {
return this.rappelEvenement;
}
public void setRappelEvenement(int rappelEvenement) {
this.rappelEvenement = rappelEvenement;
}
public String getTitreEvenement() {
return this.titreEvenement;
}
public void setTitreEvenement(String titreEvenement) {
this.titreEvenement = titreEvenement;
}
public String getTypeEvenement() {
return this.typeEvenement;
}
public void setTypeEvenement(String typeEvenement) {
this.typeEvenement = typeEvenement;
}
public Integer getUtilCopieEvenement() {
return this.utilCopieEvenement;
}
public void setUtilCopieEvenement(int utilCopieEvenement) {
this.utilCopieEvenement = utilCopieEvenement;
}
}
Do anyone have a idea what am i missing?
The difference isn't that you call persist, the difference is that you call em.flush() which as the error states, requires the EntityManager be joined to a transaction. Makes sure your getListeEvenement() method is wrapped in a transaction, or start one depending on your setup.