首页 > 其他 > 详细

Mybatis 第一天

时间:2017-01-10 23:25:52      阅读:942      评论:0      收藏:0      [点我收藏+]

目录

mybatis    1

1.    jdbc回顾:    1

1.1.    jdbc的问题:    1

2.    mybatis介绍    2

3.    mybatis的整体架构    2

4.    mybatis快速入门    3

4.1.    编写第一个mybatis程序    3

4.1.1.    导入依赖    3

4.1.2.    编写全局配置文件    3

4.1.3.    构建SqlSessionFactory    3

4.1.4.    根据id查询用户信息    4

4.1.5.    错误:    5

4.2.    添加日志支持    5

4.2.1.    导入依赖    5

4.2.2.    编写log4j的配置文件    5

4.3.    mybatis使用步骤总结    5

5.    完整CRUD操作    6

5.1.    创建UserDao接口    6

5.2.    创建UserDao的实现类    6

5.3.    编写User对应的Mapper.xml    6

5.4.    编写测试用例    7

5.5.    解决数据库字段名和实体类属性名不一致的问题    8

5.6.    思考CURDdao中的问题    9········典型的小星星·的···            

6.    动态代理mapper实现类    9

6.1.    名称空间    9

6.2.    通过sqlSession.getMapper(Class)    9

6.3.    使用动态代理总结    10

7.    mybatis-config 配置    10

7.1.    properties(读取外部的资源文件)    10

7.2.    settings(设置)    11

7.2.1.    mapUnderscoreToCamelCase用法:    13

7.3.    typeAliases    13

7.3.1.    typeAliases的使用1    13

7.3.2.    typeAliases的使用2---使用扫描包    14

7.3.3.    mybatis提供的默认别名    14

7.4.    typeHandlers(类型处理器)    15

7.5.    plugins(插件,又名拦截器)    17

7.6.    environments(环境)    17

7.7.    mappers----映射器    18

7.7.1.    使用mapper接口路径:    18

7.7.2.    使用mapper接口扫描包    18

8.    mybait-config梳理    19

9.    Mapper.xml    19

9.1.    CURD操作    19

9.1.1.    select    19

9.1.2.    insert    19

9.1.3.    获取自增的id的值    20

9.1.4.    update    20

9.1.5.    delete    21

9.2.    ${}的用法    21

9.3.    parameterType传入参数    22

9.4.    parameterType传入多个参数    22

9.5.    面试题:#{}${}的区别    23

9.6.    ResultMap    24

9.6.1.    resultMap的自动映射    24

9.7.    sql片段    25

9.7.1.    用法1    25

9.7.2.    用法2    25

10.    动态sql    26

10.1.    if    26

10.1.1.    定义接口    26

10.1.2.    编写mapper和测试类    26

10.1.3.    问题:    27

10.2.    choose,when,otherwise    27

10.2.1.    定义接口    27

10.2.2.    编写mapper.xml    27

10.2.3.    测试    28

10.3.    where set    28

10.3.1.    定义接口    28

10.3.2.    编写mapper.xml    28

10.3.3.    测试    28

10.4.    foreach    29

10.4.1.    定义接口    29

10.4.2.    编写mapper.xml    29

10.4.3.    测试    29

11.    缓存    29

11.1.    一级缓存    29

11.1.1.    测试一级缓存    30

11.1.2.    使用session.clearCache()强制查询不缓存。    30

11.1.3.    执行update,delete,insert 语句的时候,会刷新缓存    30

11.2.    二级缓存    31

11.2.1.    开启二级缓存    31

11.2.2.    测试二级缓存    31

11.2.3.    关闭二级缓存    32

11.2.4.    二级缓存的高级配置    32

12.    高级查询    32

12.1.    案例说明    32

12.2.    需求    33

12.3.    一对一查询    33

SELECT    33

FROM    33

WHERE o.order_number = ‘20140921001‘    33

12.3.1.    一对一查询实现1    33

12.3.2.    一对一查询实现2    34

12.4.    一对多查询    35

SELECT    35

FROM    35

WHERE o.order_number = ‘20140921001‘    35

12.4.1.    定义接口    35

12.4.2.    编写mapper    36

12.4.3.    测试用例    36

12.5.    多对多查询    36

12.5.1.    定义接口    36

12.5.2.    编写mapper.xml    37

12.5.3.    编写测试用例    37

12.6.    resultMap的继承    37

13.    延迟加载    38

13.1.    开启延迟加载    38

13.2.    添加cglib    38

13.3.    接口定义    39

13.4.    mapper定义    39

13.5.    测试类    39

14.    分页插件    39

14.1.    实现通用分页组件    39

14.2.    Mybatisplugin实现原理    40

14.3.    使用PageHelper实现分页    40

14.4.    导入依赖    40

14.5.    配置插件    41

