I'm developing a small stock control application using Java-SE8, JPA and Hibernate and this is my first contact with ORMs and the Persistence API. All was fine, but my tests failed when I created a method to retrieve things on the database(MySQL) and I get an:
"IllegalStateException: Entity Manager is closed."
I really don't know what is happening and spent almost two days trying to fix this. Can anyone help me, please?
Here are the pieces of code that trigger the error.
DAO.java
private EntityManager getEntityManager() {
EntityManagerFactory factory = null;
EntityManager entityManager = null;
try {
factory = Persistence.createEntityManagerFactory("stockcontrol");
entityManager = factory.createEntityManager();
} finally {
factory.close();
}
return entityManager;
}
public <T> List<T> findAllByClass(Class clazz) {
EntityManager manager = null;
try{
manager = getEntityManager();
String hql = "FROM " + clazz.getName();
Query hqlQuery = manager.createQuery(hql);
return hqlQuery.getResultList();
} finally {
manager.close();
}
}
Moneytory.java
DAO dao = new DAO();
public static void registerProduct(String name, int amount, double unitPrice,
String strCategory) throws RegisterException {
List<Product> products = dao.findAllByClass(Product.class);
List<Category> categories = dao.findAllByClass(Category.class);
if(products.contains(getProductByName(name)))
throw new RegisterException("The product already exists");
Product newProduct = null;
Category newCategory = null;
try{
newCategory = new Category(strCategory);
newProduct = new Product(name, amount, unitPrice, newCategory);
} catch(IllegalArgumentException e){
throw new RegisterException(e.getMessage());
}
if(!categories.contains(newCategory))
dao.persist(newCategory);
dao.persist(newProduct);
dao.flush();
}
And the StackTrace I've got:
java.lang.IllegalStateException: EntityManager is closed
at org.hibernate.jpa.internal.EntityManagerImpl.checkOpen(EntityManagerImpl.java:105)
at org.hibernate.jpa.internal.EntityManagerImpl.checkOpen(EntityManagerImpl.java:96)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:326)
at br.edu.noorg.moneytory.dao.DAO.findAllByClass(DAO.java:154)
at br.edu.noorg.moneytory.core.MoneyTory.registerProduct(MoneyTory.java:111)
at br.edu.noorg.moneytory.test.MoneyToryTest.mustRegisterProduct(MoneyToryTest.java:92)
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:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
So you created an EntityManagerFactory (EMF), then an EntityManager (from the EMF), and then closed the EntityManagerFactory… which will close all of the EntityManager that it owns. Don't close the EMF!!
Related
I am deleloping a small spring and hibernate program, And i want to get sum of values from database. For that i written below code
public double getDataFromDb(String num) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
double result=0;
Query getSumquery=(Query)session.createQuery("select sum(amount) from User_Master where =:num");
getSumquery.setParameter("num",num);
List list =getSumquery.list();
result=(double) list.get(0);
tx.commit();
Here i am getting exception in list line.When running from junit testcasethe Exception is like below
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.abc.process.hbmfiles.Number.num
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:35)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:183)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:3596)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:3312)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:181)
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:218)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:397)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:87)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:38)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:491)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1563)
at org.hibernate.loader.Loader.doQuery(Loader.java:673)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2213)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at com.creditprocess.daoimpl.EvaluationDAOImpl.getCrtTotal(EvaluationDAOImpl.java:294)
at com.creditprocess.managerimpl.EvaluationManagerImpl.saveData(EvaluationManagerImpl.java:264)
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:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy28.saveData(Unknown Source)
at EvaluationTest.sendDetails(EvaluationTest.java:150)
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:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field com.caja.creditprocess.hbmfiles.Doi_Master.dni to java.lang.String
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:393)
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:32)
... 62 more
These are my entities
User_Master.java
#Entity
#Table(name="User_Master")
public class User_Master implements Serializable{
#Id
#Column(name="User_master_id")
private String user_master_id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="num")
private Number num;
}
Number.java
#Entity
#Table(name="Number")
public class Number implements Serializable{
#Id
#Column(name="num")
private String num;
}
If you are using conditional statement then you have to define some condition after where so here I think You are mission your Entity Variable (num) reference....
public double getDataFromDb(String num) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
double result=0;
Query getSumquery=(Query)session.createQuery("select sum(u.amount) from User_Master u where u.num =:num");
getSumquery.setParameter("num",num);
List list =getSumquery.list();
result=(double) list.get(0);
tx.commit();
}
While using reflection, I also faced the same problem and the mistake I have done was instead of writing:
Arrays.asList(object.getClass().getDeclaredFields()).forEach(field -> {
field.setAccessible(true);
try {
System.out.pringln(String.valueOf(field.get(object)));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
I wrote:
Arrays.asList(object.getClass().getDeclaredFields()).forEach(field -> {
field.setAccessible(true);
try {
System.out.pringln(String.valueOf(field.get(object.getField())));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
meaning to say that I tried to get objects field while giving its value as an argument.
I'm testing Tinkerpop frames. I have a relationship similar to Person Knows Person but everytime I test my code it gives me this error
com.orientechnologies.orient.core.exception.OSchemaException: Cannot change the schema while a transaction is active. Schema changes are not transactional
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.saveInternal(OSchemaShared.java:956)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.releaseSchemaWriteLock(OSchemaShared.java:751)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.doCreateClass(OSchemaShared.java:385)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:314)
at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass(OSchemaProxy.java:77)
at com.tinkerpop.blueprints.impls.orient.OrientElement$1.call(OrientElement.java:469)
at com.tinkerpop.blueprints.impls.orient.OrientElement$1.call(OrientElement.java:465)
at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.executeOutsideTx(OrientBaseGraph.java:1658)
at com.tinkerpop.blueprints.impls.orient.OrientElement.checkForClassInSchema(OrientElement.java:465)
at com.tinkerpop.blueprints.impls.orient.OrientEdge.getClassName(OrientEdge.java:474)
at com.tinkerpop.blueprints.impls.orient.OrientEdge.createDocument(OrientEdge.java:511)
at com.tinkerpop.blueprints.impls.orient.OrientEdge.convertToDocument(OrientEdge.java:441)
at com.tinkerpop.blueprints.impls.orient.OrientEdge.setProperty(OrientEdge.java:314)
at com.tinkerpop.frames.annotations.PropertyAnnotationHandler.processElement(PropertyAnnotationHandler.java:34)
at com.tinkerpop.frames.annotations.PropertyAnnotationHandler.processElement(PropertyAnnotationHandler.java:11)
at com.tinkerpop.frames.FramedElement.invoke(FramedElement.java:89)
at com.sun.proxy.$Proxy7.setWeight(Unknown Source)
at com.spicegraph.test.domain.test.DbTest.addNewStuffToDb(DbTest.java:52)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I'm using OrientDb as the graph provider. What could have possible gone wrong?
Here is my code:
public interface Ingredient extends VertexFrame{
#Property("name")
public String getName();
#Property("name")
public void setName(String name);
#Adjacency(label="usedwith", direction=Direction.BOTH)
public Iterable<Ingredient> getUsedWithIngredient();
#Adjacency(label = "usedwith")
public Ingredient addUsedWithNewIngredient();
#Incidence(label = "usedwith")
public UsedWithEdge addUsedWithIngredient(final Ingredient person);
#Adjacency(label = "usedwith")
public void removeUsedWithIngredient(final Ingredient person);
#Incidence(label = "usedwith")
public void removeUsedWith(final UsedWithEdge usedWith);
}
public interface UsedWithEdge extends EdgeFrame {
#Property("weight")
public void setWeight(int weight);
#Property("weight")
public int getWeight();
#OutVertex
Ingredient getOutIngredient();
#InVertex
Ingredient getInIngredient();
}
and this is a snippet of the test case
Ingredient v1=framedGraph.addVertex(null, Ingredient.class);
Ingredient v2=framedGraph.addVertex(null, Ingredient.class);
v1.setName("cumin");
v1.setConservAndStoring("conservation yearly");
v1.setPrepAndUse("prep prep ");
v2.setName("cinnamon");
v2.setAbout("about is about");
v2.setConservAndStoring("conservation is daily");
UsedWithEdge edge=v2.addUsedWithIngredient(v2);
edge.setWeight((1)); // << error is thrown here !!
framedGraph.getBaseGraph().commit();
This is an OrientDb problem. I used OrientGraphNoTx
OrientGraphNoTx graph=new OrientDbGenericDao().graphInstance();
FramedGraphFactory factory = new FramedGraphFactory(); // make sure you reuse the factory when creating new framed graphs.
framedGraph = factory.create(graph); // wrap the base graph
and it worked pretty well.
I have method that saves entity into database.It is:
#Cacheable(value = EMPLOYEE_CACHE,key="#employee.id")
public Employee createEmployee(Employee employee) {
try {
entityManager.persist(employee);
} catch (Exception e) {
return null;
}
return employee;
}
I want the result Employee to be cached by key = id of Employee. Employee's id is assigned after entityManager,persist method runs.
I know that #Cacheable works because of AOP. By default, it stores employee into cache before method createEmployee runs.
How to force org.springframework.cache.annotation.#Cacheable to store into cache after method execution?
The stacktrace :
java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) CachePutOperation[public com.livelessons.spring.springcore.entities.Employee com.livelessons.spring.springcore.service.EmployeeServiceImpl.createEmployee(com.livelessons.spring.springcore.entities.Employee)] caches=[employees] | key='#employee.id' | condition='' | unless=''
at org.springframework.cache.interceptor.CacheAspectSupport.inspectCacheUpdates(CacheAspectSupport.java:371)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:202)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy30.createEmployee(Unknown Source)
at com.livelessons.spring.springcore.EmployeeServiceTest.saveEmployee(EmployeeServiceTest.java:59)
at com.livelessons.spring.springcore.EmployeeServiceTest.testSpringCacheable(EmployeeServiceTest.java:51)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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)
You may define your own annotation, e.g. #defferedCacheable, and then using aop to store/read the object in cache programmatically.
You should use #CachePut instead of #Cacheable (with the the same attributes):
As opposed to {#Cacheable} annotation,
this annotation does not cause the target method to be skipped
rather it always causes the method to be invoked and its result to be placed into the cache.
A little bit late, but maybe will be useful to someone.
#Cacheable define the key from method argument, not the return value, so if you pass new Employee object without id you get null.
Straightforward solution may looks like this:
public Employee createEmployeeWithCaching(Employee employee) {
Employee employee = persistEmployee(employee);
return saveEmployeeInCache(employee);
}
private Employee persistEmployee(Employee employee) {
try {
return entityManager.persist(employee);
} catch (Exception e) {
return null;
}
}
#Cacheable(value = EMPLOYEE_CACHE,key="#employee.id")
private Employee saveEmployeeInCache(Employee employee) {
return employee;
}
But think twice if you really need to return null in catch block. Obviously it will lead to other exception in saveEmployeeInCache method.
I am running a simple JUnit test. The test is:
private HangmanModel model;
private WordsToGuess word;
public void setUp()
{
model = new HangmanModel();
word = new WordsToGuess();
}
#Test
public void addWordAndChoose()
{
WordsToGuess testWord = new WordsToGuess("ahoy");
model.addWord(testWord); <---- NullPointerException
String foundWord = model.randomWord();
assertEquals("Not found the word", testWord, foundWord);
}
In WordsToGuess, the constructor is:
public WordsToGuess(String w)
{
word = w;
}
In HangmanModel, the addWord method is:
private ArrayList<WordsToGuess> words;
words = new ArrayList<WordsToGuess>();
public void addWord(WordsToGuess w)
{
words.add(w);
}
This is a REALLY weird NullPointerException since everything should run perfectly fine. It is copied almost word for word from a similar project. Here is the Stack trace:
java.lang.NullPointerException
at testing.HangmanModelTest.addWordAndChoose(HangmanModelTest.java:22)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
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)
The #Before annotation is required before the setup method for JUnit 4
#Before
public void setUp() {
...
}
I have a problem during studying Hibernate. I wrote UnitTest and there i try to add object into DB. All selects are working properly, but insert not working so.
public class HibernateTutorial extends BaseTest {
#Autowired
SessionFactory sessionFactory;
#Test
#Transactional
public void hibernateTutorial() {
#SuppressWarnings("unchecked")
List<User> users = sessionFactory.getCurrentSession().createQuery("from User").list();
sessionFactory.getCurrentSession().saveOrUpdate(new User("HiberTest", "HiberPass", "Hiber#Mail.ru", "HiberSurname",
"HiberLastname", "HiberAddress", "123432"));
}
I also try something like this
public class HibernateTutorial extends BaseTest {
#Autowired
SessionFactory sessionFactory;
#Test
#Transactional
public void hibernateTutorial() {
#SuppressWarnings("unchecked")
List<User> users = sessionFactory.getCurrentSession().createQuery("from User").list();
sessionFactory.getCurrentSession().saveOrUpdate(
new User("HiberTest", "HiberPass", "Hiber#Mail.ru", "HiberSurname", "HiberLastname", "HiberAddress", "123432"));
sessionFactory.getCurrentSession().getTransaction().commit();
}
}
It throw me Exception that Transaction not succesfully started, but it add user
Here is an Exception
org.springframework.transaction.TransactionSystemException: Could not
roll back Hibernate transaction; nested exception is
org.hibernate.TransactionException: Transaction not successfully
started at
org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:679)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:845)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:822)
at
org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:512)
at
org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:290)
at
org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:183)
at
org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:406)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:90)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) 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:236) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
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)
Caused by: org.hibernate.TransactionException: Transaction not
successfully started at
org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:183)
at
org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:676)
... 25 more
I can see 2 problems in your code.
1 -Your transactions have not been started.
Answer: You have to use the getSession().beginTransaction() method before you do anything on Database.
2 - There's no rollback method in case your transactions fails
Answer: Use a try-catch block, see example below.
Example of my code:
public void salvarDB(Object object)
{
Session session = HibernateUtil.getSession();
HibernateUtil.beginTransaction();
try
{
session.save(object);
HibernateUtil.commit();
avisos.salvoComSucesso(object);
}
catch(ConstraintViolationException e)
{
avisos.registroJaInserido(object);
HibernateUtil.rollback();
}
catch (Exception ex) {
avisos.falhaAoSalvar(object);
HibernateUtil.rollback();
}
finally {
HibernateUtil.closeSession();
}
}