Java学习笔记10 ── MyBatis(HelloWorld、核心配置文件介绍、映射文件介绍)

HelloWorld

导入jar包

需要用到下面三个jar包
myBatis-3.4.1.jar
mysql-connector-java-5.1.37-bin.jar
log4j.jar

创建并配置MyBaits核心配置文件

通过阅读MyBaits的官方文档,我们拿过来一份配置文件,命名为mybaits-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/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapping.xml"/>
    </mappers>
</configuration>

创建实体bean和数据库操作接口

实体bean中有以下五个属性,接口中提供一个通过id获取User对象的抽象方法

    private Integer uid;

    private String userName;

    private String password;

    private Integer age;

    private String sex;
public interface UserMapper {
    public User getUserById(String id);
}

创建并配置映射文件

一般以xxxMapping,xml命名,这里是和User类建立映射关系,所以命名为UserMapping.xml,其中namespace属性用来和接口关联,填的内容是接口的全限定名;
select标签中的id属性与方法名保持一致,resultType与返回值类型保持一致。创建完成了以后注意修改mybatis-config.xml中的mappers标签。

<?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.glq.mapper.UserMapper">
    <select id="getUserById" resultType="com.glq.bean.User">
        select * from user where uid = #{id}
    </select>
</mapper>
    <mappers>
        <mapper resource="UserMapping.xml"/>
    </mappers>

获取SqlSession进行测试

首先获取数据源的输入流,然后创建一个SqlSessionFactory对象并通过这个对象来获得SqlSession对象,再通过getMapper方法获取UserMapper对象,最后进行执行。执行结果如下:

    @Test
    public void test1() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById("1");
        System.out.println(userById);
    }

在这里插入图片描述

配置文件标签介绍

environments标签

用来配置数据库的连接环境,default:设置默认使用的数据库环境,可以不使用默认的,修改为mysql等,使用不同的数据库修改为对应的类型即可。

<environments default="mysql">

environment标签

用来设置某个具体的数据库环境,id属性是唯一标识

properties标签

用来引入外部的配置文件,
1.这里创建了一个jdbc,.properties用来存储数据库的连接信息。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=root

2.在mybatis的核心配置文件使用properties标签来引入配置文件

<properties resource="jdbc.properties"></properties>

3.可以以${}的形式直接引入使用了

<property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>

settings标签

可以通过settings标签来设置mybatis的一些运行时的行为方式,有name和valus两个值,name属性用来选择行为,value属性用来设置参数,这里以mapUnderscoreToCamelCase为例,设置了mapUnderscoreToCamelCase为true以后会将下划线的命名方式改为驼峰命名法。在数据库中创建的字段名为user_name,而在对应的bean中设置的属性名为userName,不设置的话不能正产赋值,设置了以后就可以正常自动赋值了。

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

在这里插入图片描述
附:解决不能自动赋值的问题还可以在sql语句中给查询出来的结果起一个别名,这样也能正常赋值。

 select uid,user_name userName,password,age,sex  from user where uid = #{id}

typeAliases标签

可以给java类型起一个别名,例如我们觉着com.glq.bean.User这个名太长,我们可以通过这个标签来设定一个短的别名,其他地方直接使用这个别名即可。这里有typeAlias和package两个子标签,其中typeAlias可以设置一个指定的而package是给整个包下的类都起别名,默认的别名名称为类名。要注意的是这里的别名都不区分大小写。

    <typeAliases>
        <!--<typeAlias type="com.glq.bean.User" alias="user"></typeAlias>-->
        <package name="com.glq.bean" ></package>
    </typeAliases>

注意顺序

mybatis中的标签有先后顺序,不能错了顺序
properties,
settings,
typeAliases,
typeHandlers,
objectFactory,
objectWrapperFactory,
reflectorFactory,
plugins,
environments,
databaseIdProvider,
mappers

映射文件

单表的增删改查

1.首先创建一个类,用来映射操作数据库的数据

	private Integer eid;
	
	private String ename;
	
	private Integer age;
	
	private String sex;
	
	private Dept dept;

Dept类(下面的多对一、一对多用)


	private Integer did;
	
	private String dname;
	
	private List<Emp> emps;

2.创建映射的接口EmpMapper,其中有这几个抽象方法。

    //添加
    public void addEmp(Emp emp);

    //删除
    public void deleteEmp(String id);

    //修改
    public Integer updateEmp(Emp emp);

    //查找一个Emp
    public  Emp selectEmpById(String id);

    //查找所有的Emp
    public List<Emp> selectAllEmpList();

    //查找某一个Emp返回Map
    public Map<String,Object> selectEmpByIdMap(String id);

    //查找返回Map集合
    @MapKey("eid")
    public Map<String,Object> selectAllEmpMap();

3.创建映射文件EmpMapper.xml

添加数据