14.6.    在执行查询时设置分页参数    41

15.    mybatisspring整合    41

15.1.    导入依赖    41

15.2.    配置spring文件    42

15.3.    配置SqlSessionFactory    42

15.4.    配置mapper    42

15.5.    使用1    43

15.6.    配置mapper接口扫描器    43

15.7.    mapper接口配置多个包    43

15.8.    Spring配置文件中指定别名包    43

15.9.    Mapper.xmljava代码分离    43

15.10.    mapper整合servcie    43

16.    mybatis整合事务管理    44

16.1.    配置事务管理    44

16.2.    测试    45

 

 

1、书写mybatis的入门案例

2、书写dao层的curd的操作

3、详细去学习mybatis中的配置信息

    3.1 mybatis-config.xml 全局配置

    3.2 *mapper.xml 局部的配置

 

 

  1. (1)参见《eclipse相关配置.docx》,配置好maven和jar包仓库,

  2. (2)导入itcast-parent

技术分享

技术分享

技术分享

直接点击 Finsh完成

 

  1. 新建maven项目。

技术分享

技术分享

技术分享

  1. 导入依赖

    pom.xml文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>cn.itcast.mybatis</groupId>

<artifactId>mybatis-test</artifactId>

<version>0.0.1-SNAPSHOT</version>

<parent>

<groupId>cn.itcast.parent</groupId>

<artifactId>itcast-parent</artifactId>

<version>0.0.1-SNAPSHOT</version>

</parent>

<dependencies>

            <!-- mysql -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

        </dependency>

        <!-- Mybatis -->

        <dependency>

            <groupId>org.mybatis</groupId>

            <artifactId>mybatis</artifactId>

        </dependency>

</dependencies>

 

</project>

导入后效果

技术分享

  1. 项目报错时选中项目,选取 maven ,然后点击 update project解决

技术分享

mybatis

 

  1. jdbc回顾:

 

public static void main(String[] args) throws Exception {

Connection connection = null;

PreparedStatement preparedStatement = null;

ResultSet resultSet = null;

try {

// 加载驱动

Class.forName("com.mysql.jdbc.Driver");

 

// 创建数据库连接

String url = "jdbc:mysql://127.0.0.1:3306/mybatis";

String user = "root";

String password = "123456";

connection = DriverManager.getConnection(url, user, password);

 

// 获取statement对象

String sql = "SELECT * FROM tb_user WHERE id = ?";

preparedStatement = connection.prepareStatement(sql);

 

// 设置参数,2个参数,第一个是下标,从1开始,第二个是参数值

preparedStatement.setLong(1, 1L);

 

// 执行查询

resultSet = preparedStatement.executeQuery();

 

// 遍历结果集

while (resultSet.next()) {

System.out.println("id = " + resultSet.getLong("id"));

System.out.println("name = " + resultSet.getString("name"));

System.out.println("passwd = " + resultSet.getString("password"));

}

} finally {

// 关闭连接释放资源

if (null != resultSet) {

resultSet.close();

}

if (null != preparedStatement) {

preparedStatement.close();

}

if (null != connection) {

connection.close();

}

}

}

 

 

  1. jdbc的问题:

 

技术分享

1、加载驱动问题:

    每次执行都加载驱动

    驱动名称,硬编码到java代码中,如果需要修改驱动。需要修改java文件

解决方案:将驱动名称放入到外部的配置文件

2、数据库的连接信息,硬编码到java代码中,解决方案:外部配置文件

3、设置参数的问题:

    参数下标硬编码了。需要人为的去判断参数的位置。

    

4、遍历结果集:需要人工的判断字段名,以及个位置参数类型,不方便

    是否可以:能够将结果集直接映射到一个pojo对象中

5、频繁的创建连接,关闭连接。导致资源浪费,影响性能,解决:连接池。

 

 

  1. mybatis介绍

 

技术分享

在mybatis的包里面可以看到,ibatis的字样。 Call xxx(1,ss)

 

  1. mybatis的整体架构

 

技术分享

 

  1. mybatis快速入门

    1. 编写第一个mybatis程序

 

hello,看demo(官方文档)

 

  1. 导入依赖

向工程的pom文件中,添加mybatis的依赖

技术分享

  1. 编写全局配置文件

在工程的根目录下面创建一个mybatis-config.xml

技术分享

<?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">

<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/mybatis"/>

<property name="username" value="root"/>

<property name="password" value="admin"/>

</dataSource>

</environment>

</environments>

<mappers>

<mapper resource="mapper.xml"/>

</mappers>

</configuration>

 

  1. 构建SqlSessionFactory

技术分享

 

  1. 根据id查询用户信息

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="abc">

<select id="selectUser" resultType="cn.itcast.mybatis.pojo.User">

select * from tb_user where id = #{id}

</select>

</mapper>

1、创建一个局部的mapper.xml

