Mybatis
1.准备
1.创建数据库
CREATE TABLE `user`(`id` INT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,`name` VARCHAR(30) DEFAULT NULL,`pwd` VARCHAR(30) DEFAULT NULL
);
-- 插入示例数据
INSERT INTO `user` (`id`, `name`, `pwd`) VALUES
(1, '张三', 'zhangsan123'),
(2, '李四', 'lisi456'),
(3, '王五', 'wangwu789'),
(4, '赵六', NULL), -- 密码为NULL(使用默认值)
(5, NULL, 'zhaoqi101'); -- 姓名为NULL(使用默认值)
2.搭建环境
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306"/><property name="username" value="root"/><property name="password" value="1234"/></dataSource></environment></environments><mappers><mapper resource="org/mybatis/example/BlogMapper.xml"/></mappers>
</configuration>
3.编写Mybatis工具类
获取SqlSessionFactory对象
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public class MybatisUtils {public static SqlSessionFactory sqlSessionFactory;static {try {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {throw new RuntimeException(e);}}
// 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。public static SqlSession getSqlSession() {return sqlSessionFactory.openSession();}
}
2.编写
1.实现类
public class User {private Integer id;private String name;private String pwd;public User() {}
}
dao接口
public interface UserDao {List<User> getUSerList();
}
接口实现类Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace=绑定一个对应的Mapper接口-->
<mapper namespace="com.shang.dao.UserDao"><select id="getUSerList" resultType="com.shang.pojo.User">select * from mybatis.user;</select>
</mapper>
3.测试
可能出现的问题:
1.resources/mybatis-config.xml中要配置
<mappers><mapper resource="com/shang/dao/UserMapper.xml"/>
</mappers>
2.maven资源无法导出解决方案
pop.xml中配置
<build><!-- 资源插件配置 --><resources><resource><!-- 主资源目录(默认是src/main/resources) --><directory>src/main/resources</directory><!-- 包含所有文件 --><includes><include>**/*.*</include></includes></resource><!-- 如果资源放在src/main/java下,需要额外配置 --><resource><directory>src/main/java</directory><!-- 匹配java目录下的xml、properties等资源文件 --><includes><include>**/*.xml</include><include>**/*.properties</include><!-- 其他类型的资源文件 --></includes><!-- 不排除任何文件 --><filtering>true</filtering></resource></resources>
</build>
junit测试,并且建包和Java建包保持一致
public class UserDaoTest {@Testpublic void test(){SqlSession sqlSession = MybatisUtils.getSqlSession();
// 获取mapper和方法UserDao mapper = sqlSession.getMapper(UserDao.class);List<User> userList = mapper.getUserList();for (User user : userList) {System.out.println(user);}
// 关闭sqlSessionsqlSession.close();}
}
4.CRUD
Select
id: 方法名
resultType: 返回值类型,eg:自定义实体类user(List
paramType: 参数类型 eg:方法getUserBYID(int id) 传入的参数类型为int
<select id="getUserBYID" parameterType="int" resultType="com.shang.pojo.User">select * from mybatis.user where id = #{id};
</select>
insert
接口
int insertUser(User user);
实现接口
<insert id="insertUser" parameterType="com.shang.pojo.User">insert into mybatis.user (id, name, pwd) values(#{id}, #{name}, #{pwd});
</insert>
测试
@Testpublic void insertUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();
// 获取mapper和方法UserMapper mapper = sqlSession.getMapper(UserMapper.class);int res = mapper.insertUser(new User(6, "小亮", "123"));
// 提交事务sqlSession.commit();
// 关闭sqlSessionsqlSession.close();}
注意!不要忘记提交事务!!!
Update,Delete
int updateUser(User user);
int deleteUser(int id);
<update id="updateUser" parameterType="com.shang.pojo.User">update mybatis.user set name=#{name},pwd = #{pwd} where id = #{id};
</update><delete id="deleteUser" parameterType="int">delete from mybatis.user where id = #{id};
</delete>
@Testpublic void updateUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();
// 获取mapper和方法UserMapper mapper = sqlSession.getMapper(UserMapper.class);int res = mapper.updateUser(new User(6, "小亮plus", "123plus"));
// 提交事务sqlSession.commit();
// 关闭sqlSessionsqlSession.close();}@Testpublic void testDeleteUser(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);int res = mapper.deleteUser(6);sqlSession.commit();sqlSession.close();}