观黑马32期就业班笔记
目录
MyBatis介绍
原来是Apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年迁移到GitHub。
是一个持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
jdbc存在问题
- 数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。如果使用数据库连接池可解决此问题。
- Sql语句在代码中硬编码,造成代码不易维护,实际应用中sql变化的可能较大,sql变动需要改变java代码。
- 使用preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不一定,可能多也可能少,修改sql还要修改代码,系统不易维护。
- 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便。
MyBatis架构
- 这里,其实SqlSession就能连接到数据库,Executor属于SqlSession的一部分,MappedStatement属于Executor的一部分
- MappedStatement中有类似jdbc中
?
的占位符:#{}
,输入映射到其中,再到数据库中查找,然后产生输出
需要掌握
- 根据用户id查询一个用户
- 根据用户名称模糊查询用户列表
- 添加用户
- 更新用户
- 删除用户
根据用户id查询一个用户
MybatisFirstTest.java 创建工厂、执行SQL语句
public class MybatisFirstTest
{
public void testMybatis() throws Exception
{
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in=Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
User user=sqlSession.selectOne("test.findUserById",10);
System.out.prinln(user);
}
User.xml 写SQL语句
<!--命名空间,用于区分不同xml文件但id相同的情况-->
<mapper namespace="test">
<!--resultType是返回值,需要写全称-->
<select id="findUserById" parameterType="Integer"
resultType="com.itheima.mybatis.pojo.User">
select * from user where id=#{v}
</select>
</mapper>
通过用户名称模糊查询用户列表
public class MybatisFirstTest
{
public void testMybatis() throws Exception
{
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in=Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
List<User> users=sqlSession.selectList("test.findUserByUsername","五");
for(User user2:users){
System.out.prinln(user);
}
}
<mapper namespace="test">
<select id="findUserByUserName" parameterType="String"
resultType="com.itheima.mybatis.pojo.User">
<!--
#{} select * from user where id=?
占位符,自带单引号,使用时不需要加
${} select * from user where username like '%五%'
字符串拼接,需要加上单引号使用
-->
select * form user where username like '%${value}%'
<!--
还可以使用"%"#{}"%"
此时大括号中的内容无限制(因为是占位符)
-->
</select>
</mapper>
添加用户
public void testInsertUser() throws Exception{
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in=Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
User user=new User();
user.setId(29)
user.setUsername("曾志伟");
user.setBirthday(new Date());
user.setAddress("北京");
user.setSex("男");
int i=sqlSession.insert("test.insertUser",user)
sqlSession.commit();//提交
}
<mapper namespace="test">
<insert id="insertUser"
parameterType="com.itheima.mybatis.pojo.User">
insert into user(username,birthday,address,sex)
values (#username,birthday,address,sex)
</insert>
</mapper>
更新用户
public void testUpdateUserById() throws Exception{
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in=Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
User user=new User();//更新也需要创建对象
user.setId(29)//根据id查询,id不变
user.setUsername("曾伟");
user.setBirthday(new Date());
user.setAddress("南京");
user.setSex("女");
int i=sqlSession.update("test.updateUserById",user);
<mapper namespace="test">
<update id="updateUserById" parameterType="com.itheima.mybatis.pojo.User">
update user
set username=#{username},sex=#{sex},
birthday=#{birthday},address=#{address}
where id=#{id}
</update>
</mapper>
删除用户
public void testUpdateUserById() throws Exception{
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in=Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
SqlSession.delete("test.deleteUserById",29)
sqlSession.commit();
<mapper namespace="test">
<delete id="deleteUserById" parameterType="Integer">
delete from user where id=#{id};
</delete>
<mapper>
Mybatis解决jdbc编程的问题
- 数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能,如果使用数据库连接池可解决此问题。
解决:在SqlMapConfig.xml中配置数据连接池,使用连接池管理数据库链接。 - Sql语句写在代码中造成代码不易维护,实际应用sql变化的可能较大,sql变动需要改变java代码。
解决:将Sql语句配置在XXXXmapper.xml文件中与java代码分离。 - 向sql语句传参数麻烦,因为sql语句的where条件不一定,可能多也可能少,占位符需要和参数一一对应。
解决:Mybatis自动将java对象映射至sql语句,通过statement中的parameterType定义输入参数的类型。 - 对结果集解析麻烦,sql变化导致解析代码变化,且解析前需要遍历,如果能将数据库记录封装成pojo对象解析比较方便。
解决:Mybatis自动将sql执行结果映射至java对象,通过statement中的resultType定义输出结果的类型。
Mybatis和Hibernate区别
Mybatis和hibernate不同,它不完全是一个ORM框架,因为MyBatis需要程序员自己编写Sql语句。mybatis可以通过XML或注解方式灵活配置要运行的sql语句,并将java对象和sql语句映射生成最终执行的sql,最后将sql执行的结果再映射生成java对象。
Mybatis学习门槛低,简单易学,程序员直接编写原生态sql,可严格控制sql执行性能,灵活度高,非常适合对关系数据模型要求不高的软件开发,例如互联网软件、企业运营类软件等,因为这类软件需求变化频繁,一但需求变化要求成果输出迅速。但是灵活的前提是mybatis无法做到数据库无关性,如果需要实现支持多种数据库的软件则需要自定义多套sql映射文件,工作量大。
Hibernate对象/关系映射能力强,数据库无关性好,对于关系模型要求高的软件(例如需求固定的定制化软件)如果用hibernate开发可以节省很多代码,提高效率。但是Hibernate的学习门槛高,要精通门槛更高,而且怎么设计O/R映射,在性能和对象模型之间如何权衡,以及怎样用好Hibernate需要具有很强的经验和能力才行。
总之,按照用户的需求在有限的资源环境下只要能做出维护性、扩展性良好的软件架构都是好架构,所以框架只有适合才是最好。
Mapper动态代理开发
使用MyBatis开发Dao,有原始Dao开发方法和Mapper动态代理开发两种。以下介绍动态代理开发。
接口遵循四个原则:
- 接口方法名==User.xml中id名
- 返回值类型与 Mapper.xml 文件中返回值类型一致
- 方法的入参类型与 Mapper.xml 文件中入参类型一致
- User.xml的命名空间绑定此接口
创建接口 UserMapper.java
public interface UserMapper{
//方法名与xml中id名相同
//入参、返回值类型与xml相同
public User findUserById(Integer id);
}
User.xml
<!--命名空间绑定接口-->
<mapper namespace="com.itheima.mybatis.mapper.UserMapper">
<!--入参、返回值-->
<select id="findUserById" parameterType="Integer"
resultType="com.itheima.mybatis.pojo.User">
</select>
</mapper>
测试 MybatisMapperTest.java
public class MybatisMapperTest{
public void testMapper() throws Exception{
//加载核心配置文件
String resource="sqlMapConfig.xml";
InputStream in=Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//执行sql语句
//sqlSession帮助生成一个实现类
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
//直接调用方法
User user=userMapper.findUserById(10);
System.out.println(user);
}
}