技术分享

 

 

2、在全局的mybatis-config.xml 中去添加mapper.xml的配置

技术分享

 

3、书写java代码,调用指定的statement,并且传递参数信息。获取返回值

技术分享

  1. 如果出现如下错误:

技术分享

 

问题原因:

mybatis没有引入 mapper

需要在mybatis-config.xml 中使用mapper 去引入外部的mapper.xml

技术分享

  1. 添加日志支持

    1. 导入依赖

技术分享

  1. 编写log4j的配置文件

log4j.properties:

log4j.rootLogger=DEBUG,A1

log4j.logger.org.mybatis=DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

 

日志信息

2016-01-08 10:56:02,081 [main] [org.apache.ibatis.logging.LogFactory]-[DEBUG] Logging initialized using ‘class org.apache.ibatis.logging.slf4j.Slf4jImpl‘ adapter.

2016-01-08 10:56:02,093 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.

2016-01-08 10:56:02,093 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.

2016-01-08 10:56:02,094 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.

2016-01-08 10:56:02,094 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.

org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@62ccf439

org.apache.ibatis.session.defaults.DefaultSqlSession@40378309

2016-01-08 10:56:02,148 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Opening JDBC Connection

2016-01-08 10:56:02,309 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] Created connection 495124555.

2016-01-08 10:56:02,309 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1d83004b]

2016-01-08 10:56:02,321 [main] [abc.selectUser]-[DEBUG] ==> Preparing: select * from tb_user where id = ?

2016-01-08 10:56:02,351 [main] [abc.selectUser]-[DEBUG] ==> Parameters: 1(Long)

2016-01-08 10:56:02,377 [main] [abc.selectUser]-[DEBUG] <== Total: 1

User [id=1, userName=null, password=123456, name=张三, age=30, sex=1, birthday=Wed Aug 08 00:00:00 CST 1984, created=Fri Sep 19 16:56:04 CST 2014, updated=Sun Sep 21 11:24:59 CST 2014]

2016-01-08 10:56:02,380 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1d83004b]

2016-01-08 10:56:02,381 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1d83004b]

2016-01-08 10:56:02,381 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] Returned connection 495124555 to pool.

 

 

  1. mybatis使用步骤总结

0) 配置mybatis-config.xml 全局的配置文件

  1. 创建SqlSessionFactory
  2. 通过SqlSessionFactory创建SqlSession对象
  3. 通过SqlSession操作数据库 s
  4. 调用session.commit()提交事务
  5. 调用session.close()关闭会话

技术分享

 

  1. 完整CRUD操作

    1. 创建UserDao接口

    

    public Integer selectCount();

    

    /**

     * 根据id查询用户信息

     * @param id

     * @return

     */

    public User queryUserById(Long id);

    

    /**

     * 查询所有用户

     * @return

     */

    public List<User> queryAllUser();

    

    /**

     * 添加用户信息

     * @param user

     */

    public void addUser(User user);

    

    /**

     * 修改用户信息

     * @param user

     */

    public void updateUser(User user);

    

    /**

     * 根据id删除用户信息

     * @param id

     */

    public void deleteUserById(Long id);

 

  1. 创建UserDao的实现类

技术分享

技术分享

 

 

  1. 编写User对应的Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namesapce 名称空间,一个标识 -->

