一、根据how2j案例进行基础增删改查的练习
入门
1、进行数据库的创建和数据导入
2、在mybatis的项目上导入两个jar包
3、准备实体类Category,用于映射表category_
4、配置文件mybatis-config.xml,其作用主要是提供连接数据库用的驱动,数据库名称,编码方式,账号密码。
语句<package name="com.how2java.pojo"/>配置了别名,自动扫描com.how2java.pojo下的类型,使得在后续配置文件Category.xml中使用resultType的时候,可以直接使用Category简化操作,而不必写全com.how2java.pojo.Category
5、配置文件Category.xml

select * from category_,这条sql语句用id: listCategory 进行标示以供后续代码调用。resultType="Category" 表示返回的数据和Category关联起来,这里本应该使用的是 com.how2java.pojo.Category, 但是因为上一步配置了别名,所以直接使用Category就行了。
6、测试类TestMybatis


由于创建的时候mybatis-config.xml的时候文件出现在了两个位置,删除一个之后就可以运行,否则一直找不到该文件而无法运行
CRUD
配置

增加
对应代码片段<insert id="addCategory" parameterType="Category" >
insert into category_ ( name ) values (#{name})
</insert>

删除
对应代码片段<delete id="deleteCategory" parameterType="Category" >
delete from category_ where id= #{id}
</delete>

获取
对应的sql语句:<select id="getCategory" parameterType="_int" resultType="Category">
select * from category_ where id= #{id}
</select>

修改
对应的sql语句:
<update id="updateCategory" parameterType="Category" >
update category_ set name=#{name} where id=#{id}
</update>

查询所有
对应的sql语句<select id="listCategory" resultType="Category">
select * from category_
</select>

在配置文件category.xml中提供CRUD对应的sql语句,当后续需要执行什么操作的时候通过session.insert调用对应的SQL语句,#{name}会自动获取c对象的name属性值。
更多查询
模糊查询
修改Category.xml,提供listCategoryByName查询语句
select * from category_ where name like concat('%',#{0},'%')

多条件查询
结合前面的模糊查询,多一个id>多少的条件
Category.xml 准备sql语句
<select id="listCategoryByIdAndName" parameterType="map" resultType="Category">
select * from category_ where id> #{id} and name like concat('%',#{name},'%')
</select>
因为是多个参数,而selectList方法又只接受一个参数对象,所以需要把多个参数放在Map里,然后把这个Map对象作为参数传递进去
Map<String,Object> params = new HashMap<>();
params.put("id", 3);
params.put("name", "cat");
List<Category> cs = session.selectList("listCategoryByIdAndName",params);
文章介绍了如何使用Mybatis进行基础的数据库操作,包括创建数据库和导入数据,配置实体类Category,设置mybatis-config.xml和Category.xml文件进行CRUD操作。同时,文章还展示了如何进行模糊查询和多条件查询,强调了参数映射和Map对象在处理多个参数时的作用。

被折叠的 条评论
为什么被折叠?



