How to build project by Spring Boot + Mybatis + Mybatis Generator? - spring-boot

I follow mybatis official website to build my project step by step, but it always can not work well, so I hope you could give me a fully guide from beginning to the end, many thanks.

Step 1. Build a new spring boot project named booking.
This step is basically, I will skip it.
Step 2. Add mybatis-generator to project.
This could help us to generate entity and mapper class mybatis needed automatically, it's very useful for us to save our time.
Add plugin config in pom.xml
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
</plugin>
Create generatorConfig.xml at base resources path.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/booking?useSSL=false"
userId="root"
password="123456">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<javaModelGenerator targetPackage="com.clycle.booking.entity" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.clycle.booking.mapper" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.clycle.booking.mapper" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="%">
</table>
</context>
</generatorConfiguration>
Create maven Run/Debug Configuration to run this plugin.
It will generate all entity, mapper class and mapper xml automatically. -Dmybatis.generator.overwrite=true, means it will overwrite existing entity or mapper class when run mybatis generator with maven.
Step 3. Add mybatis to this project.
Add mybatis dependency in pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
Create mybatis-config.xml at base resources path.
<?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="com.clycle.booking.entity" />
</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/booking" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.clycle.booking.mapper" />
<!--<mapper resource="com/clycle/booking/mapper/ShopMapper.xml" />-->
</mappers>
</configuration>
Add #MapperScan for application main class.
#SpringBootApplication
#MapperScan({"com.clycle.booking.mapper"})
public class BookingApplication {
public static void main(String[] args) {
SpringApplication.run(BookingApplication.class, args);
}
}
Autowired mapper interface to operate your database.
#Autowired
private ShopMapper shopMapper;
#PostMapping(RoutePath.SHOP_LIST)
public List<Shop> GetList() {
try {
return shopMapper.selectAll();
} catch (Exception ex) {
return null;
}
}

You can download this project: https://github.com/yyqian/spring-boot-mybatis-generator .
Everything just work fine on my computer.

Related

How can i configure my spring aop xml with aop.xml an load time weaving?

