MyBatis的作用
可以简化JDBC操作,实现数据的持久化
- ORM: Object Relational Mapping
- MyBatis: 是ORM的一个实现(与之相同的还有Hibernate)
- ORM使得开发人员像操作对象一样操作数据库。
MyBatis程序的步骤
- 引入mybatis.jar 和 jdbc.jar
- 配置: conf.xml文件配置数据库的信息和需要加载的映射文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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/football?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="MyNewPass"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 放映射文件 -->
<mapper resource="org/pvtwen/entity/personMapper.xml"/>
</mappers>
</configuration> - 映射文件 xxMapper.xml
1
2
3
4
5
6
7
8
9
<mapper namespace="org.pvtwen.entity.personMapper">
<select id="queryPersonById" resultType="org.pvtwen.entity.Person" parameterType="int">
select * from Person where id = #{id}
</select>
</mapper> - 测试类:
1
2
3
4
5
6
7
8
9
10Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
String statement = "org.pvtwen.entity.personMapper.queryPersonById";
//MyBatis底层通过动态代理将Object对象变成一个Person对象
Person person = session.selectOne(statement, 1);
session.commit();
session.close();注意: 因为transaction的代理模式为JDBC,所以在执行完毕后应该commit和close.
conf.xml文件中各种参数
- dataSource数据源类型 :
- POOLED:使用数据库连接池
- UNPOOLED:传统的JDBC模式
- JNDI:从tomcat中获取一个内置的数据库连接池(数据库连接池-数据源)
- transactionManager事务提交的方式
- type=”JDBC”: 利用JDBC方式处理事务(commit rollback close)
- type=”MANAGED”: 将事务交给其他组件去托管(Spring, jobss)
xxMapper.xml文件中各种参数
- Namespace: 该mapper.xml映射文件的唯一标识符
- 增删改查等标签当中 各参数的含义:
parameterType: 输入参数的类型
resultType: 查询返回结果的类型 - 如果输入参数: 是简单类型 (8个基本类型+String) 可以使用任何占位符, #{xx}
- 如果是对象类型(例如Student),则必须是对象的属性#{属性名}
多个参数的SQL语句
1 | <insert id=”addStudent” parameter=”org.pvtwen.entity.Student”> |
mapper动态代理方式的crud(也叫mybatis开发)
原则:约定优于配置
- 动态代理的几种配置方式
- 配置方式(abc.xml)
1 <name>myProject</name>- 硬编码方式(abc.java)
1
2
3 Configuration conf=new Configuration();
Con.setName(“myProject”);- 约定方式(默认值就是myProject)
具体实现步骤
一:基础环境:mybatis.jar/connector.jar、conf.xml、mapper.xml
二:不同之处:约定的目标:省略掉statement,根据定位,可以直接定位sql语句
三:定义接口:
(a) 方法名和mapper.xml中sql标签的id值相同
(b) 方法的输入参数和mapper.xml文件中标签的parameterType类型一致
(c) 方法的返回值和mapper.xml文件中标签的resultType类型一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 <mapper namespace="org.pvtwen.mapper.StudentMapper">
<select id="queryPersonById" resultType="org.pvtwen.entity.Person" parameterType="int">
select * from Person where id = #{id}
</select>
<update id="updatePersonById" parameterType="org.pvtwen.entity.Person">
update Person set pname=#{pname},age=#{age} where id=#{id}
</update>
<insert id="addPerson" parameterType="org.pvtwen.entity.Person">
insert into Person values(#{id},#{pname},#{age})
</insert>
<select id="queryAllPerson" resultType="org.pvtwen.entity.Person">
select * from Person
</select>
</mapper>(d) Mapper.xml文件中的namespace的值,就是接口的全类名(接口-mapper)
1
2
3
4
5
6
7 public interface StudentMapper {
Person queryPersonById(int id);
List<Person> queryAllPerson();
void updatePersonById(Person person);
void addPerson(Person person);
}
一般将mapper配置文件和接口放在同一个包中
优化配置
- 步骤
- 创建属性文件:db.properties,用于保存数据库的信息
mybatis的全局参数
conf.xml1
2
3
4
5
6
7
8
9
10<settings>
<!-- 开启日志,并指定使用的具体日志 -->
<setting name="logImpl" value="LOG4J"></setting>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"></setting>
<!-- 关闭立即加载 -->
<setting name="aggressiveLazyLoading" value="false"></setting>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
给属性设置别名
- 在conf.xml文件中配置
- 设置单个别名
1
2
3<typeAliases>
<typeAliase type=“org.pvtwen.entity.Student” alias=”student”>
<typeAliases/> - 批量设置别名
将package中的所有类的别名自动替换成其自身的类名1
2
3<typeAliases>
<package name=”org.pvtwen.entity.Student”>
<typeAliases/>
输入参数:parameterType
类型为简单类型(8个基本类型+String)
类型为HashMap
java文件中1
2
3
4Map<String,Object> studentMap=new HashMap<>();
studentMap.put(“stuAge”,24);
studentMap.put(“stuName”,”zs”);Mapper.xml文件中
1
2
3
4<select parameterType=”HashMap”>
Select stuno,stuname,stuage from student where stuage = #{stuAge} or stuname
Like '%${stuName}%'
</select>
注意事项
<transactionManager type=”JDBC”>意味着增删改需要手动提交事务session.commit()
查询缓存
- 一级缓存
第一次查询将对象信息放入sqlsession中、第n次查询从sqlsessio缓存中获取对象,一旦
session.commit()则清理所有的缓存对象 - 二级缓存
- mybatis自带的二级缓存
范围: 同一个namespace(mapper接口的值:包名+接口名称)生成的mapper对象放在同一个二级缓存中
- 第三方的二级缓存
memcache,ehcache
逆向工程
步骤:
- 导入三个jar包,mybatis-generator-core.jar
- 生成逆向工程配置文件 generator.xml,以及其配置信息
Spring整合Mybatis
- 整合思路
- jar包 mybatis-spring.jar
- 建立类-表
- 通过mapper.xml将表和类建立映射关系
- 之前使用conf.xml去配置数据库的信息,现在整合的时候,需要通过spring管理sqlsessionfactory,因此产生factory所需要的数据库信息不用放入
- 之前的Spring -之前的mybatis
1
2
3
4
5
6
7
8
9<!-- 配置数据库相关 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/football?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="MyNewPass"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="6"></property>
</bean>1
2
3
4
5
6
7
8
9
10
11
12
13
14<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/football?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="MyNewPass"/>
</dataSource>
</environment>
</environments>
使用springMybatis整合产物开发程序
目标:通过spring产生mybatis最终操作需要的动态mapper对象
Spring产生 动态mapper对象 有三种方法:
- DAO层实现类 继承 sqlsessiondaosupport类
- 省略掉第一种方式的实现类DaoImpl