MyBatis快速入门
思路流程:搭建环境—>导入Mybatis–>编写代码—>测试
1、代码演示
1.1、搭建数据库
CREATE DATABASE `mybatis`; USE `mybatis`; CREATE TABLE `user` ( `id` int(20) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `address` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`username`,`address`) values (1,'詹姆斯','克里夫'), (2,'科比','洛杉矶'), (3,'保罗','洛杉矶'), (4,'苏炳添','中国');
1.2、导入MyBatis相关依赖
<!--导入mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <!--导入mysql依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency>
1.3、编写Mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--配置环境(可以配置多套环境,可以指定选用的环境)--> <environments default="development"> <!--配置mysql的环境--> <environment id="development"> <!--配置事务的类型--> <transactionManager type="JDBC"/> <!--配置数据源(连接池)--> <dataSource type="POOLED"> <!--配置连接数据库的基本信息--> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--指定映射配置文件的位置--> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
1.4、编写实体类
package com.lili.entity; /** * 对应数据库下的t_user表 * * @author: QiJingJing * @create: 2021/8/6 */ public class User { /** * 用户编号 */ private int id; /** * 姓名 */ private String username; /** * 住址 */ private String address; public void setId(int id) { this.id = id; } public User() { } public User(String username, String address) { this.username = username; this.address = address; } public int getId() { return this.id; } public void setUsername(String username) { this.username = username; } public String getUsername() { return this.username; } public void setAddress(String address) { this.address = address; } public String getAddress() { return this.address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", address='" + address + '\'' + '}'; } }
1.5、编写Mybatis工具类(获取SqlSession对象)
package com.lili.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * 获取sqlSession对象 * * @author: QiJingJing * @create: 2021/8/6 */ public class MybatisUtil { private static SqlSessionFactory sqlSessionFactory; static { try { // 获取sqlSessionFactory InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); } } /** * 获取sqlSession对象 */ public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
1.6、编写Mapper接口类
public interface UserMapper { /** * 查询所有操作 */ List<User> findAll(); }
1.7、编写Mapper.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mapper.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lili.dao.UserMapper"> <!--查询所有信息--> <select id="findAll" resultType="com.lili.entity.User"> select * from user </select> </mapper>
1.8、编写测试类
public class MybatisTest { @Test public void userDaoTest() { // 放到 try 里面sqlSession会自动关闭 try (SqlSession sqlSession = MybatisUtil.getSqlSession()) { // 执行sql UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.findAll(); userList.forEach(System.out::println); } catch (Exception e) { e.printStackTrace(); } } }
1.9、运行测试,结果如下
User{id=1, username='詹姆斯', address='克里夫'} User{id=2, username='科比', address='洛杉矶'} User{id=3, username='保罗', address='洛杉矶'} User{id=4, username='苏炳添', address='中国'}
2、CRUD
2.1、select
- select语句的属性
- id
- 命名空间中唯一标识符
- 接口中的方法必须与映射文件中的SQL语句ID一一对应
- parameterType
- 传入SQL的参数类型。【如果参数过多可以使用Map】
- resultType:
- SQL语句返回值类型。【完整的类名或别名】
需求1:根据id查询用户
1.在UserMapper中添加对应方法
public interface UserMapper { /** * 查询所有操作 */ List<User> findAll(); /** * 根据id查询用户 */ User findById(@Param("id") int id); }
2.在UserMapper.xml中添加对应select语句
<!--查询根据Id查询用户--> <select id="findById" parameterType="integer" resultType="com.lili.entity.User"> select * from user where id = #{id} </select>
3.测试类中进行测试
@Test public void test2() { // 获取SqlSession try (SqlSession sqlSession = MybatisUtil.getSqlSession()) { // 得到UserMapper对象 UserMapper mapper = sqlSession.getMapper(UserMapper.class); // 执行查询 User user = mapper.findById(1); // 打印 System.out.println(user); } catch (Exception e) { e.printStackTrace(); } }
4.输出如下
User{id=1, username='詹姆斯', address='克里夫'}
需求2:根据用户名和住址查询用户
方法一:直接在方法中传递参数
- 在接口方法的参数前加 @Param属性
- Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型
User findByUA(@Param("username") String username,@Param("address") String address); <select id="findByUA" resultType="com.lili.entity.User"> select * from user where username = #{username} and address = #{address} </select>
方法二:使用Map传参
1.在接口方法上,直接使用map参数
User findByMap(Map<String,Object> map);
2.UserMapper.xml
<select id="findByMap" parameterType="map" resultType="com.lili.entity.User"> select * from user where username = #{username} and address = #{address} </select>
3.在使用方法的时候,Map的key为sql中取得值即可,没有顺序要求
Map<String,Object> map = new HashMap<>(); map.put("username","苏炳添"); map.put("address","中国"); // 执行查询 User user = mapper.findByMap(map);
2.2、insert
需求:给数据库增加一个用户
1.在UserMapper中添加对应方法
int addUser(User user);
2.UserMapper.xml
<insert id="addUser" parameterType="com.lili.entity.User"> insert into user (`id`, `username`, `address`) values (#{id}, #{username}, #{address}) </insert>
3.测试代码
User user = new User(); user.setId(5); user.setUsername("齐菁菁"); user.setAddress("河南"); // 执行添加 int i = mapper.addUser(user); System.out.println(i); // 注意:增删改操作必须提交 sqlSession.commit();
2.3、update
需求 :把id为5的地址改为中国
1.在UserMapper中添加对应方法
int update(@Param("address") String address,@Param("id") int id);
2.UserMapper.xml
<update id="update" > update user set address = #{address} where id = #{id} </update>
3.测试代码
UserMapper mapper = sqlSession.getMapper(UserMapper.class); int i = mapper.update("中国", 5); System.out.println(i); // 注意:增删改操作必须提交 sqlSession.commit();
2.4、delete
需求 :根据id删除一个用户
1.在UserMapper中添加对应方法
int deleteById(@Param("id") int id);
2.UserMapper.xml
<delete id="deleteById" > delete from user where id = #{id} </delete>
3.测试代码
int i = mapper.deleteById(1); System.out.println(i); // 注意:增删改操作必须提交 sqlSession.commit();
小结:
- 所有的增删改操作都需要提交事务!
- 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
- 有时候根据业务的需求,可以考虑使用map传递参数!
- 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!