I have one "Hello word" application on spring AOP and configured by XML, it looks like this:
public class CustomerBoImpl {
public CustomerBoImpl() {
super();
}
protected void addCustomer(){
System.out.println("addCustomer() is running ");
}
}
public class App {
public static void main(String[] args) throws Exception {
ApplicationContext appContext =
new ClassPathXmlApplicationContext("Spring-Customer.xml");
CustomerBoImpl customer =
(CustomerBoImpl) appContext.getBean("customerBo");
customer.addCustomer();
}
}
My spring configuration looks like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy />
<!-- this switches on the load-time weaving -->
<context:load-time-weaver aspectj-weaving="on" />
<bean id="customerBo" class="com.mkyong.saad.CustomerBoImpl"
scope="singleton" />
<!-- Aspect -->
<bean id="logAspect" class="com.mkyong.saad.LoggingAspect" />
<aop:config>
<aop:aspect id="aspectLoggging" ref="logAspect">
<!-- #Before -->
<aop:pointcut id="pointCutBefore"
expression="execution(* com.mkyong.saad.CustomerBoImpl.addCustomer(..))" />
<aop:before method="logBefore" pointcut-ref="pointCutBefore" />
<!-- #After -->
<aop:pointcut id="pointCutAfter"
expression="execution(* com.mkyong.saad.CustomerBoImpl.addCustomer(..))" />
<aop:after method="logAfter" pointcut-ref="pointCutAfter" />
</aop:aspect>
</aop:config>
that doesn't work because of protected method, so I tried to use load time weaving with aop.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
<weaver>
<!-- only weave classes in our application-specific packages -->
<include within="com.mkyong.saad.*"/>
</weaver>
<aspects>
<!-- weave in just this aspect -->
<aspect name="com.mkyong.saad.LoggingAspect"/>
</aspects>
</aspectj>
Source code for the aspect:
public class LoggingAspect {
public void logBefore(JoinPoint joinPoint) {
System.out.println("logBefore() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
}
public void logAfter(JoinPoint joinPoint) {
System.out.println("logAfter() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
}
}
but it doesn't work, only if I change to annotation config. SOS PLZ
removing the following code in your aop.xml, then run your jvm with args like this: -javaagent:"yourpath/spring-instrument-***.jar"
<weaver>
<!-- only weave classes in our application-specific packages -->
<include within="com.mkyong.saad.*"/>
</weaver>

Enunciate framework - Not working with Spring Restful project

I have integrated enunciate framework to generate the API document for the Spring RESTful project. I have followed the steps from https://github.com/stoicflame/enunciate/wiki/Executables and deployed the war created from the enunciate configuration in the tomcat server(http://localhost:8080/sample_enunciate) but its displaying the empty document. Here I have provided the configuration details used in the sample project.
NOTE: But the similar configuration is working with Jersey restful project. I really stuck here. Please let me know, is this bug with the enunciate framework integration with Spring project. Thanks in advance.
Project configuration:
java -1.7.0
tomcat -6.0 &7.0
ant -1.9.4
spring -4.0.5
enunciate -1.30
jars:
enunciate-core-1.30-RC1.jar
enunciate-core-annotations-1.30-RC1.j
enunciate-core-rt-1.30-RC1.jar
enunciate-java-client-1.30-RC1.jar
enunciate-docs-1.30-RC1.jar
enunciate-rt-1.30-RC1.jar
enunciate-spring-app-rt-1.30-RC1.jar
enunciate-spring-jaxws-rt-1.30-RC1.ja
spring-aop-4.0.5.RELEASE.jar
spring-beans-4.0.5.RELEASE.jar
spring-context-4.0.5.RELEASE.jar
spring-context-support-2.5.4.jar
spring-core-4.0.5.RELEASE.jar
spring-expression-4.0.5.RELEASE.jar
spring-jdbc-4.0.5.RELEASE.jar
spring-test-4.0.5.RELEASE.jar
spring-tx-4.0.5.RELEASE.jar
spring-web-4.0.5.RELEASE.jar
spring-webmvc-4.0.5.RELEASE.jar
This is my enunciate.xml.
enunciate.xml
<?xml version="1.0"?>
<api-classes>
<include pattern="com.sample.controller.*" />
</api-classes>
<modules>
<!-- Docs -->
<docs title="example" copyright="Example.com"/>
<webapp mergeWebXML="WebContent/WEB-INF/web.xml" />
<spring-app disabled="false" springVersion="4.0.5">
<springImport file="resources/dev/applicationContext.xml" />
<springImport file="WebContent/WEB-INF/rest-servlet.xml" />
</spring-app>
<c disabled="true" />
<csharp disabled="true" />
<java-client disabled="false" />
<cxf disabled="false" />
<gwt disabled="false" />
<jaxws-client disabled="true" />
<jaxws-ri disabled="true" />
<jaxws-support disabled="true" />
<jersey disabled="true" />
<xml disabled="false" />
<obj-c disabled="true" />
<rest disabled="false" />
</modules>
properties file for build.xml
enunciate_build.properties
JAVA_HOME=C:/Java/jdk1.7.0/
tomcat.home=D:/xampp/tomcat
This is my build.xml
build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project default = "enunciate">
<property file ="enunciate_build.properties"/>
<property name="lib.dir" value="../libs" />
<property name="src.dir" value="src"/>
<target name = "enunciate">
<path id= "enunciate.classpath">
<fileset dir = "${lib.dir}">
<include name="*.jar"/>
</fileset>
<fileset dir ="${lib.dir}/modules/spring">
<include name="*.jar"/>
</fileset>
<fileset dir = "${JAVA_HOME}">
<include name = "lib/tools.jar"/>
</fileset>
</path>
<taskdef name="enunciate" classname = "org.codehaus.enunciate.main.EnunciateTask">
<classpath refid = "enunciate.classpath"/>
</taskdef>
<enunciate javacSourceVersion="1.7" javacTargetVersion="1.7" basedir = "${src.dir}" configFile="enunciate.xml">
<include name = "**/*.java"/>
<classpath refid= "enunciate.classpath"/>
<export artifactId="war.file" destination="${tomcat.home}/webapps/sample_enunciate.war"/>
</enunciate>
</target>
</project>
Enunciate only recognizes JAX-RS annotations right now. For further information follow this link.https://github.com/stoicflame/enunciate/issues/60

Duplicate bean conflicts during integration tests (multiple, merged contexts?, re: surefire vs failsafe?)

I am experiencing some dependency injection errors during the integration-test phase of my application. I think it's happening because spring is firing up a context during unit testing, then caching all my mock bean instances used for unit tests, which then conflict with the beans fired up during the integration-test phase, causing DI in my classes to fail because Spring is finding multiple instances of the same beans (mock vs real instances).
Note: This issue is only present during the integration-test phase of the app. The app otherwise starts, runs, and unit tests normally (it's a webapp and I run it with maven 3 using the tomcat:run-war goal).
This is the basic composition of my integration tests. I wrote a bogus one yesterday just to try and isolate the issue (no DI involved in this test):
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="file:src/main/webapp/WEB-INF/spring/root-context.xml")
#DirtiesContext
public class ITNonsenseTest {
#Test
public void doNothing() {
System.out.println("hello, world");
Assert.assertTrue(true);
}
}
My integration tests all begin with the prefix "IT" and my unit tests all begin with the prefix "UT"
I am using apache surefire for unit tests, and apache failsafe for integration tests:
from my pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven.nfire.plugin.version}</version>
<configuration>
<excludes>
<exclude>**/IT*.java</exclude>
</excludes>
<includes>
<include>**/UT*.java</include>
</includes>
<skipTests>
${skipUnitTests}
</skipTests>
</configuration>
<executions>
<execution>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>${maven.nfire.plugin.version}</version>
</plugin>
<!-- For Integration Tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven.nfire.plugin.version}</version>
<configuration>
<includes>
<include>**/IT*.java</include>
</includes>
<excludes>
<exclude>**/UT*.java</exclude>
</excludes>
<skipTests>
${skipIntegrationTests}
</skipTests>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
Even when running my simple ITNonsenseTest above, the Spring context fails to initialize properly. Since many of the beans I'm trying to create already exist in the context (as mock bean instances from my Unit test phase), Spring is complaining about duplicates being found.
Is there a way to tear down the context after the unit test phase, and build a new context for the integration-test phase? Or am I just doing something completely wrong?
This is my root-context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:property-placeholder location="file://${conf.dir}/*.properties" />
<context:component-scan base-package="com.myapp.models, com.myapp.dao, com.myapp.service" />
<beans:import resource="simplesm-context.xml" />
<beans:import resource="datasources.xml" />
<beans:import resource="rabbit-context.xml" />
<util:properties id="swaggerProps" location="classpath:swagger.properties" />
<util:properties id="encryptionProps" location="classpath:sharedEncryption.properties" />
<aop:aspectj-autoproxy />
<beans:bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
<beans:property name="caches">
<beans:set>
<beans:bean class="com.google.code.ssm.spring.SSMCache">
<beans:constructor-arg name="cache" index="0" ref="defaultCache" />
<beans:constructor-arg name="expiration" index="1" value="86400" />
<beans:constructor-arg name="allowClear" index="2" value="false" />
</beans:bean>
</beans:set>
</beans:property>
</beans:bean>
<beans:bean name="defaultCache" class="com.google.code.ssm.CacheFactory">
<!-- <beans:property name="cacheName" value="defaultCache" /> -->
<beans:property name="cacheClientFactory">
<beans:bean name="cacheClientFactory" class="com.google.code.ssm.providers.spymemcached.MemcacheClientFactoryImpl" />
</beans:property>
<beans:property name="addressProvider">
<beans:bean class="com.google.code.ssm.config.DefaultAddressProvider">
<beans:property name="address" value="${ureg.memcached.url}:${ureg.memcached.port}" />
</beans:bean>
</beans:property>
<beans:property name="configuration">
<beans:bean class="com.google.code.ssm.providers.CacheConfiguration">
<beans:property name="consistentHashing" value="true" />
</beans:bean>
</beans:property>
</beans:bean>
</beans:beans>
This is my project's dependencies' versioning info:
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.0.6.RELEASE</org.springframework-version>
<org.springframework.amqp.version>1.3.5.RELEASE</org.springframework.amqp.version>
<org.springframework.data.version>1.6.0.RELEASE</org.springframework.data.version>
<google.simple.spring.memcached.version>3.2.1</google.simple.spring.memcached.version>
<maven.nfire.plugin.version>2.17</maven.nfire.plugin.version>
</properties>
Lastly, I tried adding a #DirtiesContext to all of my Unit tests that use SpringJunit4ClassRunner, but I'm still seeing this error. All of my unit tests are structured in the following manner:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#DirtiesContext
public class UTAdditionalDataPointsServiceTest {
#Configuration
static class AdditionalDataPointsServiceUnitTestContextConfiguration {
#Bean
#Qualifier("props")
public Properties getProperties() {
return Mockito.mock(Properties.class);
}
#Bean
#Qualifier("npJdbcTemplate")
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return Mockito.mock(NamedParameterJdbcTemplate.class);
}
#Bean
#Qualifier("uJdbcTemplate")
public JdbcTemplate getJdbcTemplate() {
return Mockito.mock(JdbcTemplate.class);
}
#Bean
public AdditionalDataPointsDao getAdditionalDataPointsDao() {
return Mockito.mock(AdditionalDataPointsDaoImpl.class);
}
#Bean
public AdditionalDataPointService getAdditionalDataPointService() {
return Mockito.mock(AdditionalDataPointServiceImpl.class);
}
}
#Inject
AdditionalDataPointService adpService;
#Test
public void testGetAdditionalDataPoints() throws Exception {
List<AdditionalDataPoint> adpList = adpService.getAdditionalDataPoints(1);
org.junit.Assert.assertNotNull(adpList);
}
I'm fairly confident the issue is the mock instances cached in the context during the unit testing phase, because if i comment out the definition for a bean when theyre instantiated in my root-context.xml file, the errors for those duplicates go away.
The stack traces are always the same, along the lines of:
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [java.util.Properties] is defined: expected single matching bean but found 2: realInstanceBeanName,mockInstanceBeanNameGetter
Configuring classesDirectory do the job for me. See Maven-failsafe-plugin fails to execute integration tests
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<classesDirectory>${project.build.outputDirectory}</classesDirectory>
</configuration>
</plugin>

