黄舟2017-04-18 10:39:04
There are two common methods:
Define a Bean specifically for passing parameters and provide Setter/Getter methods. This method is obviously too cumbersome.
But it can be simplified, just put multiple parameters map
,将map
and pass them in.
You can mark parameter names in mapper接口
定义的方法入参里,使用注解org.apache.ibatis.annotations.Param
. For example:
public interface UserMapper{
User login(@Param("name")String name,@Param("password")String password);
}
After that, just use the corresponding name mapping in xml:
<select id="login" resultMap="UserResultMap">
select col1,col2,col3
from tal_name
where user_name=#{name} and pwd=#{password}
</select>
If you want to use method 2, your current method will not work.
Because you are calling using sqlSession.selectOne(queryId)
or sqlSession.selectOne(queryId,paramObj)
. sqlSession.selectOne(queryId)
或sqlSession.selectOne(queryId,paramObj)
的方来调用的。
要使用方法二,你得先用sqlSession.getMapper(UserMapper.class)
拿到定义的接口(DAO
),拿到接口后,传递参数就相对自由了,因为接口里的方法定义就是常规的java方法定义。在定义的接口方法里就可以使用@Param
To use method 2, you must first use sqlSession.getMapper(UserMapper.class)
to get the defined interface (DAO
). After getting the interface, pass the parameters accordingly. It's free, because the method definitions in the interface are regular java method definitions. You can use the @Param
annotation to mark parameters in the defined interface method. A rough example is as follows:
package cn.xxx.dao;
public interface UserMapper{
User login(@Param("name")String name,@Param("password")String password);
}
<?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="cn.xxx.dao.UserMapper">
<select id="login" resultMap="UserResultMap">
select col1,col2,col3
from tal_name
where user_name=#{name} and pwd=#{password}
</select>
</mapper>
It should be noted here:
The full class name of the custom DAO interface
cn.xxx.dao.UserMapper
should be the same as <mapper namespace="cn.xxx.dao.UserMapper" Corresponds to the
. namespace
attribute in >DAO接口
的全类名cn.xxx.dao.UserMapper
应该和<mapper namespace="cn.xxx.dao.UserMapper">
中的namespace
属性相对应。
同时,namespace
的值(cn.xxx.dao.UserMapper)和select
的id
属性值(login)连起来其实就是你使用的sqlSession.selectOne(queryId)
中用来标记查询的queryId
At the same time, the value of namespace
(cn.xxx.dao.UserMapper) and the value of id
attribute (login) of select
are actually you. The sqlSession.selectOne(queryId)
used to mark the query is queryId
.
If it is maven
工程,你应该将xxxMapper.xml
置于资源路径(src/main/resources
)下而不是源代码路径(src/main/java
),否则在运行时源代码路径下的xml文件
it cannot be found.
Another suggestion is: visually check the example of integration using Spring
来管理Bean
的,鉴于此,还有另一种管理SqlSessionFactory
的方式,可以不用直接在DAO
里显示地注入SqlSessionFactory
。此处是我以前从别人那里fock
过来的一个SSM
: https://github.com/hylexus/be...