MyBatis基础 Day11 2018-11-29

2018-11-29  本文已影响0人  Ernest_Chou

二、mybatis基础

1. typeAliases类型设置别名

mybatis-config.xml文件中设置:

<!-- 配置类型别名  User 可以使用在任何使用com.zhougl.web.beans.PhoneUser的地方-->
<typeAliases>
    <typeAlias alias="User" type="com.zhougl.web.beans.PhoneUser"/>
</typeAliases>
<!-- 设置包扫描(别名) 制定一个包名,每一个在该包中的java Bean ,没有注解的情况下会使用Bean的首字母小写的非限定类名作为别名,有注解则为主键值@Alias("User")-->
<typeAliases>
    <package name="com.zhougl.web.beans" />
</typeAliases>
@Alias("User")
public class PhoneUser {
}

2.mapper映射器

<!-- 配置持久化类映射文件:用来配置sql语句和结果集类型等 -->
    <!-- 使用类路径查找资源文件 -->
    <mappers>
        <mapper resource="com/zhougl/web/dao/mapper/PhoneUserMapper.xml" />
    </mappers>
    <!-- 使用本地文件 -->
    <mappers>
        <mapper url="file:///D:\OxygenWorkspace\maven-mybatis\src\main\java\com\zhougl\web\dao\mapper\PhoneUserMapper.xml"/>
    </mappers>
    <!-- 使用包名 非注解模式的话xml配置文件必须也处于同一级 package 下,且与Mapper类同名-->
    <mappers>
        <package name="com.zhougl.web.dao.mapper"/>
    </mappers>

3.<selectKey>生成主键

 <insert id="insert" parameterType="com.zhougl.web.beans.PhoneDepartment">
    <selectKey keyProperty="id" resultType="String" order="BEFORE">
        select SQ_PHONE_DEPARTMENT_ID.nextval as id from dual
    </selectKey>
    insert into PHONE_DEPARTMENT (ID, DEPARTMENT_NAME, DEPARTMENT_CODE
      )
    values (#{id,jdbcType=VARCHAR}, #{departmentName,jdbcType=VARCHAR}, #{departmentCode,jdbcType=VARCHAR}
      )
  </insert>

4. sql代码段

<!--  引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<!-- 属性代码段可以被包含在其他语句里面 -->
<sql id="sometable">${prefix}Table</sql>
<sql id="someinclude">from <include refid="${include_target}"/></sql>
<!-- 属性值可以用于包含的refid属性或包含的代码段里面的属性 -->
<select id="select" resultType="map">
    select field1,field2,field3 
    <include refid="someinclude">
        <property name="prefix" value="Some" />
        <property name="include_target" value="sometable"/>
    </include>
</select>

5.SqlSessionFactoryUtil工厂类封装方法

public class SqlSessionFactoryUtil {
    
    private static SqlSessionFactory sqlSessionFactory = null;
    //创建初始化SqlSessionFactory对象
    static {
        try {
            //读取mybatis-config.xml配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            
            e.printStackTrace();
        }
    }
    //获取SqlSession对象的静态方法
    public static  SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
    //获取SqlSessionFactory的静态方法
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

6. <association>一对一查询

<association>元素的解释:

6.1 基本应用

6.1.1 java bean
public class WebClass {
    private BigDecimal id;
    private String code;
    private String name;
    //班级与学生是一对多的关系
    private List<Student> students;
    
}
public class Student {
    private BigDecimal id;

    private String name;

    private String sex;

    private Short age;
    //学生与班级是多对一的关系
    private WebClass webClass;
} 
6.1.1 映射文件
<mapper namespace="com.zhougl.web.dao.StudentDao">
  <resultMap id="StudentMap" type="com.zhougl.web.beans.Student">
    <id column="id" jdbcType="DECIMAL" property="id" />
    <result column="studentName" jdbcType="VARCHAR" property="name" />
    <result column="SEX" jdbcType="VARCHAR" property="sex" />
    <result column="AGE" jdbcType="DECIMAL" property="age" />
    <!-- 一对多 -->
    <association property="webClass" column="class_id"
     javaType="com.zhougl.web.beans.WebClass" 
     select="selectClassById"/>
  </resultMap>
 