实现添加数据的方法,只需要用到insert标签,这里还设置了useGeneratedKeys和keyProperty两个属性,用来获取自增的主键。

    <insert id="addEmp" useGeneratedKeys="true" keyProperty="eid">
        insert into emp values(null,#{ename},#{age},#{sex},NULL )
    </insert>

删除数据

删除方法直接使用delete标签

    <delete id="deleteEmp">
        delete from emp where eid = #{eid}
    </delete>

修改数据

修改数据需要用到update标签

    <update id="updateEmp">
        update emp set ename = #{ename},age = #{age},sex = #{sex} where eid = #{eid}
    </update>

查询数据

查询数据用到的是select标签,这里按照查询结果分为几种情况讨论

返回bean对象

当查询返回的结果是一个bean对象的时候,此时的resultType应该设置为bean相对应的类的全限定名

    <select id="selectEmpById" resultType="Emp">
        select * from emp where eid = #{eid}
    </select>

当返回结果是一个List的时候,返回的对象应该是List<Emp,mybaties会自动解析成list类型的,所以resultType属性需要填bena对应类的全限定名

返回一个List
    <select id="selectAllEmpList" resultType="Emp">
        select * from emp
    </select>
返回一条记录的Map

因为返回的数据直接放到一个map中,以属性名为键,以 查询出来的结果为值,所以resultType属性需要填写Map的全限定名

    <select id="selectEmpByIdMap" resultType="java.util.Map">
        select * from emp where eid = #{eid}
    </select>
返回多条记录的Map

当返回的数据是多条并且想把返回的数据放到map中时,需要在接口中指定谁来充当键,这里用到的是@MapKey注解,下面的例子中标志使用eid字段的数据当做键。此时resultType应该写映射的bean的类的全限定名

    @MapKey("eid")
    public Map<String,Object> selectAllEmpMap();
    <select id="selectAllEmpMap" resultType="Emp">
        select * from emp
    </select>

通过package管理映射文件

在mybaties核心配置文件中科院使用mappers标签类管理映射文件,可以使用resource来管理一个映射文件,也可以使用package来管理一个包下的所有映射文件,这里可以在conf下创建一个与接口所在的包同名的包。

    <mappers>
        <!--<mapper resource="EmpMapper.xml"></mapper>-->
        <package name="com.glq.mapper"></package>
    </mappers>

${}与#{}

mybatis中可以使用#{}和$ {}两种方式来获取参数,使用#{}的时候是使用占位符,使用 的 时 候 是 使 用 字 符 串 拼 接 的 方 式 , 所 以 使 用 {}的时候是使用字符串拼接的方式,所以使用 使使${}的时候若填充的数据是字符串类型的时候要加单引号

参数是一个bean

    <!--//参数是一个bean-->
    <!--void insertEmp(Emp emp);-->
    <!--使用#{}和${}{}中都可以填入属性名,mybaties会自动映射,只是字符串类型的时候使用${}要注意加上‘’,因为${}不会自动加单引号,#{}会自动加-->
    <!--insert into emp values(null,#{ename},#{age},#{sex},null)-->
    <insert id="insertEmp">
        insert into emp values(null,'${ename}',${age},'${sex}',NULL )
    </insert>

参数是一个String

    <!--//参数是一个String-->
    <!--Emp getEmpById(String eid);-->
    <!--当参数只有一个值的时候#{}可以使用任何值,而${}只能填入value或者_parameter-->
    <!--select * from emp where eid = #{eidwerferew}-->
    <select id="getEmpById" resultType="emp">
        select * from emp where eid = ${_parameter}
    </select>

参数是两个String

    <!--//参数是两个String-->
    <!--Emp getEmpByEidAndEname(String eid,String ename);-->
    <!--都可以使用param1 param2....  #{}还可以使用0 1 ..-->
    <!--select * from emp where eid = #{0} and ename = #{1}-->
    <select id="getEmpByEidAndEname" resultType="emp">
        select * from emp where eid = ${param1} and ename = '${param2}'
    </select>

参数是一个Map

    <!--//参数是一个Map-->
    <!--Emp getEmpByMap(Map<String,Object> map);-->
    <!--都可以通过Map中的键来获取-->
    <!--select * from emp where eid = #{eid} and ename = #{ename}-->
    <select id="getEmpByMap" resultType="emp">
        select * from emp where eid = ${eid} and ename = '${ename}'
    </select>

参数是一个List

当参数是List或者是数组的时候,mybaties会将List或者数组放进map中,List以list为键,Array以array为键。

命名参数

可以在接口中通过@Param注解来起一个名字,这个名字会封装进Map,在mybatis中就可以通过设置的名字来填充参数了。

    Emp getEmpByEidAndEnameByParam(@Param("eid") String eid, @Param("ename") String ename);
    <!--//命名参数-->
    <!--Emp getEmpByEidAndEnameByParam(@Param("eid") String eid, @Param("ename") String ename);-->

    <!--可以通过设置的名称来获取-->
    <!--select * from emp where eid = ${eid} and ename = '${ename}'-->
    <select id="getEmpByEidAndEnameByParam" resultType="emp">
        select * from emp where eid = #{eid} and ename = #{ename}
    </select>

多对一映射

需要使用连接查询来获得

    <!--//    获取所有的员工信息-->
    <!--public List<Emp> getAllEmp();-->
    <select id="getAllEmp" resultMap="empVSdept">
        select e.eid,e.ename,e.age,e.sex,e.did,d.dname from emp e left join dept d on e.did = d.did
    </select>

但是获取到的数据不能够自动填充Emp中的dept属性,这里需要来设定映射关系
方法一:
使用级联的方式。其中id标签用来设置主键 result标签用来设置非主键。column属性表示数据表的哪一列,property表示实体类中的哪一个属性

    <!-- <resultMap type="Emp" id="empMap">
        <id column="eid" property="eid"/>
        <result column="ename" property="ename"/>
        <result column="age" property="age"/>
        <result column="sex" property="sex"/>
        <result column="did" property="dept.did"/>
        <result column="dname" property="dept.dname"/>
    </resultMap> -->

方式二:
使用association 标签来映射。property属性表示要映射的属性,javaType属性表示该属性对应的java类型

    <resultMap id="empVSdept" type="Emp">
        <id column="eid" property="eid"></id>
        <result column="ename" property="ename"></result>
        <result column="age" property="age"/>
        <result column="sex" property="sex"/>
        <association property="dept" javaType="Dept">
            <id column="did" property="did"/>
            <result column="dname" property="dname"/>
        </association>
    </resultMap>

多对一映射分步加载、

分步查询顾名思义就是一步一步的查询,首先根据eid查询出did,再根据did查询dname。
在association 标签中使用select属性来指定下一步查询的映射,然后使用column属性表示下一步查询需要传入的参数,当参数不止一个的时候可以使用map的方式来传值。

    <!--Dept getDeptByDid(String did);-->
    <select id="getDeptByDid" resultType="Dept">
        select did,dname from dept where did = #{did}
    </select>
    <resultMap id="empVSdeptStept" type="Emp">
        <id column="eid" property="eid"></id>
        <result column="ename" property="ename"></result>
        <result column="age" property="age"/>
        <result column="sex" property="sex"/>
        <association property="dept" select="com.glq.mapper.DeptMapper.getDeptByDid" column="{did = did}" fetchType="lazy"></association>
    </resultMap>
    <!--//根据eid查询一个员工信息-->
    <!--Emp getEmpByEid(String eid);-->
    <select id="getEmpByEid" resultMap="empVSdeptStept">
        select eid,ename,age,sex,did from emp where eid = #{eid}
    </select>

一对多映射

与多对一查询类似,只不过这里不是用association 标签,而是使用collection标签(因为有多条结果),然后使用ofType属性来表示操作的属性的java类型(即是类的全限定名)

    <!--public List<Dept> getAllDept();-->
    <resultMap id="DeptVSEmpMapper" type="Dept">
        <id column="did" property="did"/>
        <result column="dname" property="dname"/>
        <collection property="emps" ofType="Emp">
            <id column="eid" property="eid"/>
            <result column="ename" property="ename"/>
            <result column="age" property="age"/>
            <result column="sex" property="sex"/>
        </collection>
    </resultMap>

    <select id="getAllDept" resultMap="DeptVSEmpMapper">
        select d.did,d.dname,e.eid,e.ename,e.age,e.sex from dept d left join emp e on d.did = e.eid
    </select>

一对多映射分步加载

与多对一类似,只需要改成collection标签就行。

    <resultMap id="DeptVSEmpMapperDept" type="Dept">
        <id column="did" property="did"/>
        <result column="dname" property="dname"/>
        <collection property="emps" select="com.glq.mapper.DeptVSEmpMapper.getEmpsByEid" column="did" fetchType="lazy"></collection>
    </resultMap>

    <select id="getDeptById" resultMap="DeptVSEmpMapperDept">
        	select did,dname from dept where did = #{did}
    </select>

延迟加载

只需要在mybaties的核心配置文件中配置以下即可。

    <settings>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"></setting>
        <!--是否查询所有数据-->
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>

还可以在collection或者association 标签中使用fetchType属性来指定当前这个映射关系是否使用延迟加载。例如全局设置了延迟加载,可以通过设置fetchType="eager"来指定该映射不使用;或者全局设置了不延迟加载,可以通过设置fetchType="lazy"来实现该映射实现延迟加载。



今天的内容到此结束,谢谢大家的观看,如有错误请指正,谢谢!CSDN记录成长!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值