<mapper namespace="user">

    <select id="queryUserById" resultType="cn.itcast.mybatis.pojo.User">

        select * from tb_user

        where id = #{id}

    </select>

 

    <!-- resultType:指定结果集的映射的java对象类型 tb_user 对应到User这个类,所以配置 cn.itcast.mybatis.pojo.User -->

    <select id="queryAllUser" resultType="cn.itcast.mybatis.pojo.User">

        select * from tb_user

    </select>

    <!-- parameterType:定义传入参数类型 -->

    <insert id="addUser" parameterType="cn.itcast.mybatis.pojo.User">

        INSERT INTO tb_user (

            id,

            user_name,

            password,

            name,

            age,

            sex,

            birthday,

            created,

            updated

        ) VALUES

        ( NULL,

            #{userName},

            #{password},

            #{name},

            #{age},

            #{sex},

            #{birthday},

            NOW(),

            NOW()

        );

    </insert>

    <update id="updateUser" parameterType="cn.itcast.mybatis.pojo.User">

        UPDATE tb_user SET

                 user_name = #{userName},

                 password = #{password},

                 name = #{name},

                 age = #{age},

                 sex = #{sex},

                 birthday = #{birthday},

                 updated = NOW() WHERE

                (id = #{id});

    </update>

    <delete id="deleteUserById" parameterType="java.lang.Long">

        delete from tb_user where id = #{id}

    </delete>

</mapper>

 

 

  1. 编写测试用例—操作

技术分享

 

技术分享

技术分享

 

  1. 编写测试用例

//    private UserDao userDao;

    private UserMapper userMapper;

    private SqlSession sqlSession;

 

    @Before

    public void setUp() throws Exception {

        //全局配置文件路径

        String resource = "mybatis-config.xml";

//        获取输入流

        InputStream is = Resources.getResourceAsStream(resource);

//        构建sqlSessionFactory

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

          

        sqlSession = sqlSessionFactory.openSession();

          

        

//        userDao进行初始化

//        userDao = new UserDaoImpl(sqlSession);

//        要求:

//        1、对应的mapper中的namesapce 必须和接口的全路径要一致

//        2、要求方法的名字和 statementid的值一直

        userMapper = sqlSession.getMapper(UserMapper.class);

    }

 

    

    @Test

    public void testLogin(){

        User user = userMapper.login("lisi", "123456");

        System.out.println(user);

    }

      

    

    @Test

    public void testQueryUserById() {

        User user = userMapper.queryUserById(2l);

        System.out.println(user);

    }

 

    @Test

    public void testQueryAllUser() {

        List<User> userlist = userMapper.queryAllUser();

        for(User user :userlist){

            System.out.println(user);

        }

    }

 

    @Test

    public void testAddUser() {

        User user = new User();

        user.setName("赵柳");

        user.setAge(19);

        user.setBirthday(new Date());

        user.setPassword("123456");

        user.setSex(1);

        user.setuserName("zhaoliu1");

        int num = userMapper.addUser(user);

        

//        有时候业务可能需要插入到数据库对应的id

        System.out.println( "修改的数目"+num);

//        需要事务进行提交

        System.out.println(user.getId());

        sqlSession.commit();

    }

 

    @Test

    public void testUpdateUser() {

//        更新操作

//        1、先去查询

        User user = userMapper.queryUserById(1l);

        user.setAge(100);

        userMapper.updateUser(user);

//        提交事务

        sqlSession.commit();

    }

 

    @Test

    public void testDeleteUserById() {

        userMapper.deleteUserById(9l);

        sqlSession.commit();

    }

    @Test

    public void testselectCount(){

        System.out.println(userMapper.selectCount());

    }

    

    @Test

    public void selectUserFromTable(){

        this.userMapper.selectUserFromTable("tb_user");

    }

 

 

 

  1. 解决数据库字段名和实体类属性名不一致的问题

查询数据的时候,查不到userName的信息,原因:数据库的字段名是user_name

             POJO中的属性名字是userName

两端不一致,造成mybatis无法填充对应的字段信息。修改方法:在sql语句中使用别名

解决方案1:在sql语句中使用别名

解决方案2: 参考后面的resultMap –mapper具体的配置的时候

解决方案3:参考驼峰匹配 --- mybatis-config.xml 的时候

 

技术分享

 

技术分享

 

 

  1. 知识点回顾:

1、准备一个mybatis-config.xml 全局的配置信息

    连接数据库的参数

    引入mapper.xml

2、构建sqlSessionFactory。

3、获取sqlSession

4、通过sqlsession.insert update delete ,select ()完成数据库的crud的操作

         方法中的参数 sqlSession.insert("名称名字.sql_id");

    5、准备一个mapper.xml 书写各个sql语句

        分别书写在<insert > <select > <update> <delete>

  1. 思考CURD的dao中的问题

1、接口->实现类->mapper.xml

2、实现类中,使用mybatis的方式非常类似

3sql statement 硬编码到java代码中。

 

思考:能否只写接口,不书写实现类,只编写Mapper.xml即可

 

 

  1. 动态代理mapper实现类

因为在dao(mapper)的实现类中对sqlsession的使用方式很类似。mybatis提供了接口的动态代理

 

  1. 名称空间

mapper.xml的 namespace 属性

如果希望使用mybatis通过的动态代理的接口,就需要namespace 中的值,和需要对应的Mapper(dao)接口的全路径一致

技术分享

 

  1. 通过sqlSession.getMapper(Class)

 

 

 

技术分享

 

技术分享

 

  1. 要求mapper中的statement,sql中的id 和方法中的名字一模一样才可以去调用

    1. 使用动态代理总结

技术分享

 

 

  1. mybatis-config 配置

 

技术分享

 

  1. properties(读取外部的资源文件)

通过resource引入外部属性:

 

jdbc.properties

 

技术分享

 

技术分享

 

 

  1. 解决插入数据时中文乱码的问题

在URL后面添加 红色字体部分

url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8

 

 

 

 

设置参数

描述

有效值

默认值

cacheEnabled

该配置影响的所有映射器中配置的缓存的全局开关。

true | false

true

lazyLoadingEnabled

延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。

true | false

false

aggressiveLazyLoading

当启用时,带有延迟加载属性的对象的加载与否完全取决于对任意延迟属性的调用;反之,每种属性将会按需加载。

true | false

true

multipleResultSetsEnabled

是否允许单一语句返回多结果集(需要兼容驱动)。

true | false

true

useColumnLabel

使用列标签代替列名。不同的驱动在这方面会有不同的表现,具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。

true | false

true

useGeneratedKeys

允许 JDBC 支持自动生成主键,需要驱动兼容。如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。

true | false

False

autoMappingBehavior

指定 MyBatis 是否以及如何自动映射指定的列到字段或属性。NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。FULL 会自动映射任意复杂的结果集(包括嵌套和其他情况)。

NONE, PARTIAL, FULL

PARTIAL

defaultExecutorType

配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements);BATCH 执行器将重用语句并执行批量更新。