  <select id="selectClassById" parameterType="int" resultType="com.zhougl.web.beans.WebClass">
    select * from WEB_CLASS  where ID = #{id,jdbcType=DECIMAL}
  </select>
  <select id="selectStudent" parameterType="int" resultMap="StudentMap">
    select * from STUDENT
  </select>
 
</mapper>
6.1.2 测试代码
public static void main(String[] args) {
        SqlSession session = SqlSessionFactoryUtil.getSession();
        List<Student> students = session.selectList("com.zhougl.web.dao.StudentDao.selectStudent");
        students.forEach(student -> System.out.println(student));
        session.commit();
        session.close();
    }
==>  Preparing: select * from STUDENT 
==> Parameters: 
====>  Preparing: select * from WEB_CLASS where ID = ? 
====> Parameters: 1(Integer)
<====      Total: 1
====>  Preparing: select * from WEB_CLASS where ID = ? 
====> Parameters: 2(Integer)
<====      Total: 1
<==      Total: 4
Student [id=1, name=null, sex=女, age=22, webClass=WebClass [id=1, code=C001, name=大乱斗指导班]]
Student [id=2, name=null, sex=女, age=24, webClass=WebClass [id=2, code=C002, name=无限流战斗班]]
Student [id=3, name=null, sex=男, age=28, webClass=WebClass [id=1, code=C001, name=大乱斗指导班]]
Student [id=4, name=null, sex=女, age=26, webClass=WebClass [id=2, code=C002, name=无限流战斗班]]

6.2 一对一映射(接口)

6.2.1 java bean
public class Card {
    private Integer id;
    private String code;
    //省略构造器和set/get方法
}
public class Person {
    private Integer id;
    private String name;
    private String sex;
    private Short age;
    private Card card;
    //省略构造器和set/get方法
}
6.2.2 映射文件
<mapper namespace="com.zhougl.web.dao.mapper.CardMapper">
  <sql id="Base_Column_List">
    ID, CODE
  </sql>
 
  <select id="selectCardById" parameterType="integer" resultType="com.zhougl.web.beans.Card">
    select 
    <include refid="Base_Column_List" />
    from CARD
    where ID = #{id,jdbcType=DECIMAL}
  </select>
 
</mapper>
<mapper namespace="com.zhougl.web.dao.mapper.PersonMapper">
    <resultMap id="personMap" type="com.zhougl.web.beans.Person">
        <id column="ID" jdbcType="DECIMAL" property="id" />
        <result column="NAME" jdbcType="VARCHAR" property="name" />
        <result column="SEX" jdbcType="VARCHAR" property="sex" />
        <result column="AGE" jdbcType="DECIMAL" property="age" />
        <!-- 一对一关联映射 -->
        <association property="card" column="CARD_ID"
            javaType="com.zhougl.web.beans.Card"
            select="com.zhougl.web.dao.mapper.CardMapper.selectCardById" />
    </resultMap>

    <sql id="Base_Column_List">
        ID, NAME, SEX, AGE, CARD_ID
    </sql>

    <select id="selectPersonById" parameterType="integer"
        resultMap="personMap">
        select
        <include refid="Base_Column_List" />
        from PERSON
        where ID = #{id,jdbcType=DECIMAL}
    </select>
</mapper>
6.2.3 接口
public interface PersonMapper {
    /**
     * 方法名与参数必须和xml文件中<select...>的id属性和parameterType属性一致
     * @param id
     * @return Person
     */
    Person selectPersonById(Integer id);  
}
6.2.4 测试类
public class OneToOneTest {
    public static void main(String[] args) {
        SqlSession session = SqlSessionFactoryUtil.getSession();
        //获得mapper接口代理对象
        PersonMapper mapper = session.getMapper(PersonMapper.class);
        //直接调用接口方法,查询数据
        Person person = mapper.selectPersonById(1);
        System.out.println(person);
        System.out.println(person.getCard());
        session.commit();
        session.close();
    }
}

上一篇下一篇

猜你喜欢

热点阅读