Mybatis and invalid types - java

I use mybatis 3.2.2, PostgreSQL and get the "Error instantiating class xxx with invalid types or values". The exception is triggered when calling getPluginId(). Here is my configuration:
mapper.xml:
<resultMap type="my.class.plugins.Plugin" id="pluginMap">
<constructor>
<idArg column="id" javaType="_int"/>
<arg column="dtype" javaType="String"/>
</constructor>
</resultMap>
and this a problematic method:
<select id="getPluginById" resultMap="pluginMap">
SELECT *
FROM public.plugin
WHERE id = #{id, jdbcType=NUMERIC}
</select>
a default constructor:
public abstract class Plugin {
...
public Plugin(int id, String name) {
this.id = id;
this.name = name;
}
}
an the exception:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Error instantiating class my.class.plugins.Plugin with invalid types (int,String,) or values (7418,FORWARD,). Cause: java.lang.InstantiationException
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:364)
at $Proxy15.selectOne(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:159)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:43)
at $Proxy16.getPluginById(Unknown Source)
at my.class.service.UserServiceImpl.getUserById(UserServiceImpl.java:44)
at my.class.persistence.db.DbUserDaoTest.testLoading(DbUserDaoTest.java:74)
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: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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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)
Caused by: org.apache.ibatis.reflection.ReflectionException: Error instantiating class my.class.plugins.Plugin with invalid types (int,String,) or values (7418,FORWARD,). Cause: java.lang.InstantiationException
at org.apache.ibatis.reflection.factory.DefaultObjectFactory.instantiateClass(DefaultObjectFactory.java:83)
at org.apache.ibatis.reflection.factory.DefaultObjectFactory.create(DefaultObjectFactory.java:45)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.createParameterizedResultObject(FastResultSetHandler.java:415)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.createResultObject(FastResultSetHandler.java:384)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.createResultObject(FastResultSetHandler.java:365)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.getRowValue(FastResultSetHandler.java:261)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.handleRowValues(FastResultSetHandler.java:216)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.handleResultSet(FastResultSetHandler.java:188)
at org.apache.ibatis.executor.resultset.FastResultSetHandler.handleResultSets(FastResultSetHandler.java:154)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:57)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:70)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:57)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:259)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:132)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:115)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:104)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:62)
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.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:354)
... 37 more
Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.apache.ibatis.reflection.factory.DefaultObjectFactory.instantiateClass(DefaultObjectFactory.java:67)
... 59 more

You need to have an empty constructor:
public Plugin() {
}

Did you define the Person class as abstract?
This is not PostgreSQL or MyBatis issue in my opinion. The VM can't create instance of Person, but constructor args & types is correct.
Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)

Try removing the "abstract" and
public Plugin(int id, String name) {
this.id = id;
this.name = name;
}
From the class

Related

java.lang.illegalargumentexception cannot set java.lang.string field to java.lang.String

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.

MappingException: Invalid path reference club.name! Associations can only be pointed to directly or via their id property

I'm using Spring Data Mongodb library and I don't know to find by #Query an element in two collections joined with #DBRef, like this:
User:
#Document
public class User {
#Id
#JsonSerialize(using=ObjectIdSerializer.class)
private ObjectId id;
#CreatedDate
private Date dateCreated = new Date();
#LastModifiedDate
private Date dateModified = new Date();
#NotEmpty
#Indexed
private String name;
#Language
private String lang;
#NotEmpty
#DBRef
private Club club;
...
Club:
#Document
public class Club {
#Id
#JsonSerialize(using=ObjectIdSerializer.class)
private ObjectId id;
#Indexed(unique = true)
private String name;
private Address address;
...
UserRepository:
#Query("{\"$or\":"
+ "["
+ "{\"name\" : {\"$regex\" : ?0, \"$options\": \"i\"}}, "
+ "{\"club.name\" : {\"$regex\" : ?0, \"$options\": \"i\"}} "
+ "]"
+ "}")
public Page<User> findAll(String query, Pageable pageable);
error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.data.mapping.model.MappingException: Invalid path reference club.name! Associations can only be pointed to directly or via their id property!
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at it.stasbranger.rotarylive.controller.UserControllerTests.showUsersFilterTEST3(UserControllerTests.java:137)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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 com.lordofthejars.nosqlunit.core.AbstractNoSqlTestRule$1.evaluate(AbstractNoSqlTestRule.java:72)
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:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
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: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: org.springframework.data.mapping.model.MappingException: Invalid path reference club.name! Associations can only be pointed to directly or via their id property!
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.getPath(QueryMapper.java:853)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.(QueryMapper.java:729)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.(QueryMapper.java:706)
at org.springframework.data.mongodb.core.convert.QueryMapper.createPropertyField(QueryMapper.java:216)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:122)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedKeyword(QueryMapper.java:235)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:100)
at org.springframework.data.mongodb.core.MongoTemplate.count(MongoTemplate.java:724)
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery$PagedExecution.execute(AbstractMongoQuery.java:268)
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:106)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:462)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy132.findAll(Unknown Source)
at it.stasbranger.rotarylive.service.UserServiceImpl.findAll(UserServiceImpl.java:71)
at it.stasbranger.rotarylive.controller.UserController.showUsers(UserController.java:53)
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.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
... 42 more
It is not possible to query on DBRef in MongoDB itself. Thus it is not possible to do so using Spring Data MongoDB. The resulting error is very clear about that in its message "Associations can only be pointed to directly or via their id property!"
As the error message implies, in the query, it will only allow using the id of the referenced document.
Others already answered why this error happens. If you must have this I suppose there are two ways to go about it.
query clubDB first and get ID of matching names. Have user select on the options and use those selected IDs to search userDB. Sort of like you have to select an option in a drop-down like state selection.
query clubDB and get a list of all IDs of matching names and query userDB for all these IDs. With this option, user probably won't have to change how they interact with the application.