SIMPLE REUSE BATCH

SIMPLE

defaultStatementTimeout

设置超时时间,它决定驱动等待数据库响应的秒数。

Any positive integer

Not Set (null)

safeRowBoundsEnabled

允许在嵌套语句中使用行分界(RowBounds)。

true | false

False

mapUnderscoreToCamelCase

是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。

true | false

False

localCacheScope

MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。

SESSION | STATEMENT

SESSION

jdbcTypeForNull

当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULLVARCHAR OTHER

JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER

OTHER

lazyLoadTriggerMethods

指定哪个对象的方法触发一次延迟加载。

A method name list separated by commas

equals,clone,hashCode,toString

defaultScriptingLanguage

指定动态 SQL 生成的默认语言。

A type alias or fully qualified class name.

org.apache.ibatis.scripting.xmltags.XMLDynamicLanguageDriver

callSettersOnNulls

指定当结果集中值为 null 的时候是否调用映射对象的 settermap 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意原始类型(intboolean等)是不能设置成 null 的。

true | false

false

logPrefix

指定 MyBatis 增加到日志名称的前缀。

Any String

Not set

logImpl

指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING

Not set

proxyFactory

Mybatis 用来创建具有延迟加载能力的对象设置代理工具。

CGLIB | JAVASSIST

CGLIB

 

 

帮助我们完成数据库的经典命名规则,到java的命名规则的映射

数据库的经典命名规则:userName === user_name 值的映射

    java中的经典命名规则:驼峰。

 

    把数据库中下划线去掉,映射到java中的对象的属性。

 

技术分享

 

 

技术分享

技术分享

 

 

缺点:需要为每一个实体类pojo都去设置别名。

技术分享

 

 

已经为普通的 Java 类型内建了许多相应的类型别名。它们都是大小写不敏感的,需要注意的是由于重载原始类型的名称所做的特殊处理。

别名

映射的类型

_byte

byte

_long

long

_short

short

_int

int

_integer

int

_double

double

_float

float

_boolean

boolean

string

String

byte

Byte

long

Long

short

Short

int

Integer

integer

Integer

double

Double

float

Float

boolean

Boolean

date

Date

decimal

BigDecimal

bigdecimal

BigDecimal

object

Object

map

Map

hashmap

HashMap

list

List

arraylist

ArrayList

collection

Collection

iterator

Iterator

 

 

技术分享

 

类型处理器

Java 类型

JDBC 类型

BooleanTypeHandler

java.lang.Booleanboolean

任何兼容的布尔值

ByteTypeHandler

java.lang.Bytebyte

任何兼容的数字或字节类型

ShortTypeHandler

java.lang.Shortshort

任何兼容的数字或短整型

IntegerTypeHandler

java.lang.,Integer int

任何兼容的数字和整型

LongTypeHandler

java.lang.Longlong

任何兼容的数字或长整型

FloatTypeHandler

java.lang.Floatfloat

任何兼容的数字或单精度浮点型

DoubleTypeHandler

java.lang.Doubledouble

任何兼容的数字或双精度浮点型

BigDecimalTypeHandler

java.math.BigDecimal

任何兼容的数字或十进制小数类型

StringTypeHandler

java.lang.String

CHAR VARCHAR 类型

ClobTypeHandler

java.lang.String

CLOB LONGVARCHAR 类型

NStringTypeHandler

java.lang.String

NVARCHAR NCHAR 类型

NClobTypeHandler

java.lang.String

NCLOB 类型

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

其他或未指定类型

EnumTypeHandler

Enumeration Type

VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引)

EnumOrdinalTypeHandler

Enumeration Type

任何兼容的 NUMERIC  DOUBLE 类型,作为位置存储(而不是代码本身)。

 

技术分享

 

 

技术分享

 

技术分享

 

自定义拦截器:

 

技术分享

 

技术分享

 

技术分享

作用:将mapper.xml 文件配置到mybatis的环境中。

 

技术分享

 

这里所谓的mapper接口路径。实际上就是dao的接口路径。在mybatis中,通常把dao的包叫做mapper

类名,也叫做mapper

 

1、定义一个接口

2、在接口所在的包中定义mapper.xml

