MyBatis 框架 浅析

更详细的内容可以查看 官方给出的文档 : http://www.mybatis.org/mybatis-3/zh/getting-started.html

一.重要的SqlSessionFactory对象

见名知意, SqlSessionFactory是生产 SqlSession的工厂, 而执行SQL语句必须要通过 SqlSession对象 ,因此获取SqlSessionFactory 是第一步

根据SqlSessionFactoryBuilder类中的 实例方法 build() 一般使用下图中的两种方式重载方法构建SqlSessionFactory对象, 1种是通过接收InputStream 刘对象
另一种是通过接收Configuration对象. 通常更多的是创建配置文件,使用第一种方式,即传入InputStream对象
 

获取SqlSessionFactory对象的方式共两种:
/**** 方式一: 从 XML 中构建 SqlSessionFactory ****/
String resource = "mybatis_config.xml";
// 加载mybatis的配置文件(它也加载关联的映射文件)
InputStream inputStream = null;
try {
    inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
    e.printStackTrace();
}
// 构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

附上项目结构:

附上供于本地调试的POM文件:

<?xml version="1.0" encoding="UTF-8"?>
<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>mybatis_study</groupId>
    <artifactId>mybatis_study</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

    </dependencies>
</project>

附上 mybatis的 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>
    <!--为类的权限定名称设置简短的别名-->
    <typeAliases>
        <typeAlias type="com.baoxian.domain.UserInfo" alias="UserInfo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/> <!--事务管理类型-->
            <dataSource type="POOLED">
                <property name="username" value="root"/>
                <property name="password" value=""/>
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/crm?serverTimezone=GMT%2B8"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--存放处理SQL语句的XML文件-->
    <mappers>
        <mapper resource="com/baoxian/dao/UserInfoMapper.xml"/>
        <mapper resource="com/baoxian/dao/ProductMapper.xml"/>
    </mappers>
</configuration>
/**** 方式二: 不使用 XML 构建 SqlSessionFactory ****/
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

//此种方式没有写过测试, 详细细节待补充;对此种构建方式有兴趣的小伙伴可以自行查阅资料(但一般都是使用第一种方式)

二.通过SqlSeesionFactory 创建 SqlSession对象

//创建SQLSession
/*
            sqlSession默认是不自动提交事务的,所以insert,delete ,update 默认是不会生效的
            开启自动提交事务的两种解决方案:
            1.openSession(true);
            2.sqlSession.commit();手动提交事务
*/
SqlSession sqlSession = sessionFactory.openSession(true);

三 .通过SqlSession对象执行一条简单的select 语句:

执行select语句的方式同样有两种:

方式一:直接通过SqlSession对象中封装的实例方法,执行SQL语句

    @Test
    public void testSelectOne() {
        try{
            UserInfo user = sqlSession.selectOne("com.baoxian.dao.UserInfoMapper.selectUserById", 1L);
            System.out.println(user);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }

    }
附上 UserInfo 的实例类:
package com.baoxian.domain;

public class UserInfo {

    private long id;
    private String userName;
    private int age;


    public long getId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }

    public int getAge() {
        return age;
    }

    public void setId(long id) {
        this.id = id;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "id=" + id +
                ", name='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}

附上userInfo的表设计:



方式二:通过SqlSession获取 Mapper接口对象,再通过接口对象调用接口中的方法(接口中的方法名称,返回值,形参要与Mapper.xml文件中保持一致)

相比方式一: 此种方式更加直观,而且不用传入较长的xml文件路径 ,避免了代码的写死 ,因此推荐方式二
  @Test
    public void testSelectOne2() {
        try{
            UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
            UserInfo userInfo = mapper.selectUserById(1L);
            System.out.println(userInfo);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }

 附上UserInfoMapper接口的代码:

package com.baoxian.dao;

import com.baoxian.domain.UserInfo;

import java.util.List;

public interface UserInfoMapper {

    //查询全部User
    public List<UserInfo> selectAll();

    //根据user的ID查询User对象
    public UserInfo selectUserById(Long id);
}

附上UserInfoMapper.xml文件的代码:

对于初学者来说,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.baoxian.dao.UserInfoMapper" >
  <!--
    正常情况下 type 需要写上实体类的全限定名称,但是由于在 mybatis的配置文件中,即 mybatis_config.xml中指定了别名,所以可以使用别名的方式
    <resultMap id="BaseResultMap" type="com.baoxian.domain.UserInfo" >
    -->
  <resultMap id="BaseResultMap" type="UserInfo" >
    <id column="id" property="id"  />
    <result column="username" property="userName"  />
    <result column="age" property="age"  />
  </resultMap>

  <!--通过ID删除用户-->
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from UserInfo
    where id = #{id}
  </delete>

  <!--新增用户-->
  <insert id="insert" parameterType="com.baoxian.domain.UserInfo" useGeneratedKeys="true" keyProperty="id" >
    insert into UserInfo (username,age)
    values (#{userName},#{age})
  </insert>

  <!--通过ID更新用户-->
  <update id="updateByPrimaryKey" parameterType="com.baoxian.domain.UserInfo" >
    update UserInfo
    set username = #{userName},age =#{age}
    where id = #{id}
  </update>

  <!--通过ID查找用户-->
  <select id="selectUserById" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select id,userName,age
    from UserInfo
    where id = #{id}
  </select>

  <!--查询出所有用户-->
  <select id="selectAll" resultMap="BaseResultMap" >
    select id, username,age from userinfo
  </select>

</mapper>

猜你喜欢

转载自www.cnblogs.com/lzzRye/p/9388177.html