Mybatis入门学习笔记

1.定义别名

在sqlMapConfig.xml中,编写如下代码:

1     <!-- 定义别名 -->
2     <typeAliases>
3         <!-- 
4             type: 需要映射的类型
5             alias: 别名
6          -->
7         <typeAlias type="cn.sm1234.domain.Customer" alias="customer"/>
8     </typeAliases>

在Customer.xml中使用,

1     <!-- 添加 -->
2     <insert id="insertCustomer" parameterType="customer">
3         INSERT INTO t_customer(NAME,gender,telephone) VALUES(#{name},#{gender},#{telephone})
4     </insert>

说明:别名不区分大小写

程序结构图如下:

Mybatis入门学习笔记

代码说明:

 1     <!-- 修改 -->    
 2     <!-- parameterType传入对象,包含需要使用的值 -->
 3     <update id="updateCustomer" parameterType="customer">
 4         UPDATE t_customer SET NAME = #{name} WHERE id = #{id}
 5     </update>
 6     
 7     <!-- 查询所有数据 -->
 8     <!-- 输出映射 resultType -->
 9     <select id="queryAllCustomer" resultType="customer">
10         SELECT * FROM t_customer
11     </select>
12     
13     <!-- 根据id查询 -->
14     <select id="queryCustomerById" parameterType="_int" resultType="customer">
15         SELECT * FROM t_customer WHERE id=#{value}
16     </select>
17     
18     <!-- 根据name模糊查询 -->
19     <select id="queryCustomerByName" parameterType="string" resultType="customer">
20         <!-- 方法一 -->
21         SELECT * FROM t_customer WHERE NAME LIKE #{value}
22         <!-- 方法二 -->
23         <!-- SELECT * FROM t_customer WHERE NAME LIKE '%${value}%' -->
24     </select>
25     
26     <!-- 删除 -->
27     <delete id="deleteCustomer" parameterType="int">
28         DELETE FROM t_customer WHERE id=#{value}
29     </delete>