Mockito can't mock an interface?

I'm having difficulties understanding how to mock/stub an interface with Mockito.
This simple scenario...
public interface Adder
{
int add(int a, int b);
}
public class Calculator
{
Adder _adder;
public Calculator(Adder adder)
{
_adder = adder;
}
public int add(int a, int b)
{
return _adder.add(a, b);
}
}
public class MockitoTester
{
#Test
public void can_mock()
{
Adder adder = mock(Adder.class);
Calculator sut = new Calculator(adder);
assertThat(sut).isNotNull();
}
}
Is giving me this error...
java.lang.NoClassDefFoundError: net/bytebuddy/dynamic/scaffold/subclass/ConstructorStrategy
at org.mockito.internal.creation.bytebuddy.CachingMockBytecodeGenerator.<init>(CachingMockBytecodeGenerator.java:20)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.<init>(ByteBuddyMockMaker.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:33)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:12)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:11)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:23)
at org.mockito.internal.MockitoCore.<init>(MockitoCore.java:44)
at org.mockito.Mockito.<clinit>(Mockito.java:1101)
at com.jnericks.testutils.MockitoTester.can_mock(MockitoTester.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
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.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 40 more
Mockito depends on the artifact net.bytebuddy:byte-buddy. See this POM definition from the Maven repositories. Make sure you get the mockito-all artifact which includes all dependencies in one Jar.
If you are using Maven, then it should automatically resolve the dependency when using mockito-core. You can run mvn dependency:tree on the project to see the hierarchy of your project's dependencies.

Tinkerpop frames: Cannot change the schema while a transaction is active

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.

unable to resolve java.lang.NullPointerException

I have three classes- class 'ABC' 'PQR' and 'XYZ'
class ABC
#Test
public void getModulesid() throws Exception {
Long GrpId= PQR.getExistingGroupId();
System.out.println(GrpId);
}
class PQR
public static Long getExistingGroupId() throws Exception {
Long GrpId;
List<MsecBusGroups> busGroupsList = new ArrayList<MsecBusGroups>();
busGroupsList=XYZ.getBusGroups();
if (busGroupsList!=null){
MsecBusGroups It1=busGroupsList.get(busGroupsList.size()-1);
GrpId=It1.getId();
return GrpId;
} else {
throw new Exception("BUSINESS GROUPS LIST RETURNED IS NULL");
}
}
class XYZ
public List<MsecBusGroups> getBusGroups() throws PersistenceException {
final String METHOD_NAME = "getBusGroups()";
LogHelper.logEntry(CLASS_NAME, METHOD_NAME);
List<MsecBusGroups> list = null;
try {
Query q = em.createNamedQuery("getBusGroups");
list = q.getResultList();
if (list == null) {
LogHelper.debug(CLASS_NAME, METHOD_NAME, "No Record Found");
}
...
}
When I run the test method in ABC class its throwing java.lang.NullPointerException.
java.lang.NullPointerException
at com.causeway.platform.security.model.actions.BusServiceActions.getExistingGroupId(BusServiceActions.java:202)
at com.causeway.platform.security.model.serviceImpl.SecurityBusServiceTest.testDeleteModule(SecurityBusServiceTest.java:1231)
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: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.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
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: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:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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)
I see that getBusGroups() is not static. This means that in busGroupsList=XYZ.getBusGroups(); XYZ is a variable. The NPE is probably thrown because XYZ is null.
securityBusService is probably null. Where is it initialized?

Categories

Resources