美文网首页
Mybatis(二):使用方法

Mybatis(二):使用方法

作者: aix91 | 来源:发表于2019-01-23 12:49 被阅读0次

1. 目录结构

目录结构

2. 获取SqlSessionFactory

SqlSessionFactoryBuilder有5个build()方法用于创建SqlSessionFactory:

SqlSessionFactory build(InputStream inputStream)
SqlSessionFactory build(InputStream inputStream, String environment)
SqlSessionFactory build(InputStream inputStream, Properties properties)
SqlSessionFactory build(InputStream inputStream, String env, Properties props)
SqlSessionFactory build(Configuration config)

其中inputStream就是mybatis配置文件的Reader实例,可选的参数是environment 和 properties,分别用来决定代码环境和参数文件。
由于参数的获取方式有多种,mybatis于是按照优先级来获取参数:
方法传递参数 > properties 元素的类路径 resource或者url指定的元素 > properties 元素体指定的属性
最后的一个方法,传入的参数是Configuration。其实Configuration类,包含了创建SqlSessionFactory所需要的所有的内容:

DataSource dataSource = BaseDataTest.createBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();

Environment environment = new Environment("development", transactionFactory, dataSource);

Configuration configuration = new Configuration(environment);
configuration.setLazyLoadingEnabled(true);
configuration.setEnhancementEnabled(true);
configuration.getTypeAliasRegistry().registerAlias(Blog.class);
configuration.getTypeAliasRegistry().registerAlias(Post.class);
configuration.getTypeAliasRegistry().registerAlias(Author.class);
configuration.addMapper(BoundBlogMapper.class);
configuration.addMapper(BoundAuthorMapper.class);

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(configuration);

这其实和mybatis 的配置文件一样

<?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="${db.driver}"/>
                <property name="url" value="jdbc:mysql://${db.host}:3306/${db.database}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="data/TestMapper.xml"/>
    </mappers>
</configuration>

3. 获取SqlSession

SqlSessionFactory中用于创建SqlSession的方法

SqlSession openSession()
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType)
SqlSession openSession(ExecutorType execType, boolean autoCommit)
SqlSession openSession(ExecutorType execType, Connection connection)

在创建SqlSession时需要考虑:

  • session是否需要使用事务或者自动提交功能(开启事务就不自动提交了)
  • 是否需要自定义数据源配置(connection)
  • 是否需要复用预处理语句和批量更新处理

4. 使用映射器Mapper

  • 定义映射器接口
public interface TestMapper {
    void insert(@Param("user") User user);
    select(@Param("name") String name);
    List<User> selectAll();
}
  • 定义映射器xml文件: 指定namespace为定义的映射器接口
<?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="data.TestMapper">
    <select id="select" resultType="model.User">
      select name,age from mybatis where name=#{name}
    </select>
    <select id="selectAll" resultType="model.User">
      select name,age from mybatis
    </select>
    <insert id="insert" parameterType="model.User">
      insert into mybatis(name,age) values(#{user.name},#{user.age})
    </insert>
</mapper>
  • 在mybatis-config.xml 文件中,指定mapper
    <mappers>
        <mapper resource="data/TestMapper.xml"/>
    </mappers>
  • 使用SqlSession创建Mapper
        TestMapper mapper = session.getMapper(TestMapper.class);
        mapper.insert(user);
        List<User> users = mapper.selectAll();
        User userSelected = mapper.select("peggi");

相关文章

网友评论

      本文标题:Mybatis(二):使用方法

      本文链接:https://www.haomeiwen.com/subject/lgeljqtx.html