3、在mybatis-config.xml 中通过class路径,引入mapper。要求mapper.xml 中的名称空间是类的接口的全路径

 

技术分享

 

技术分享

技术分享

 

问题:

1、mapper.xml 和 java文件没有分离。 明天和spring整合之后解决。

2、需要一个一个的去加载mapper

 

 

技术分享

 

缺点:

如果包的路径有很多? 明天spring整合的时候解决。

 

技术分享

 

1、properties,引入外部的文件,保存了 jdbc相关参数

技术分享

 

2、settings设置---开启驼峰匹配

技术分享

 

3、类型别名---使用扫描包的形式使用类型别名

技术分享

 

4、配置数据库的环境

技术分享

 

5、配置mapper,引入外部的mapper.xml ---使用扫描包的方式

技术分享

 

 

 

技术分享

 

 

 

select – 书写查询sql语句

select中的几个属性说明:

 

id属性:当前名称空间下的statement的唯一标识。必须。要求id和mapper接口中的方法的名字一致。

resultType:将结果集映射为java的对象类型。必须(和 resultMap 二选一)

 

parameterType:传入参数类型。可以省略

 

 

技术分享

 

 

 

insert 的几个属性说明:

id属性:当前名称空间下的statement的唯一标识(必须属性);

parameterType:传入的参数类型,可以省略。

标签内部:具体的sql语句。

使用#{} 去替换一个变量。

 

 

技术分享

 

 

 

技术分享

 

update 的几个属性说明:

id属性:当前名称空间下的statement的唯一标识(必须属性);

parameterType:传入的参数类型,可以省略。

标签内部:具体的sql语句。

使用#{} 去替换一个变量。

 

 

技术分享

 

delete 的几个属性说明:

id属性:当前名称空间下的statement的唯一标识(必须属性);

parameterType:传入的参数类型,可以省略。

标签内部:具体的sql语句。

使用#{} 去替换一个变量。

 

 

技术分享

 

 

需求:数据库有两个一模一样的表。历史表,当前表

查询表中的信息,有时候从历史表中去查询数据,有时候需要去新的表去查询数据。

希望使用1个方法来完成操作。

 

使用#的时候出现问题:

技术分享

 

技术分享

 

注意#{} 只是替换? 这个功能,sql语句中 ? 只能出现where中。 当作一个变量

 

${} 数据:是进行字符串拼接。

如果使用${} 去取出参数信息,则需要在方法的参数列表上加上一个注释@param 表示参数的名字

#{} 只是表示站位,与参数的名字无关。

 

sql语句动态生成的时候,使用${};

sql语句中某个参数进行站位的时候#{}

 

技术分享

技术分享

技术分享

 

 

 

 

 

 

定义传入参数的类型:

可以使用#{} 进行接受一个变量,可以${}接受一个变量

 

如果${} 没有指定参数名(在方法的参数列表中没有加入@Param)可以使用${value} 表示传递过来的参数。

技术分享

 

可以在方法的参数列表列表上 @param("参数名")

 

技术分享

 

1、如果使用$去传递参数的时候,使用@Param

2、如果传入多个参数的时候,使用@Param

 

如果代码这样书写:

java代码:

技术分享

mapper.xml

user_name = #{userName} and password = #{password}

 

传递多个参数的时候出现如下错误:

技术分享

对于传入多个参数的时候,#{} 需要使用参数名的方式去获取数据。

 

解决方案1:

在mapper.xml中使用 0,1这样的序号去,0表示第一个参数,1表示第二个参数。

技术分享

或者:

技术分享

 

解决方案2:

在java代码中加入param注解

 

技术分享

 

在mapper.xml 中

技术分享

 

 

技术分享

 

技术分享

 

 

推荐使用 @Param注解

 

 

 

技术分享

 

${} statement对象

#{} Preparedstatement对象

 

${} 方式:

技术分享

 

技术分享

 

 

案例:

使用#方式

技术分享

技术分享

 

使用$方式:

 

技术分享

 

dao层给servcie去使用。一个方法可能被多个service所使用。

使用#的方式,需要每个servcie方法都在传递参数之前,进行字符串拼接

$只是在xml中去拼接一次即可。

 

技术分享

 

 

 

技术分享

 

技术分享

 

 

技术分享

 

 

在一个mapper.xml 中使用<sql> 去定义sql片段,然后在需要的位置使用<include> 引入

技术分享

将所有的公用的SQL片段集中定义到一个Mapper.xml文件中,其他Mapper.xml文件如需引入,通过命名空间.id即可。

技术分享

 

引入公共的sql.xml

 

技术分享

 

sqlMapper.xml

 

 

 

技术分享

 

技术分享

 

 

需求1:查询男性用户,如果输入了姓名,就使用姓名进行模糊查找,否则返回所有男性。

 

技术分享

 

 

