官方网站 http://www.mybatis.org/mybatis-3/zh/configuration.html#typeHandlers
对于mybatis中字段名和model中名不一致的问题:
1.select user_name as username from users;
2.<resultMap id=“userResultMap” type="user">
<id column="user_name" property="username"/>
</resultMap>
3.mybatis 对于字段user_name 到属性 username ,mybatis能自动识别装配 。
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->
@Param注解
int updateUserById (@Param("id") Integer id,@Param("name") String name);
<update id="updateUserById"> <!--注解之后不需要指定参数-->
update
users
set
name = #{name}
where id = #{id}
</update>
int updateUser(Map<String,Object> params);
<update id="updateUser" parameterTYpe="map">
update
users
set
name = #{name}
where id = #{id}
</update>
4.<sql ></sql>
<sql id="selectBaseField">
id as id,
user_name as userName,
password as password,
age as age,
create_time as createTime
</sql>
<select id = "selUser" resultType="User">
select
<include refid="selectBaseField"/>
from
users
</select>
5.动态sql
<select id="selectUser" resultType="user">
select
<include refid="selectFields"/>
from
user
<where>
<if test="user_name != null and user_name !='' ">
and user_name = #{username} <!--会自动去掉第一个符合条件的 and-->
</if>
<if test="age != null and age !='' ">
and age = #{age}
</if>
</where>
</select>
<update id="updateUser" parameterTYpe="user">
update
users
<set>
<if test="age != null and age > 18 ">
and age = #{age} , <!--会自动去掉最后一个 ,-->
</if>
</set>
</update>
<insert id="addUser" parameterType="java.util.List">
insert into users
(
user_name,
age,
password
)values
<foreach collection="list" item="item" separator=",">
<!-- <foreach collection="list" item="item" separator="," close=")" open="(">-->
(
#{item.username},
#{item.age},
#{item.password},
)
</foreach>
</insert>
6.关于逻辑分页和物理分页
逻辑分页是一次查询出所有结果,然后对resultSet 结果进行处理,设计算法去分页
物理分页是通过 查表的时候 limit 行数
7.<mvc:mapping path="/**"/> //这里注意,path需要配置成path="/**" , /**的意思是所有文件夹及里面的子文件夹 /*是所有文件夹,不含子文件夹 /是web项目的根目录
8.MyBatis 插入空值时,需要指定JdbcType.如#{name,jdbcType=VARCHAR}
在执行SQL时MyBatis会自动通过对象中的属性给SQL中参数赋值,它会自动将Java类型转换成数据库的类型。而一旦传入的是null它就无法准确判断这个类型应该是什么,就有可能将类型转换错误,从而报错。
<if test="condition.createTimeTo != null">
and create_time < #{condition.createTimeTo,jdbcType=TIME}
</if>
MyBatis 通过包含的jdbcType类型
BIT FLOAT CHAR TIMESTAMP OTHER UNDEFINED
TINYINT REAL VARCHAR BINARY BLOB NVARCHAR
SMALLINT DOUBLE LONGVARCHAR VARBINARY CLOB NCHAR
INTEGER NUMERIC DATE LONGVARBINARY BOOLEAN NCLOB
BIGINT DECIMAL TIME NULL CURSOR