After integrating Infinispan 5.2.1 second level cache occurred org.springframework.beans.factory.BeanDefinitionStoreException

I am using Infinispan L2 cache with Tomcat 6, Hibernate 4 Spring 3.5 and Junit 4.10. After integrating Infinispan cache I have encountered an exception when try to run application
Could not resolve placeholder 'hibernate.connection.password' in string value "${hibernate.connection.password}": Could not resolve placeholder 'hibernate.connection.password' in string value "${hibernate.connection.password}"
All the hibernate.properties file and spring files are in relevant places where they were in previously.
My Infinspan configuration is
<globalJmxStatistics enabled="true" jmxDomain="org.infinispan" allowDuplicateDomains="true"/>
<transport
transportClass="org.infinispan.remoting.transport.jgroups.JGroupsTransport"
clusterName="infinispan-hibernate-cluster"
distributedSyncTimeout="50000"
strictPeerToPeer="false">
<properties>
<property name="configurationFile" value="jgroups.xml"/>
</properties>
</transport>
</global>
<default>
</default>
<namedCache name="my-cache-entity">
<clustering mode="replication">
<stateRetrieval fetchInMemoryState="false" timeout="60000"/>
<sync replTimeout="20000"/>
</clustering>
<locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
lockAcquisitionTimeout="15000" useLockStriping="false"/>
<eviction maxEntries="10000" strategy="LRU"/>
<expiration maxIdle="100000" wakeUpInterval="5000"/>
<lazyDeserialization enabled="true"/>
<!--<transaction useSynchronization="true"
transactionMode="TRANSACTIONAL" autoCommit="false"
lockingMode="OPTIMISTIC"/>-->
<loaders passivation="false" shared="false" preload="false">
<loader class="org.infinispan.loaders.cluster.ClusterCacheLoader"
fetchPersistentState="false"
ignoreModifications="false" purgeOnStartup="false">
<properties>
<property name="remoteCallTimeout" value="20000"/>
</properties>
</loader>
</loaders>
</namedCache>
This is Spring configuration for the placeholders
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:tomcat-jdbc-pool.properties</value>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>