使用# {}的方式

技术分享

技术分享

 

 

或者使用${}的方式

 

技术分享

 

技术分享

 

 

choose,when,otherwise 相当于java中的 if, elseif的逻辑

 

查询男性用户,如果输入了姓名则按照姓名模糊查找,姓名不为空时忽略年龄这个条件,当姓名为空,年龄不为空,则按照年龄查找。

 

 

技术分享

<!-- queryUserManByNameOrAge    查询男性用户,如果输入了姓名则按照姓名模糊查找,

        姓名不为空时忽略年龄这个条件,当姓名为空,年龄不为空,则按照年龄查找 -->

    <select id="queryUserManByNameOrAge" resultType="User">

        select * from tb_user where sex=1

         <choose>

             <when test="name != null and name != ‘‘">     and user_name like ‘%${name}%‘ </when>

             <otherwise>

<!--               此处必须判断age非空 -->

              <if test="age > 0">and age = #{age}</if>

             </otherwise>

         </choose>

    </select>

 

 

1.名称有值时忽略年龄

技术分享

2.名称为null时,且年龄不为空,安装年龄进行查找

 

技术分享

 

3.参数都为空时,查询所有

 

技术分享

作用:完成WHERE和SET关键字,并且处理SQL语句的中语法错误。

 

 

where 是 条件

set update。

 

语法错误: where and

set aa=‘‘ , bb=‘‘ ,

 

练习:查询所有用户,如果输入了姓名按照姓名进行模糊查询,如果输入年龄,按照年龄进行查询。

 

技术分享

 

技术分享

 

 

技术分享

 

10.3.4 set set标签可以替代sql语句里面的set,并且可以自动判断条件后的逗号分割

接口定义

技术分享

mapper

技术分享

测试

技术分享

执行效果

技术分享

 

10.3.5 特殊字符的处理

技术分享

技术分享

 

按照多个id查询用户信息 select * from tb_user where id in (1,2,3,4)

 

技术分享

 

 

技术分享

 

 

技术分享

 

 

技术分享

 

在mybatis中,一级缓存默认是开启的,并且一直无法关闭

 

1、测试代码

技术分享

 

2、日志输出

技术分享

 

一级缓存满足条件:

 

 

 

1、代码

技术分享

2、日志输出:

技术分享

 

技术分享

 

技术分享

mybatis 的二级缓存的作用域是一个mapper的namespace ,同一个namespace中查询sql可以从缓存中命中。

 

需要在mapper.xml 中加入如下:

技术分享

java代码:

技术分享

 

 

日志输出:

 

技术分享

 

在全局的mybatis-config.xml 中去关闭二级缓存

 

技术分享

 

技术分享

 

 

技术分享

 

技术分享

 

技术分享

技术分享

 

查询订单,并且查询出下单人的信息

 

 

sql语句分析:

SELECT

    o.*,

    u.user_name,

u.name

FROM

    tb_order o

LEFT JOIN tb_user u ON u.id = o.user_id

 

WHERE o.order_number = ‘20140921001‘

 

 

 

核心思想:扩展Order对象,来映射结果结。

 

技术分享

 

 

接口定义:

技术分享

 

mapper.xml中的定义

 

技术分享

 

测试类

 

 

 

核心思想:面向对象的思想,在Order对象中添加User对象。

技术分享

 

 

使用resultType不能完成自动映射,所以需要手动完成结果集的映射,需要使用resultMap实现。

技术分享

 

 

 

一对多查询:根据订单号查询订单,查询出下单人信息并且查询出订单明细。

 

sql:

 

SELECT

    o.*,

    u.user_name,

u.name,

d.*

FROM

    tb_order o

LEFT JOIN tb_user u ON u.id = o.user_id

LEFT JOIN tb_orderdetail d ON d.order_id = o.id

 

WHERE o.order_number = ‘20140921001‘

Order类:

 

技术分享

 

 

 

接口定义:

技术分享

 

 

 

 

技术分享

技术分享

 

 

技术分享

 

 

 

多对多查询:查询订单,查询出下单人信息并且查询出订单详情中的商品数据。

java对象的实现,在订单详情里添加商品对象为属性:

技术分享

 

接口:

技术分享

技术分享

技术分享

技术分享

 

技术分享

 

 

 

技术分享

 

 

技术分享

 

技术分享

 

    <dependency>

        <groupId>cglib</groupId>

        <artifactId>cglib</artifactId>

        <version>3.1</version>

</dependency>

技术分享

技术分享

技术分享

 

 

 

技术分享 

 

 

技术分享

 

技术分享

 

 

<dependency>

        <groupId>com.github.pagehelper</groupId>

        <artifactId>pagehelper</artifactId>

        <version>3.7.5</version>

    </dependency>

    <dependency>

        <groupId>com.github.jsqlparser</groupId>

        <artifactId>jsqlparser</artifactId>

        <version>0.9.1</version>

