Mybatis SqlSessionFactory常用创建方式(IDEA)

    最近在重新看mybatis文档时,又将mybatis的基本操作又练了练手。mybatis的操作,是通过SqlSessionFactory对象来操作数据sql,官网也写了两种SqlSessionFactory对象的创建方式,下面说一下两种方式不同的区别,一种是基于XML配置文件的创建方式,一种是JAVA代码的方式。今天想记录这篇博客也是因为中间通过Java代码创建方式的时候,中间遇到些问题。

XML配置文件方式

  主要归结于一下几个步骤:

1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象; 

2、书写sql映射文件;配置了每一个sql,以及sql的封装规则等。

3、将sql映射文件注册在全局配置文件中

4、写代码:

   1)、根据全局配置文件得到SqlSessionFactory(通过SqlSessionFactoryBuilder工厂方法创建);

  2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查; 一个sqlSession就是代表和数据库的一次会话,用完关闭

  3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。

实现细节

数据源

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3308/SPRINGBOOT
jdbc.username=root
jdbc.password=123456

首先全局配置文件(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>
    <properties resource="db.properties"></properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="LOG4J"/>
        <!--<setting name="logPrefix" value="mapper." />-->
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!--mapper sql映射文件-->
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

UserMapper(interface)

public interface UserMapper {
//根据ID查询
    User findById(Integer id);
}

UserMapper(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">
<mapper namespace="mapper.UserMapper">
    <select id="findById" resultType="domain.User">
    select * from USER where id = #{id}
  </select>
</mapper>

通过配置文件实现


    @Test
    public void test() throws Exception {

        String resource = "mybatis-config.xml";
//获取配置文件流
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession session = sqlSessionFactory.openSession();

        User u = session.selectOne("mapper.UserMapper.findById", 1);
        System.out.println("user:" + u);
        session.close();

    }

通过JAVA代码的方式创建

上面就是通过全局配置文件的实现方式,官网文档介绍:

注意该例中,configuration 添加了一个映射器类(mapper class)。映射器类是 Java 类,它们包含 SQL 映射语句的注解从而避免了 XML 文件的依赖。不过,由于 Java 注解的一些限制加之某些 MyBatis 映射的复杂性,XML 映射对于大多数高级映射(比如:嵌套 Join 映射)来说仍然是必须的。有鉴于此,如果存在一个对等的 XML 配置文件的话,MyBatis 会自动查找并加载它(这种情况下, BlogMapper.xml 将会基于类路径和 BlogMapper.class 的类名被加载进来)
@Test
    public void test5() throws Exception {
        //创建连接池
        DataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3308/SPRINGBOOT", "root", "123456");
        //事务
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        //创建环境
        Environment environment = new Environment("development", transactionFactory, dataSource);
        //创建配置
        Configuration configuration = new Configuration(environment);
        //开启驼峰规则
        configuration.setMapUnderscoreToCamelCase(true);
        //加入资源(Mapper接口)
        configuration.addMapper(UserMapper.class);
        //
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
       
        SqlSession session = sqlSessionFactory.openSession();

        try {
          //statement:sql唯一标识(mapper.xml映射文件中的id标识)
          //parament:参数
            User user = session.selectOne("mapper.UserMapper.findById", 1);
            System.out.println(user);
            //操作数据时,需要有提交操作
            session.commit();
        } finally {
            session.close();
        }
    }

这里使用IDEA实现的话,可能会报下面的错误

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for mapper.UserMapper.findById
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for mapper.UserMapper.findById

这里是idea编译的问题,他默认不是编译java文件夹下的.xml文件,这里我们可以在配置文件中添加这块的编译;我这里使用的Maven方式,我们只需要在pom文件中,添加build标签中,添加需要编译的xml文件位置;也可以直接放到resource资源文件中,也就是类路径;这里可以添加多个。

 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>classpath</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

  通过以上方式实现SqlSessionFactory的对象创建。

  代码的仓库地址: github地址

IDEA 中使用 MyBatis 项目,你需要进行以下步骤: 1. 首先,你需要在你的项目中添加 MyBatis 的依赖项。可以在 Maven 或 Gradle 中添加: ``` <!-- Maven --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> // Gradle implementation 'org.mybatis:mybatis:3.5.6' ``` 2. 在你的项目中,创建一个 MyBatis 的配置文件,例如 `mybatis-config.xml`。在这个文件中配置 MyBatis 的一些基本信息,例如数据库连接信息、类型别名、mapper 配置等。 3. 在你的项目创建一个 mapper 接口,定义 SQL 语句和参数映射。例如: ```java public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(int id); } ``` 4. 在你的项目创建 mapper 接口对应的 XML 文件,例如 `UserMapper.xml`。在这个文件中配置 SQL 语句和参数映射。例如: ```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"> <mapper namespace="com.example.mapper.UserMapper"> <select id="getUserById" parameterType="int" resultMap="userResultMap"> SELECT * FROM user WHERE id = #{id} </select> <resultMap id="userResultMap" type="com.example.entity.User"> <id column="id" property="id"/> <result column="username" property="username"/> <result column="password" property="password"/> <result column="email" property="email"/> <result column="phone" property="phone"/> <result column="created_time" property="createdTime"/> <result column="updated_time" property="updatedTime"/> </resultMap> </mapper> ``` 5. 在你的项目中,配置 MyBatis 的扫描包路径和 mapper 配置文件路径。例如: ```xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml"/> </bean> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.example.mapper.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> ``` 6. 最后,在你的项目中调用 mapper 接口方法进行数据库操作。例如: ```java @Autowired private UserMapper userMapper; public User getUserById(int id) { return userMapper.getUserById(id); } ``` 以上就是在 IDEA 中使用 MyBatis 项目的步骤。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值