Mybatis - Invalid bound statement (not found) - spring-boot

I have created a new project using mybatis to connect to a mysql database. This is my second project using mybatis so I am familiar with it but am getting the following error when I call the save method:
2019-03-05 10:08:01.031 ERROR 86438 --- [nio-9905-exec-1] c.q.f.r.c.ResolveRestController : Error starting preset: Invalid bound statement (not found): com.qlsdistribution.fps.resolverender.data.mybatis.mapper.ResolveJobReportMapper.saveResolveJobReport
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.qlsdistribution.fps.resolverender.data.mybatis.mapper.ResolveJobReportMapper.saveResolveJobReport
at org.apache.ibatis.binding.MapperMethod$SqlCommand.(MapperMethod.java:232) ~[mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.binding.MapperMethod.(MapperMethod.java:50) ~[mybatis-3.5.0.jar:3.5.0]
at org.apache.ibatis.binding.MapperProxy.lambda$cachedMapperMethod$0(MapperProxy.java:62) ~[mybatis-3.5.0.jar:3.5.0]
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660) ~[na:1.8.0_101]
at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:62) ~[mybatis-3.5.0.jar:3.5.0]
.....
My mybatis config file is as follows (in src/main/resources):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- Mybatis logging -->
<setting name="logImpl" value="LOG4J2"/>
</settings>
<typeAliases>
<package name="com.qlsdistribution.fps.resolverender.data.mybatis.domain"/>
</typeAliases>
<mappers>
<mapper resource="mapper/ResolveJobReport.xml"/>
<!-- <mapper resource="com/qlsdistribution/fps/resolverender/data/mybatis/mapper/ResolveJobReport.xml"/> -->
</mappers>
</configuration>
As you can see I have tried different locations for the mapper xml file but if I put invalid syntax in the mapper xml file, it fails with invalid syntax (SAXParseException) instead so I know the mapper xml file is being read.
The mapper xml file is as follows (in src/main/resources/mapper):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qlsdistribution.fps.resolverender.data.mybatis.ResolveJobReportMapper">
<resultMap id="resolveJobReport" type="com.qlsdistribution.fps.resolverender.data.mybatis.domain.ResolveJobReport">
<result property="id" column="id" />
<result property="fpsProjectName" column="fps_project_name" />
<result property="inputPath" column="input_path" />
<result property="destinationPath" column="destination_path" />
<result property="presetName" column="preset_name" />
<result property="ipAddress" column="ip_address" />
<result property="frameRate" column="frame_rate" />
<result property="resolveProjectName" column="resolve_project_name" />
<result property="width" column="width" />
<result property="height" column="height" />
<result property="renderFormat" column="render_format" />
<result property="renderCodec" column="render_codec" />
<result property="scriptPath" column="script_path" />
<result property="cliOutput" column="cli_output" />
<result property="jobStartedDate" column="job_started_date" />
<result property="jobFinishedDate" column="job_finished_date" />
<result property="createdBy" column="created_by" />
<result property="createdDate" column="created_date" />
<result property="modifiedBy" column="modified_by" />
<result property="modifiedDate" column="modified_date" />
</resultMap>
<select id="getAllResolveJobReports" resultMap="resolveJobReport">
SELECT id, fps_project_name, input_path, destination_path, preset_name, ip_address, frame_rate, resolve_project_name, width, height,
render_format, render_codec, script_path, cli_output, job_started_date, job_finished_date, created_by, created_date, modified_by, modified_date
FROM resolve_job_report
WHERE fps_setting_id = #{value}
ORDER by id desc;
</select>
<select id="getAllResolveJobReportsById" parameterType="Long" resultMap="resolveJobReport">
SELECT id, fps_project_name, input_path, destination_path, preset_name, ip_address, frame_rate, resolve_project_name, width, height,
render_format, render_codec, script_path, cli_output, job_started_date, job_finished_date, created_by, created_date, modified_by, modified_date
FROM resolve_job_report
WHERE id = #{value};
</select>
<insert id="saveResolveJobReport" parameterType="com.qlsdistribution.fps.resolverender.data.mybatis.domain.ResolveJobReport">
INSERT INTO resolve_job_report
(fps_project_name, input_path, destination_path, preset_name, ip_address, frame_rate, resolve_project_name, width, height,
render_format, render_codec, script_path, cli_output, job_started_date, job_finished_date, created_by)
VALUE
(#{fpsProjectName},#{inputPath},#{destinationPath},#{presetName},#{ipAddress},#{frameRate},#{resolveProjectName},#{width},#{height},
#{renderFormat},#{renderCodec}, #{scriptPath},#{cliOutput},#{jobStartedDate},#{jobFinishedDate},#{createdBy});
</insert>
<update id="updateResolveJobReportById" parameterType="resolveJobReport">
UPDATE resolve_job_report
SET
fps_project_name = #{fpsProjectName},
input_path = #{inputPath},
destination_path = #{destinationPath},
preset_name = #{presetName},
ip_address = #{ipAddress},
frame_rate = #{frameRate},
resolve_project_name = #{resolveProjectName},
width = #{width},
height = #{height},
render_format = #{renderFormat},
render_codec = #{renderCodec},
script_path = #{scriptPath},
cli_output = #{cliOutput},
job_started_date = #{jobStartedDate},
job_finished_date = #{jobFinishedDate},
modified_by = #{modifiedBy}
where id = #{id};
</update>
<delete id="deleteResolveJobReporttById" parameterType="Long">
DELETE FROM resolve_job_report
WHERE id = #{value}
</delete>
</mapper>
My application.properties file contains the following (in (src/main/resources):
spring.datasource.url=jdbc:mysql://localhost:3306/fpsresolvetool?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.schema=classpath:schema.sql
mybatis.config-location=classpath:SqlMapConfig.xml
I have even tried using the latest mybatis versions in my pom.xml:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
My spring boot application is as follows:
#SpringBootApplication
#EnableScheduling
#ComponentScan({"com.qlsdistribution.fps.resolverender"})
#EnableJms
#MapperScan("com.qlsdistribution.fps.resolverender.data.mybatis")
public class FPSResolveRenderApp implements WebMvcConfigurer {
/** UTF-8 Character set name */
private static final String UTF_8 = "UTF-8";
/** Logger */
private static final Logger logger = LogManager.getLogger(FPSResolveRenderApp.class);
public static void main(String[] args) {
new SpringApplicationBuilder(FPSResolveRenderApp.class).run(args);
}
/**
* Creates and gets the FilterRegistrationBean
* #return
*/
#Bean
public FilterRegistrationBean<CharacterEncodingFilter> filterRegistrationBean() {
FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<CharacterEncodingFilter>();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding(UTF_8);
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
}
The mapper interface is as follows:
#Mapper
public interface ResolveJobReportMapper {
public List<ResolveJobReport> getAllResolveJobReports();
public List<ResolveJobReport> getAllResolveJobReports(RowBounds rowBounds);
public List<ResolveJobReport> getAllResolveJobReportsById(Long id);
public List<ResolveJobReport> getAllResolveJobReportsById(Long id, RowBounds rowBounds);
public void saveResolveJobReport(ResolveJobReport resolveJobReport);
public void updateResolveJobReportById(ResolveJobReport resolveJobReport);
public void deleteResolveJobReporttById(Long id);
}
And the service class is as follows:
#Service("ResolveJobReportService")
public class ResolveJobReportService {
#Autowired
private ResolveJobReportMapper resolveJobReportMapper= null;
public List<ResolveJobReport> getAllResolveJobReports() {
return resolveJobReportMapper.getAllResolveJobReports();
}
public List<ResolveJobReport> getAllResolveJobReports(RowBounds rowBounds) {
return resolveJobReportMapper.getAllResolveJobReports();
}
public List<ResolveJobReport> getAllResolveJobReportsById(Long id) {
return resolveJobReportMapper.getAllResolveJobReportsById(id);
}
public List<ResolveJobReport> getAllResolveJobReportsById(Long id, RowBounds rowBounds) {
return resolveJobReportMapper.getAllResolveJobReportsById(id);
}
public void saveResolveJobReport(ResolveJobReport resolveJobReport) {
resolveJobReportMapper.saveResolveJobReport(resolveJobReport);
}
public void updateResolveJobReportById(ResolveJobReport resolveJobReport) {
resolveJobReportMapper.updateResolveJobReportById(resolveJobReport);
}
public void deleteResolveJobReporttById(Long id) {
resolveJobReportMapper.deleteResolveJobReporttById(id);
}
}
Can anyone see what is wrong.

The problem happens because the namespace in mapper xml is com.qlsdistribution.fps.resolverender.data.mybatis.ResolveJobReportMapper but the package the mapper interface is com.qlsdistribution.fps.resolverender.data.mybatis.mapper.ResolveJobReportMapper.
To fix it make sure they match.

Put it in application.properties mybatis.mapper-locations=classpath*:**/mappers/*Mapper.xml

For those people using MyBatis without xml in spring boot project:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
Please check your spring boot application class, make sure your #MapperScan matches your dao package.
#MapperScan("com.jjs.videoservice.dao")
The path must be SAME as your dao package (contains your mapper interface), I ignored "dao" and caused the issue.
Hope it helps someone, thanks

I had the same error message when I changed my project from a JavaFX Project to a Maven Project.
I had to move all my xml mapper files to the resource folder. After that, worked just fine.

I hit this problem recenly, and checked everything that can be found in the internet. Cost me a whole day.
Finally I put the xml files in the same place with the interface java files, which solved the problem.
I think that is because for some reasons the xml files can not be found, and putting them there make them visiable.

I had the same issue
for me the fix was giving same filename for both the java (mapper interface class) and corresponding xml file

I had 2 mappers in the same package. It was the root cause of the problem. Once each mapper interface was moved to separate package, the problem was resolved.

in my case, I used the same name for mapper and java class but the mapping in mapper.xml was pointing to the wrong java class

I faced the same problem recently, I noticed, that I added the new method in the production xml mapper file by mistake and not in the actual xml mappers in resources folder. Once the actual xml mappers in resources folder was updated, it fixed the problem. So please make sure you update the right mapper files in your src folder that gets compiled.

Sometimes people do this mistake:
In resources folder the created folder like "org.my_app.mybatis", but the correct way is do separate folder for each part of package
-org
--my_app
---mybatis
It is hard to recognize when you do it in code editor.
Visually we have the same result
But actually a different structure
Green will work, red - won't.

Related

Spring Boot - maven-jaxb2-plugin not generaing all classes - requests and responses for WSDL

We have an example WSDL that has been provided by an API provider and we want to integrate with it.
I tried the provided example at https://spring.io/guides/gs/consuming-web-service/ and some other .wsdl files and it all looks good.
In my case with my wsdl - when running the command to generate the classes - only some of them are generated, but not all of them.
This is not the case in SoapUI - all is good there.
Any info why this is happening?
My pom.xml is the following
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.13.2</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<generatePackage>com.test.xxx.soapclient.generated</generatePackage>
<generateDirectory>${project.basedir}/src/main/java</generateDirectory>
<schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
<schemaIncludes>
<include>*.wsdl</include>
</schemaIncludes>
</configuration>
</plugin>
</plugins>
</build>
What i have come to see is that only the complex types are being created as classes - while the others are not.
In my example the input message is the one below and no classes are being generated for it.
How can i do that?
Also what is interesting here is - soapAction has empty string as parameter - and Java's API requires SoapAction
Java Code
public Object callWebService(String action, Object request){
return getWebServiceTemplate().marshalSendAndReceive(request,new SoapActionCallback(action));
}
Actual WSDL File
<operation name="login" parameterOrder="user password">
<input message="tns:CardManagementEP_login"> </input>
<output message="tns:CardManagementEP_loginResponse"> </output>
</operation>
<message name="CardManagementEP_loginResponse">
<part name="result" type="xsd:string"> </part>
</message>
<message name="CardManagementEP_login">
<part name="user" type="xsd:string"> </part>
<part name="password" type="xsd:string"> </part>
</message>
<operation name="login">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal" namespace="http://com.tch.cards.service"/>
</input>
<output>
<soap:body use="literal" namespace="http://com.tch.cards.service"/>
</output>
</operation>
I managed to resolve the issue with the help of DaShaun Carter from the show Spring Office Hours.
The issue was that the above mentioned WSDL file was really old, so the classes for requests/responses which are not complex were not generated.
What we did is modify the existing WSDL and create these things as complex types - so Jaxb will generate classes for them
example-wsdl.wsdl
<complexType name="login">
<sequence>
<element name="user" type="string"/>
<element name="password" type="string"/>
</sequence>
</complexType>
<complexType name="loginResponse">
<sequence>
<element name="result" type="string"/>
</sequence>
</complexType>
After that, the classes are getting generated, but they did not work for me, and i had to some manual changes in order to get them working
LoginResponse.java
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "loginResponse", namespace = "http://com.tch.cards.service")
#XmlAccessorType(XmlAccessType.FIELD)
public class LoginResponse {
#XmlElement(required = true)
protected String result;
public String getResult() {
return result;
}
public void setResult(String value) {
this.result = value;
}
}
Login
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "login", namespace = "http://com.tch.cards.service")
#XmlAccessorType(XmlAccessType.FIELD)
public class Login {
#XmlElement(required = true)
protected String user;
#XmlElement(required = true)
protected String password;
public String getUser() {
return user;
}
public void setUser(String value) {
this.user = value;
}
public String getPassword() {
return password;
}
public void setPassword(String value) {
this.password = value;
}
}
Also, in my case, the Soap Action did not matter, and i am passing empty strings.
The code where the actual calls were happening is as follows:
Login login = new Login();
login.setUser("user");
login.setPassword("password");
LoginResponse response = (LoginResponse) soapConnector.callWebService("", login);
System.out.println(response);
IMPORTANT NOTE: Change the namespace as per usecase - this is really important

How to declare a element for complex data type defined in a xsd file located in jar file

I have a below xsd file in a jar dependency file in a Spring boot project. The xsd does not declare the element declaration, which is required by spring boot validation. So I am trying to add another xsd in my project resource folder to declare element type.
XSD in Jar file: /wsdl/xsd/UserService-v1-0.xsd
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://usermanagement.com/userservice/xsd/2014/07"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:userservice="http://usermanagement.com/userservice/xsd/2014/07"
elementFormDefault="qualified">
<xsd:import namespace="http://usermanagement.com/userservice/common/xsd/2014/09" schemaLocation="userserviceCommon-v1-0.xsd"/>
<xsd:import namespace="http://usermanagement.com/userserviceabsolute/common/xsd/2014/09" schemaLocation="userserviceAbsoluteCommon-v1-0.xsd"/>
<xsd:complexType name="GetUsersRequest">
<xsd:attribute name="language" type="xsd:language" use="optional" default="en" />
</xsd:complexType>
</xsd:schema>
Please note that I tried to keep the complex type simple by removing some of the elements for this post. The location of file is /wsdl/xsd.
XSD to declare the element in the main Project resource: /wsdl/xsd/UserService-type-v1-0.xsd
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://usermanagement.com/userservice/wsdl/userserviceService-v1-0"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:userservice="http://usermanagement.com/userservice/xsd/2014/07"
elementFormDefault="qualified">
<import namespace="http://usermanagement.com/userservice/xsd/2014/07" schemaLocation="jar:file://{path to the jar}/!/wsdl/xsd/userserviceService-v1-0.xsd"/>
<element name="GetUsersRequest" type="userservice:GetUsersRequest"/>
</xsd:schema>
As per my understanding we need to refer to the schemaLocation of xsd file in jar using notation "jar:file://{path to the jar}/!/wsdl/xsd/userserviceService-v1-0.xsd".
However I am not sure how to declare the path to the jar. Also not sure if this is the only way to refer to the definitions in the xsd in the jar files. In the above approach when ever a new version of jar is released we need to update the xsd file.
Also including the Spring WS schema validation config:
#Configuration
public class MyWsValidatorConfig extends WsConfigurerAdapter {
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
validatingInterceptor.setValidateRequest(true);
validatingInterceptor.setValidateResponse(true);
validatingInterceptor.setXsdSchemaCollection(new XsdSchemaCollection() {
#Override
public XsdSchema[] getXsdSchemas() {
return null;
}
#Override
public XmlValidator createValidator() {
try {
return XmlValidatorFactory.createValidator(getSchemas(), "http://www.w3.org/2001/XMLSchema");
} catch (Exception e) {
log.error("Failed to create validator e={}", e);
}
return null;
}
public Resource[] getSchemas() {
List<Resource> schemaResources = new ArrayList<>();
schemaResources.add(new ClassPathResource("/wsdl/xsd/UserService-v1-0.xsd"));
schemaResources.add(new ClassPathResource("/wsdl/xsd/UserService-type-v1-0.xsd"));
return schemaResources.toArray(new Resource[schemaResources.size()]);
}
});
interceptors.add(validatingInterceptor);
}
}
This is the first time I am working with XSD and SOAP web services. Able to cross other hurdles but got stuck with this issue.
Please help.

Spring boot logbcak to file is not working on tomcat

I am running spring boot as War on tomcat with logback to console and file.
as long as i run as Java application it is fine i can see logs in console and file.
but i dont see logs printed to file when run on server.
I tried setting logger manager also, didnt work. was wondering to know if some one has faced similar issue.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
<property name="LOG_FILE_MAX_SIZE" value="10MB" />
<property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
<property name="LOG_FILE_MAX_HISTORY" value="20" />
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>
Verify that you have the following dependency :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
or even if you have spring-boot-starter-web dependency added, logging should work.
and have the following in yml or properties file :
logging.path=logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
and you can also have a logback.xml and use the spring default base.xml in that so that all default spring configurations apply for your logging as well :
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="DEBUG"/>
</configuration>
Here is my logback-spring.xml which i have
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
<property name="LOG_FILE_MAX_SIZE" value="10MB" />
<property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
<property name="LOG_FILE_MAX_HISTORY" value="20" />
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>
I could fix it by writing the logs to a different folder looks application doesn't have write access the path, however i need to make some changes to springboot main class for loading application props based profile, please find the class below. not sure if others had to the same.
anyway i am glad it is working finally:)
public class Application extends SpringBootServletInitializer{
public String PROFILE = null;
private static String CONFIG_LOCATION = null;
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Grab the active profile from the servlet conext
PROFILE = servletContext.getInitParameter("spring.profiles.active");
CONFIG_LOCATION = servletContext.getInitParameter("spring.config.path");
super.onStartup(servletContext);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//...and pass it to the boot application
application.application().setAdditionalProfiles(PROFILE);
return application.sources(Application.class).properties(getProperties());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//For Loading config from server
static Properties getProperties() {
Properties props = new Properties();
props.put("spring.config.location", CONFIG_LOCATION);
return props;
}
}
web.xml
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.config.path</param-name>
<param-value>classpath:app.config/</param-value>
</context-param>

Cannot find declaration to go to in maven?

When I ran the Test Class(CountryMapperTest.java), the error has been occurred. The following is error information.
org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in tk.mybatis.simple.mapper.CountryMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException:
Error parsing SQL Mapper Configuration.
Cause: java.io.IOException:
Could not find resource tk.mybatis.simple.mapper.CountryMapper.xml
Project Directory
By analysing the error messages, I think that the bug comes from the following statement in the mybatis-config.xml file.
<mappers>
<mapper resource="tk.mybatis.simple.mapper.CountryMapper.xml"/>
</mappers>
I have tried some solutions that work for others:
File | Invalidate Caches / Restart
Select the Directory | Make Directory as Resources Root, etc..
Add the relative code snippet in the pom.xml:
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
Relative code
CountryMapperTest.java
package tk.mybatis.simple.mapper;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import tk.mybatis.simple.model.Country;
public class CountryMapperTest {
private static SqlSessionFactory sqlSessionFactory;
#BeforeClass
public static void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
System.out.println("Test1");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
System.out.println("Test2");
reader.close();
} catch (IOException ignore) {
ignore.printStackTrace();
}
}
#Test
public void testSelectAll() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
List<Country> countryList = sqlSession.selectList("selectAll");
printCountryList(countryList);
} finally {
sqlSession.close();
}
}
private void printCountryList(List<Country> countryList) {
for (Country country : countryList) {
System.out.printf("%-4d%4s%4s\n", country.getId(), country.getCountryname(), country.getCountrycode());
}
}
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<package name="tk.mybatis.simple.model"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="12345"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="tk.mybatis.simple.mapper.CountryMapper.xml"/>
</mappers>
</configuration>
CountryMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="tk.mybatis.simple.mapper.CountryMapper">
<select id="selectAll" resultType="Country">
select id,countryname,countrycode from country
</select>
</mapper>
I expect to query the database and show data in console.
More Details
IDE: IntelliJ IDEA, 2019.1
OS: macOS Mojave, 10.14.3
The mapper resource path should be separated by slash.
<mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/>
http://www.mybatis.org/mybatis-3/configuration.html#mappers
In addition to the ave's solution, we also need to check the package naming and path.
Because the optical package naming is the same in IntelliJ IDEA, the both are the tk.mybatis.simple.mapper.
Actually, correct path is tk/mybatis/simple/mapper, error path is tk.mybatis.simple.mapper.
Please follow the below method to check it:
File | Project Structure...
click Modules | Your Project Name | Sources

Using JAX-WS + xjc + bindings to add serializable and default UID to my WSDL stubs

I am trying to use the globalBindings element to add serializable + a default UID to my WSDL stub classes so I can get rid of a bunch of annoying warnings from Eclipse.
I am trying to follow the suggestions in this answer, but no luck. Still get all the warnings in Eclipse.
Am I missing something in the pom file perhaps?
I am OK with upgrading to a newer version of the jaxws plugin, or even moving to a different plugin, if required.
Here's my bindings file:
<bindings xmlns="http://java.sun.com/xml/ns/jaxb" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc">
<globalBindings>
<xjc:serializable uid="1" />
</globalBindings>
<bindings
schemaLocation="../resources/com/satorisoftware/ws/infuseiac/intladdresscorrection/intladdresscorrection.wsdl#types?schema3"
version="1.0">
<schemaBindings>
<package name="com.satorisoftware.ws.infuseiac-intladdresscorrection" />
</schemaBindings>
<!-- Tell JAXB to generate Java class specifically named CorrectRequestElement
for this element, to avoid the name clash that automatic naming causes. -->
<bindings node="//xsd:element[#name='CorrectRequest']">
<class name="CorrectRequestElement" />
</bindings>
</bindings>
</bindings>
And here's the relevant part of my pom.xml file:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<id>import-iac-wsdl</id>
<phase>generate-sources</phase>
<goals>
<goal>wsimport</goal>
</goals>
<inherited>false</inherited>
<configuration>
<packageName>com.satorisoftware.ws.infuseiac.intladdresscorrection</packageName>
<wsdlLocation>com/satorisoftware/ws/infuseiac/intladdresscorrection/intladdresscorrection.wsdl</wsdlLocation>
<staleFile>${project.build.directory}/jaxws/stale/wsdl.intladdresscorrection.done</staleFile>
<sourceDestDir>${project.build.directory}/generated/jaxws-infuseiac-intladdresscorrection</sourceDestDir>
<wsdlDirectory>src/main/resources/com/satorisoftware/ws/infuseiac/intladdresscorrection</wsdlDirectory>
<bindingFiles>
<!-- See http://www.jroller.com/gmazza/entry/enhancing_jaxb_artifacts#BindingFile
for an end-to-end-example of doing bindings files for WSDL files. -->
<bindingFile>${basedir}/src/main/bindings/bindings-intladdresscorrection.xjb</bindingFile>
</bindingFiles>
<!-- <wsdlUrls> <value>https://infuseiac.satorisoftware.com/wsdl/IntlAddressCorrection.2012.12.wsdl</value>
</wsdlUrls> -->
<!-- Generate JAX-WS 2.0 compatible stubs -->
<target>2.0</target>
</configuration>
</execution>
</executions>
</plugin>
Here's an example of a generated class without the UID
package com.satorisoftware.ws.infuseiac.intladdresscorrection;
import javax.xml.ws.WebFault;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.7-b01-
* Generated source version: 2.0
*
*/
#WebFault(name = "DuplicateFieldFaultContract", targetNamespace = "infuse.satorisoftware.com/2012/08")
public class IntlAddressCorrectionCorrectDuplicateFieldFaultContractOfInfuseSingleFieldFaultFaultMessage
extends Exception
{
/**
* Java type that goes as soapenv:Fault detail element.
*
*/
private DuplicateFieldFaultContract faultInfo;
/**
*
* #param message
* #param faultInfo
*/
public IntlAddressCorrectionCorrectDuplicateFieldFaultContractOfInfuseSingleFieldFaultFaultMessage(String message, DuplicateFieldFaultContract faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
/**
*
* #param message
* #param faultInfo
* #param cause
*/
public IntlAddressCorrectionCorrectDuplicateFieldFaultContractOfInfuseSingleFieldFaultFaultMessage(String message, DuplicateFieldFaultContract faultInfo, Throwable cause) {
super(message, cause);
this.faultInfo = faultInfo;
}
/**
*
* #return
* returns fault bean: com.satorisoftware.ws.infuseiac.intladdresscorrection.DuplicateFieldFaultContract
*/
public DuplicateFieldFaultContract getFaultInfo() {
return faultInfo;
}
}
Here's a little bit of the WSDL as requested:
<xsd:complexType name="DuplicateFieldFaultContract">
<xsd:annotation>
<xsd:appinfo>
<GenericType xmlns="http://schemas.microsoft.com/2003/10/Serialization/"
Name="DuplicateFieldFaultContract" Namespace="infuse.satorisoftware.com/2012/08">
<GenericParameter Name="InfuseField"
Namespace="http://schemas.datacontract.org/2004/07/Satori.Infuse.Single" />
</GenericType>
</xsd:appinfo>
</xsd:annotation>
<xsd:complexContent mixed="false">
<xsd:extension base="tns:InfuseFaultContract">
<xsd:sequence>
<xsd:element
xmlns:q4="http://schemas.datacontract.org/2004/07/Satori.Infuse.Single"
name="DuplicateFields" nillable="true" type="q4:ArrayOfInfuseField" />
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
<xsd:element name="DuplicateFieldFaultContract" nillable="true"
type="tns:DuplicateFieldFaultContract" />
Anders
This is what i understood from the post for WSimport
By default JAXB generated code isn't serializable
We need to add a mechanism to generate a UID which for POjos
It will not create serialVersionUID for Exception classes
wsdl2java, by default the generated exception class will have a serialVersionUID
please try wsdl2java , hope this will solve your issue
Andres
are you not seeing this
private static final long serialVersionUID="1L" ?
Every class generated will be serializable and have the specified uid: a limitation of this process is that each of your generated class will have the same uid.

Resources