How to start myBatis implemention with spring?

I want to work with myBatis. I have read MyBatis-3-user-guide. Now i am trying to implement it. Recently i have learned spring. So it is difficult for me to implement it. So i need some helpful resource by which i can implement it step by step.
Add the MyBatis-Spring jar in your class path at first
Start with your spring context file.In your context file add following lines
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="yourDriverClassName"
p:url="yourUrl"
p:username="yourUsername"
p:password="yourPassword" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation" value="/WEB-INF/mybatis-config.xml" />
</beans:bean>
<beans:bean id="userDao" class="com.yourcomp.dao.Userdao">
<beans:property name="sqlSessionFactory" ref="sqlSessionFactory" />
</beans:bean>
your mybatis-config.xml should be something like this:
<?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>
</settings>
<typeAliases>
<typeAlias alias="User" type ="com.yourcomp.domain.User" />
</typeAliases>
<mappers>
<mapper resource="com/yourcomp/domain/UserMapper.xml"/>
<mapper resource="com/yourcomp/domain/AnotherDomainObjectMapper.xml"/>
</mappers>
</configuration>
and your userMapper.xml in src/com/yourcomp/domain/ might be something like this
<?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="org.pbl.rms.RMSUserDao">-->
<mapper namespace="com.yourcomp.domain.User">
<resultMap id="userMap" type="User">
<id property="userId" column="USER_ID" javaType="int" jdbcType="NUMERIC"/>
<result property="userName" column="USER_NAME" javaType="String" jdbcType="VARCHAR"/>
<result property="userFullName" column="USER_FULL_NAME" javaType="String" jdbcType="VARCHAR"/>
<result property="password" column="PASSWORD" javaType="String" jdbcType="VARCHAR"/>
<result property="passwordExpiryDate" column="PASWRD_EXPIRY_DATE" javaType="java.util.Date" jdbcType="DATE"/>
<result property="status" column="STATUS" javaType="_integer" jdbcType="DECIMAL"/>
</resultMap>
<select id="getUserById" parameterType="map" resultMap="userMap">
select * from user where USER_ID=#{userId}
</select>
</mapper>
now in your DAO layer you might have class like follows:
public class UserDAO{
private SqlSessionFactory sqlSessionFactory;
public UserDAO() {
}
public UserDAO(SqlSessionFactory sqlSessionFactory ) {
this.sqlSessionFactory = sqlSessionFactory;
}
public String getUserById(Integer userId) {
SqlSession session = sqlSessionFactory.openSession();
String name=null;
try {
name = (String)session.selectOne("com.yourcomp.domain.User.getUserById",userId);
}catch(Exception e){
}finally {
session.close();
}
return name;
}
}
You need MyBatis-Spring for this . See the reference here and here These provide you the step by step configs . If you need any specific details , you need to re frame your query .
Also check the spring reference for IBatis support.

Resources