Facing exception while running a DROPWIZARD application
ERROR [2016-12-30 04:36:34,735] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 6813de3aa499e307 ! org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): db.UserMapper.
@Path("/user/{username}")
public class ExampleResource {
private final SqlSessionFactory sessionFactory;
public ExampleResource(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@GET
public User getUser(@PathParam("username") String username) {
try (SqlSession session = sessionFactory.openSession())
{
UserMapper users = session.getMapper(UserMapper.class);
//session.getConfiguration().addMapper(UserMapper.class);
//UserMapper users = session.getMapper(UserMapper.class);
return users.findByUsername(username);
}
}
}
UserMapper.xml
<mapper namespace="db.UserMapper" class="db.UserMapper">
<select id="findByUsername" resultType="User">
<![CDATA[
select username,email
from user
where username = #{username}
]]>
</select>
<resultMap id="User" type="core.User">
<id column="username" property="username" />
<result column="email" property="email" />
</resultMap>
<insert id="addUser">
<![CDATA[
insert into user (username, email)
values (#{User.username}, #{User.email})
]]>
</insert>
user mapper.java
public interface UserMapper {
User findByUsername(@Param("username") String username);
void addUser(@Param("user") User user);
}
ConfigurationClass:
@Valid
@NotNull
private DataSourceFactory datasourceFactory = new DataSourceFactory();
@JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return this.datasourceFactory;
}
public void setDatabase(DataSourceFactory database) {
this.datasourceFactory = database;
}
When we are using mybatis with dropwizard in main class we initialize mybatisbundle, at that time provide the package name where your mapper class is located. Hightlighted in code below.
private final MybatisBundle<TestDropWizardConfiguration> mybatisBundle = new MybatisBundle<TestDropWizardConfiguration>("**com.example.helloworld**") {
@Override
public DataSourceFactory getDataSourceFactory(TestDropWizardConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};