</dependency>

技术分享

 

 

     <plugins>

     <!-- com.github.pagehelper为PageHelper类所在包名 -->

     <plugin interceptor="com.github.pagehelper.PageHelper">

         <!-- 数据库方言 -->

     <property name="dialect" value="mysql"/>

     <!-- 设置为true时,使用RowBounds分页会进行count查询 会去查询出总数 -->

     <property name="rowBoundsWithCount" value="true"/>

     </plugin>

    </plugins>

 

技术分享

 

 

 

<!-- 整合包 -->

        <dependency>

            <groupId>org.mybatis</groupId>

            <artifactId>mybatis-spring</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-context</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-beans</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-jdbc</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-aspects</artifactId>

        </dependency>

          

        <dependency>

            <groupId>c3p0</groupId>

            <artifactId>c3p0</artifactId>

            <version>0.9.1.2</version>

        </dependency>

技术分享

 

 

1、创建spring的配置文件applicationContext.xml

 

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

 

 

配置资源文件替换器

 

<!-- 使用spring自带的占位符替换功能 -->

    <bean

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <!-- 配置资源文件 -->

        <property name="locations">

            <list>

                <value>classpath:c3p0.properties</value>

            </list>

        </property>

    </bean>

 

配置连接池:

 

<!-- 配置连接池 -->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

        destroy-method="close">

        <property name="driverClass" value="${c3p0.driverClass}"></property>

        <property name="jdbcUrl" value="${c3p0.url}"></property>

        <property name="user" value="${c3p0.user}"></property>

        <property name="password" value="${c3p0.password}"></property>

    </bean>

 

 

  1. 配置SqlSessionFactory

<!-- 配置SqlSessionFactory -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />

        <!--引入mybatis的总配置 -->

        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

    </bean>

 

  1. 配置mapper

 

<!-- 配置mapper -->

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">

        <property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper" />

        <property name="sqlSessionFactory" ref="sqlSessionFactory" />

    </bean>

 

 

 

  1. 使用1

  2. 配置mapper接口扫描器

 

<!-- 配置mybatis mapper接口扫描器 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

         <property name="basePackage" value="cn.itcast.mybatis.mapper" />

    </bean>

 

 

  1. mapper接口配置多个包

多个包使用逗号分割即可:

技术分享

 

 

  1. 在Spring配置文件中指定别名包

 

    <!-- 配置SqlSessionFactory -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />

        <!--引入mybatis的总配置 -->

        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <!-- 类型别名扫描包 -->

        <property name="typeAliasesPackage" value="cn.itcast.mybatis.pojo"></property>

    </bean>

 

 

  1. Mapper.xml和java代码分离

 

技术分享

<!--         配置mapper.xml的文件夹,使java代码和xml文件分离 -->

        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>

  1. mapper整合servcie

 

servcie方法:

 

技术分享

 

 

技术分享

<context:component-scan base-package="cn.itcast.mybatis.service.impl"/>

测试:

 

技术分享

 

  1. mybatis整合事务管理

    1. 配置事务管理

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    

    <!-- 定义事务管理器 -->

    <bean id="transactionManager"

        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

 

    <!-- 定义事务策略 -->

    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <!--所有以query开头的方法都是只读的 -->

            <tx:method name="query*" read-only="true" />

            <!--其他方法使用默认事务策略 -->

            <tx:method name="*" />

        </tx:attributes>

    </tx:advice>

 

    <aop:config>

        <!--pointcut元素定义一个切入点,execution中的第一个星号 用以匹配方法的返回类型,

            这里星号表明匹配所有返回类型。 com.abc.dao.*.*(..)表明匹配cn.itcast.mybatis.service包下的所有类的所有

            方法 -->

        <aop:pointcut id="myPointcut" expression="execution(* cn.itcast.mybatis.service.*.*(..))" />

        <!--将定义好的事务处理策略应用到上述的切入点 -->

        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />

    </aop:config>

    

</beans>

  1. 测试

package cn.itcast.test;

 

import org.junit.Before;

import org.junit.Test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

import cn.itcast.mybatis.pojo.User;

import cn.itcast.mybatis.service.UserService;

 

public class UserServiceTest {

 

UserService userService;

 

@Before

public void setUp() throws Exception {

String resource = "applicationContext.xml";

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(resource);

userService = applicationContext.getBean(UserService.class);

}

 

@Test

public void testGetUserById(){

User user = userService.getUserById(25L);

System.out.println(user);

}

 

}

 

 

 

  1. 练习内容:

  2. 动态sql,if choose when otherwise where set foreach

  3. 高级查询 resultMap的使用 association collection

  4. Spring和mybatis的整合

Mybatis 第一天

原文:http://www.cnblogs.com/beyondcj/p/6271165.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!