Mybatis学习--5.使用Mybatis进行CRUD
步骤
使用maven创建工程
引入依赖:mybatis依赖、mysql-connector依赖,junit依赖,logback依赖
编写核心配置文件:mybatis-config.xml,并放在resource根路径下
创建XxxMapper.xml文件,在其中编写sql语句
<insert id="insertCar"> insert into t_car values(null,#{car_num},#{brand},#{guide_price},#{produce_time},#{car_type}); </insert> <delete id="deleteById"> delete from t_car where id = #{id}; </delete> <update id="updateById"> update t_car set guide_price = #{guide_price} where id = #{id}; </update> #{}里写属性名(和EL表达式用法类似,通过get方法查找)或map的key值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
5. 为了方便,编写一个MyBatis工具类
6. 创建一个java类,通过工具类获得SqlSession对象,通过SqlSession对象执行CRUD操作
1. 通过map集合传入参数
* ```java
public void testInsert(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
Map<String,Object> map = new HashMap<>();
map.put("car_num",1004);
map.put("brand","比亚迪");
map.put("guide_price",10);
map.put("produce_time",2023-11-11);
map.put("car_type","新能源");
int count = sqlSession.insert("insertCar", map);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
通过pojo对象传入参数
Car car = new Car(null,"1004","BYD","10","2022-11-11","新能源"); sqlSession.insert("insertCar",car);
1
2
3
4
5
6
7
8
9
10
11
2.
* 查询语句:
* mybatis底层是将查询到的结果封装成一个对象放入结果集中,所以我们需要告诉mybatis将查询到的结果封装为哪个java对象。可以通过select标签中的resultType属性进行设置
* ```xml
<select id="selectById" resultType=""></select>
- 需要注意的是,在编写查询的sql语句时,由于其底层是将查询到的结果封装为指定的java对象,所以需要保证查询的列名和对象属性名一致,可以使用as语法替换列名
XxxMapper.xml文件中的namespace
- 该属性是用来指定命名空间的,其作用为防止sql语句的ID冲突
- 在mybatis中是根据namespace.id来执行相应的sql语句
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 dch'blog!