Spring Boot - update data - java

I have a little problem.
I try update in repository one column.
Repository
#Modifying
#Query("UPDATE Conversation conversation SET conversation.friend = ?1 WHERE conversation.id = ?2")
fun setConversationInfoById(friend: Boolean, id: UUID): List<Conversation>
Service
fun addDeleteFriend(conversation: Conversation) {
val openedConversation = db.findByIdOrNull(conversation.id)
if (openedConversation == null) db.save(conversation)
else db.setConversationInfoById(openedConversation.friend, openedConversation.id)
}
Controler
#PostMapping("/friend", consumes = [MediaType.APPLICATION_JSON_VALUE])
#ResponseBody
fun friend(#RequestBody conversation: Conversation) = service.addDeleteFriend(conversation)
It's about the flag - boolean whos will change status column "friend".
When I'm starting BE the console shows me this error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with
name 'conversationController' defined in file [####]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'conversationService' defined in file [####]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'conversationRepository' defined in com.###.backend.repository.ConversationRepository defined in
#EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for
public abstract java.util.List com.###.backend.repository.ConversationRepository.setConversationInfoById(boolean,java.util.UUID)!
Reason: Failed to create query for method public abstract java.util.List
com.##.backend.repository.ConversationRepository.setConversationInfoById(boolean,java.util.UUID)!
No property 'setConversationInfoById' found for type 'Conversation'!; nested exception is
java.lang.IllegalArgumentException: Failed to create query for method public abstract
java.util.List com.###.backend.repository.ConversationRepository.setConversationInfoById(boolean,java.util.UUID)!
No property 'setConversationInfoById' found for type 'Conversation'!
I tried all option, but I don't know what is the problem ..

query method changes Conversation data by id, which is one data.
So it will be return one Conversation object.
try to change List to Conversation.
or, I don't know well, but quertymethod naming convention is exist, so try to check out.

Related

Inject #Value to a Path variable directly

I want to inject Path variable directly without converting it from string like this:
#Value("${screenshot.path}")
private Path path;
property file:
screenshot.path=D:\Projects\myproject\screenshots
Error:
Unsatisfied dependency expressed through field 'path'; nested
exception is org.springframework.beans.TypeMismatchException: Failed
to convert value of type 'java.lang.String' to required type
'java.nio.file.Path'; nested exception is
java.lang.IllegalArgumentException: Failed to retrieve file for class
path resource [D:/Projects/myproject/screenshots]
Is there a way to do that without injecting String and then doing Paths.get?
My mistake, it does everything automatically, just fixed path format like this:
screenshot.path=D:\\Projects\\myproject\\screenshots

Binding <annotationField> to advice body getting inconsistent binding [duplicate]

I am trying to apply a #before aspect on two different methods in two different paths
class Service1{
public Object applyX(X x){
//code
}
}
class Service2{
public OtherObject applyY(Y y){
//code
}
}
and I have my aspect class:
#Aspect
#Component
public class MyProcessor {
#Before("execution(* com.a.b.c.Service1.applyX"
+ " (com.xp.X)) "
+ "&& args(engineEvaluationRequest) || "
+ "execution(* com.a.b.d.Service2.applyY"
+ " (com.yp.Y))"
+ "&& args(y)")
public void process(X x ,Y y){
//code
}
}
I am getting an error org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'objectMapperConfigurer' defined in class path resource [springfox/documentation/spring/web/SpringfoxWebMvcConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 inconsistent binding
and I don't understand what went wrong. can I get help?
Thanks!
The error message inconsistent binding already says it: Your variable binding with args() is inconsistent insofar as it is ambiguous due to the || (logical or) operator. Either X is found and can be bound or Y, but the other one would be undefined. You might have assumed that if a variable is not bound it defaults to null, but this assumption is wrong. AspectJ does not work like that. Your pointcut must bind variables unambiguously to the corresponding advice parameters.
Edit: Because || is a logical OR and thus non-exclusive (unlike XOR), it might even happen that two OR branches match at the same time. Then which matching argument or annotation should be bound? This really is ambiguous.
So how can you fix it? Just use two pointcut/advice pairs instead of just one. If the advice is complex and contains a lot of code you can still factor out that code into a helper method taking a JoinPoint parameter or so.

Spring bean with #Autowire in superclass

I have a subclass like below:-
#Component
public class Subclass extends Superclass {
//few inherited methods implementation
}
Superclass is like below:-
#Component
public class Superclass implements InterfaceA {
#Autowired
#Qualifier("envBean")
private EnvironmentBean envBean;
private DateTime effective_date = envBean.getProperty("effective.date");
}
Now while deploying the application, I am getting below errors
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name "Subclass"
Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [Subclass]:Constructor threw exception; nested exception is java.lang.NullPointerException.
and finally I saw -
Caused by: java.lang.NullPointerException: null
at Superclass <init> (SuperClass.java:{lineNumber}
which is at the below line :-
**envBean.getProperty("effective.date");**
I have tried using constructor injection of EnvironmentBean property from the subclass itself
Tried configuring it in xml and to instantiate Superclass bean with constructor injection.
Does someone have any idea how to resolve it?
Maybe you can try interface -> InitializingBean, and override method 'afterPropertiesSet', then you can assign effective_date value. just like:
#Override
public void afterPropertiesSet() {
effective_date = envBean.getProperty("effective.date");
}
It seems that this is because Spring has to first create an instance of the class Superclass and only then inject EnvironmentBean. That is, when the class Superclass is instantiated, Java will try to instantiate the field DateTime effective_date even before Spring tries to inject the dependency #Autowired #Qualifier("envBean") private EnvironmentBean envBean;. At this time, envBean refers to null. Hence, this will surely throw an NPE. (My view.)
So, not sure if this is really related to the class hierarchy itself.
There must be a class called EnvironmentBean It must be annotated with any one of Spring stereotype shown in doc https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/package-summary.html
Component - Indicates that an annotated class is a "component".
Controller - Indicates that an annotated class is a "Controller"
Indexed - Indicate that the annotated element represents a stereotype for the index.
Repository - Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".
Service - Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."

Spring JPA Stored Procedure with a null value?

I have a stored procedure and it's being called from a JpaRepository implementation as such
#Repository
public interface DataMartRepo extends JpaRepository<DataMartDAO, String> {
#Procedure(procedureName = "dbo.txn_ETL")
public void txnETL(
#Param("txId") String txId,
#Param("inId") String inId,
#Param("proc") String proc,
#Param("qtys") String qtys);
Now, this works fine, expect for when "proc" is a null value, in which case it throws an exception:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/Authenticator]
threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException:
Error calling CallableStatement.getMoreResults; nested exception is org.hibernate.exception.GenericJDBCException:
Error calling CallableStatement.getMoreResults] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: The value is not set for the parameter number 3.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.buildParamTypeDefinitions(SQLServerPreparedStatement.java:260)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.buildPreparedStrings(SQLServerPreparedStatement.java:219)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doPrepExec(SQLServerPreparedStatement.java:612)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:400)
[...]
How do I deal with null values? Setting all Strings to "" doesn't offer null inserts.
Looks like the parameter with null value in SP call is open issue. Please see https://hibernate.atlassian.net/browse/HHH-9007

Java: how to make sense out of cryptic stack traces?

While trying to run a unit test, I get the following stack trace. I don't even know where to start looking (read my comment below).
Where should I start and what would you do to solve this?
(note that the following stack trace is basically how I get it from Eclipse, without any formatting or anything: just countless lines of about 120 chars each) [I only pasted the five lines where apparently the problem happens]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'acceptanceChain' defined in class path resource
[.../chain/connector/...xml]: Cannot resolve reference to bean 'xxxCommand' while setting constructor argument with key [0]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxxCommand' defined in class path resource
[.../bl/chain/connector/....xml]: Cannot create inner bean 'yyyDTO#1d95da7' of type [yyyListDTO] while setting bean property 'yyyListDTO'; nested exception
is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'yyyListDTO#1d95da7' defined in class path resource
[zzz.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [boolean]: Could not convert constructor argument value of type
[java.util.LinkedHashMap] to required type [boolean]: Failed to convert value of type [java.util.LinkedHashMap] to required type [boolean]; nested exception
is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.LinkedHashMap] to required type [boolean]: no matching editors or conversion
strategy found
Any help is very welcome.
Take the signifiant part of the message :
Error creating bean with name 'acceptanceChain' defined in class path resource
I guess the bean acceptanceChain can't be instanciated. Maybe because it has a boolean parameter in which one tries to inject a LinkedHashMap, as the following message states :
Failed to convert value of type [java.util.LinkedHashMap] to required type [boolean]

Categories