视频观看地址:http://edu.51cto.com/course/14674.html?source=so
1、配置文件(mybatis-config.xml)
1.1、properties 属性
之前我们编写jdbc模板类中使用属性文件db.properties文件,在mybatis中也可以这样配置
src目录下建立一个db.properties文件
db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
db.username=scott
db.password=tiger
接下来需要在mybatis-config.xml文件中进行加载
接下来测试即可
1.2、驼峰命名
是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。
在mybatis中开启驼峰命名
设置完毕后,我们更改一个之前的sql,不采用别名的方式进行
测试该方法,查看日志
DEBUG - Opening JDBC Connection
DEBUG - Created connection 532118459.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@1fb77bbb]
DEBUG - ==> Preparing: select * from tb_user
DEBUG - ==> Parameters:
DEBUG - <== Total: 4
User [userid=2, userName=张三, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=3, userName=李四, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=4, userName=王五, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
User [userid=5, userName=赵六, pwd=123456, age=10, sex=男, birthday=Mon Aug 13 10:07:55 CST 2018]
DEBUG - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@1fb77bbb]
DEBUG - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@1fb77bbb]
DEBUG - Returned connection 532118459 to pool.
但是有的时候,我们的数据库的列的命名和实体类没有遵守驼峰命名,此时就需要我们后面讲解resultMap类型来搞定
1.3、typeAliases
每个mapper文件中关于resultType,parameterType这样的属性写全类名太麻烦,我们可以通过此属性进行优化
在mybatis-config.xml中加入别名设置
单一设置:
扫描包设置:
直接运行测试即可
1.4、类型处理器
类型处理器是在设置参数,以及从result中检索值来匹配java数据类型,MyBatis提供了非常多的默认类型处理器,满足我们的开发要求。不需要自定义
类型处理器 | Java 类型 | JDBC 类型 |
---|---|---|
BooleanTypeHandler |
java.lang.Boolean , boolean |
数据库兼容的 BOOLEAN |
ByteTypeHandler |
java.lang.Byte , byte |
数据库兼容的 NUMERIC 或 BYTE |
ShortTypeHandler |
java.lang.Short , short |
数据库兼容的 NUMERIC 或 SHORT INTEGER |
IntegerTypeHandler |
java.lang.Integer , int |
数据库兼容的 NUMERIC 或 INTEGER |
LongTypeHandler |
java.lang.Long , long |
数据库兼容的 NUMERIC 或 LONG INTEGER |
FloatTypeHandler |
java.lang.Float , float |
数据库兼容的 NUMERIC 或 FLOAT |
DoubleTypeHandler |
java.lang.Double , double |
数据库兼容的 NUMERIC 或 DOUBLE |
BigDecimalTypeHandler |
java.math.BigDecimal |
数据库兼容的 NUMERIC 或 DECIMAL |
StringTypeHandler |
java.lang.String |
CHAR , VARCHAR |
ClobReaderTypeHandler |
java.io.Reader |
- |
ClobTypeHandler |
java.lang.String |
CLOB , LONGVARCHAR |
NStringTypeHandler |
java.lang.String |
NVARCHAR , NCHAR |
NClobTypeHandler |
java.lang.String |
NCLOB |
BlobInputStreamTypeHandler |
java.io.InputStream |
- |
ByteArrayTypeHandler |
byte[] |
数据库兼容的字节流类型 |
BlobTypeHandler |
byte[] |
BLOB , LONGVARBINARY |
DateTypeHandler |
java.util.Date |
TIMESTAMP |
DateOnlyTypeHandler |
java.util.Date |
DATE |
TimeOnlyTypeHandler |
java.util.Date |
TIME |
SqlTimestampTypeHandler |
java.sql.Timestamp |
TIMESTAMP |
SqlDateTypeHandler |
java.sql.Date |
DATE |
SqlTimeTypeHandler |
java.sql.Time |
TIME |
ObjectTypeHandler |
Any | OTHER 或未指定类型 |
EnumTypeHandler |
Enumeration Type | VARCHAR-任何兼容的字符串类型,存储枚举的名称(而不是索引) |
EnumOrdinalTypeHandler |
Enumeration Type | 任何兼容的 NUMERIC 或 DOUBLE 类型,存储枚举的索引(而不是名称)。 |
InstantTypeHandler |
java.time.Instant |
TIMESTAMP |
LocalDateTimeTypeHandler |
java.time.LocalDateTime |
TIMESTAMP |
LocalDateTypeHandler |
java.time.LocalDate |
DATE |
LocalTimeTypeHandler |
java.time.LocalTime |
TIME |
OffsetDateTimeTypeHandler |
java.time.OffsetDateTime |
TIMESTAMP |
OffsetTimeTypeHandler |
java.time.OffsetTime |
TIME |
ZonedDateTimeTypeHandler |
java.time.ZonedDateTime |
TIMESTAMP |
YearTypeHandler |
java.time.Year |
INTEGER |
MonthTypeHandler |
java.time.Month |
INTEGER |
YearMonthTypeHandler |
java.time.YearMonth |
VARCHAR or LONGVARCHAR |
JapaneseDateTypeHandler |
java.time.chrono.JapaneseDate |
DATE |
1.5、environments
开发环境:开发人员日常开发的时候使用的环境
测试环境:测试人员测试的时候使用环境
预发布环境:几乎和线上环境一模一样,在上线之前在进行一次测试。
生成环境:线上环境。正式的 java 程序运行的环境
MyBatis允许配置多个环境,比如说开发环境,测试环境,生成环境,但是在构建SqlSessionFactory时只能选择一个,虽然这种方式也可以做到很方便的分离多个环境,但是在实际场景下我们是更多的使用Spring来管理数据源,做到环境的分离
1.6、Mapper映射器
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要定义 SQL 映射语句了。但是首先我们需要告诉 MyBatis 到哪里去找到这些语句。 Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的 URL),或类名和包名等。例如:
1.使用相对于类路径的资源引用
2.使用完全限定资源定位符(URL)
3.使用映射器接口实现类的完全限定类名
4、映射器接口扫描包的方式
2、基于Mapper接口下的数据操作
2.1、概述
在 mybatis 中 dao 层的接口名字不推荐使用Dao,而是修改成Mapper,例如 UserDao 修改成 UserMapper
由于在 dao(mapper)的实现类中对 sqlsession 的使用方式很类似。mybatis 提供了接口的动态代理
2.2、动态代理的注意事项
1.将dao包更改命名为cn.org.kingdom.mapper(可选)
2.将接口也改为xxMapper的形式(可选)
3.删除所有的dao类实现类(必须)因为此时我们是通过动态代理的方式来生成其操作类
4.将映射文件放在mapper包下,并且将该映射文件名更改为接口的名字.xml
namespace:
根标签的 namespace 属性称为名称空间,如果希望使用 mybatis 通过的动态代理的接口,就需要 namespace 中的值,和需要对应的Mapper(dao)接口的全路径一致
注意此时还需要保证我们接口中的方法名和配置文件中的id名称保持一致
2.3、具体操作
mapper接口实现
package cn.org.kingdom.mapper;
import java.util.List;
import cn.org.kingdom.pojo.User;
public interface UserMapper {
public int insertUser(User vo) throws Exception;
public int updateUser(User vo) throws Exception ;
public int deleteUser(int userid) throws Exception ;
public User selectUserById(int userid) throws Exception ;
public List selectAll() throws Exception;
public int getAllCounts() throws Exception ;
}
将mapper.xml文件复制到mapper包中,并且将该文件的名称命名为Mapper接口的名字.xml(UserMapper.xml)
修改mybatis-config.xml文件
测试类进行测试
package cn.org.kingdom.test;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cn.org.kingdom.mapper.UserMapper;
import cn.org.kingdom.pojo.User;
public class MyBatisTest01 {
SqlSessionFactory sqlSessionFactory = null ;
SqlSession sqlSession = null ;
UserMapper userMapper = null ;
@Before
public void setUp() throws Exception {
//加载资源
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
}
@After
public void tearDown() throws Exception {
//关闭
sqlSession.close();
}
@Test
public void testInsertUser() {
User vo = new User("阿珂", "123456", 18, "女", new Date());
try {
userMapper.insertUser(vo);
//提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
}
}
@Test
public void testUpdateUser() {
User vo = new User(7,"冰封战神", "123456", 18, "男", new Date());
try {
userMapper.updateUser(vo);
//提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
}
}
@Test
public void testDeleteUserById() {
int sid = 7 ;
try {
userMapper.deleteUser(sid);
//提交事务
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
}
}
@Test
public void testSelectAll() throws Exception {
List list = userMapper.selectAll();
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testGetCount() throws Exception{
int count = userMapper.getAllCounts() ;
System.out.println(count);
}
@Test
public void testFindUserById() throws Exception{
User user = userMapper.selectUserById(2);
System.out.println(user);
}
}
测试完成:
这里需要大家注意:一定要保证mapper接口中的方法名和mapper.xml中的id名称保持一致
mapper.xml中的namespace必须是mapper接口的全类名
insert into tb_user(userid,user_name,age,pwd,sex,birthday)
values(seq_user.nextval,#{userName},#{age},#{pwd},#{sex},#{birthday})
update tb_user set user_name=#{userName},age=#{age},pwd=#{pwd},sex=#{sex},birthday=#{birthday}
where userid=#{userid}
delete from tb_user where userid=#{userid}