MyBatis框架中元素解析

MyBatis框架中元素解析

1. MyBatis的核心配置文件
1.1 名称-:我们可以自己定义,推荐大家使用 (mybatis-config.xml)
1.2 位置:IntelliJ IDEA中通过Maven创建项目,一般都保存在src/main/resources目录下。
1.3 文件中的配置元素及其属性

<?xml version="1.0" encoding="UTF-8"?>
上面表示xml文件的文件头,说明MyBatis的核心配置文件是一个xml文件。

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
 上面是引入MyBatis配置文件的格式。原本在xml文件中出现的标记,我们可以自己定义,但是引入这个MyBatis配置文件的格式之后,我们就不能在xml文件中自己定义标记了,只能使用MyBatis配置文件的格式提供默认的一组标记。
 
<configuration></configuration>
上面是MyBatis配置文件的格式提供的MyBatis核心配置文件的根元素。

	<!-- 配置引入数据库链接字符串的资源文件 -->
    <properties resource="mydata.properties"></properties>
    
    <typeAliases>
        <typeAlias type="com.qing.bean.StudentBean"></typeAlias>
    </typeAliases>
    上面是配置默认别名,直接在SQL映射文件使用默认别名,不区分大小写
    
	 <!-- 配置mybatis默认的连接数据库的环境 -->
    <environments default="development">
        <environment id="development">
        	<!-- 配置事务管理器 -->
            <transactionManager type="JDBC"></transactionManager>
            上面指明数据库连接环境的事务管理器。它有一个type属性,这个属性的取值就决定了事务管理由谁去操作。
            JDBC这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
            
             <!-- 配置数据源 -->
            <dataSource type="POOLED">
            POOLED这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这是一种		使得并发 Web 应用快速响应请求的流行处理方式。
            
                <property name="driver" value="${mydriver}"></property>
                <property name="url" value="${myurl}"></property>
                <property name="username" value="${myusername}"></property>
                <property name="password" value="${mypassword}"></property>
                上面指明数据库连接环境的数据源配置 (数据库驱动、URL、用户名、密码)
            </dataSource>
        </environment>
    </environments>
     <!--注册数据访问接口-->
    <mappers>
        <mapper resource="StudentMapper.xml"></mapper>
    </mappers>
    上面配置数据访问接口对应的sql映射文件路径/地址的。
</configuration>

2.Sql映射文件 (Mapper文件)
2.1 名称: (与数据访问接口名称一样,后缀名”.xml”)
2.2 位置:与核心配置文件同在src/main/resources下
核心配置文件:
2.3 在src/main/resources下的子文件夹中
核心配置文件:
2.4 在src/main/resources下通过修改工程结构创建的包中 (更新项目)
核心配置文件:



2.5 不在工程中,而是在指定的目录下
核心配置文件:

2.6 文件中的配置元素及其属性

<?xml version="1.0" encoding="UTF-8"?>
上面表示xml文件的文件头,说明MyBatis的核心配置文件是一个xml文件。

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
上面引入SQL映射文件的格式。原本在xml文件中出现的标记,我们可以自己定义,但是引入这个SQL映射文件的格式之后,我们就不能在xml文件中自己定义标记了,只能使用SQL映射文件的格式提供默认的一组标记。

<mapper namespace="com.qing.mapper.StudentMapper">
上面是sql映射文件的根元素,它有一个namespace属性,这个属性是用来设置数据访问接口的包名+接口名。

    <insert id="insertStud" parameterType="StudentBean">
        insert into tb_student values (null,#{stuname},#{stupassword},#{stuage},#{stuaddress});
    </insert>
     	</insert>----配置插入数据用的sql语句
		id---数据访问接口中添加数据方法的方法名称
		parameterType----数据访问接口中添加数据方法的参数类型


    <update id="updeteStud" parameterType="StudentBean">
        update tb_student set stuname=#{stuname},stupassword=#{stupassword},stuage=#{stuage},
        stuaddress=#{stuaddress} where stuid=#{stuid};
    </update>
    	</update>----配置修改数据用的sql语句
		id---数据访问接口中修改数据方法的方法名称
		parameterType----数据访问接口中修改数据方法的参数类型


    <delete id="deleteStud" parameterType="int">
        delete from tb_student where stuid=#{stuid};
    </delete>
   	 	</delete>---配置删除数据用的sql语句
		id---数据访问接口中删除数据方法的方法名称
		parameterType----数据访问接口中删除数据方法的参数类型


    <select id="selectStudId" resultType="StudentBean" >
        select * from tb_student where stuid=#{stuid};
    </select>
    	</select>----配置查询数据用的sql语句
		id---数据访问接口中查询数据方法的方法名称
		parameterType----数据访问接口中查询数据方法的参数类型


    <select id="selectStud" resultType="StudentBean">
        select * from tb_student;
    </select>
</mapper>


如果数据库表字段和java实例类成员变量不一致时,需要配置resultMap,具体配置如下:
resultMap---配置查询的结果类型的元素 (数据库表中的列名称与实体类中的成员变量的名称不同)
resultType--配置查询的结果类型。(数据库表中的列名称与实体类中的成员变量的名称相同)
 <resultMap id="studentMap" type="com.qing.bean.StudentBean">
        <id column="stu_id" property="stuid"></id>
        <result column="stu_name" property="stuname"></result>
        <result column="stu_password" property="stupassword"></result>
        <result column="stu_age" property="stuage"></result>
        <result column="stu_address" property="stuaddress"></result>
  </resultMap>
	id属性---查询的结果类型的名称,实际上就是select元素中resultMap的属性值
	type属性---查询的结果的具体类型【java实体类的类名】
	resultMap元素中目前有2类子元素
	<id>---配置主键列映射
	<result>---配置非主键列映射
	column属性----数据库表的列名
	property属性---java实体类成员变量的名称。

3. MyBatis的核心配置文件中的typeAliases元素
typeAliases元素—出现在MyBatis的核心配置文件中,给SQL映射文件的数据类型设置别名用的。SQL映射文件的数据类型,insert 元素的参数类型,resultMap元素的types属性等这些地方都需要数据类型。如果我们不设置typeAliases元素,那么SQL映射文件的数据类型就得是包名+类名。

1.一个类一个别名 (默认别名)
MyBatis的核心配置文件
<typeAliases>
    <!--默认的别名 [类名 不区分大小写]-->
    <typeAlias type="com.qing.bean.StudentBean"></typeAlias>
</typeAliases>

Sql映射文件
<insert id="insertStud" parameterType="StudentBean">
        insert into tb_student values (null,#{stuname},#{stupassword},#{stuage},#{stuaddress});
    </insert>
    
    <update id="updeteStud" parameterType="StudentBean">
        update tb_student set stuname=#{stuname},stupassword=#{stupassword},stuage=#{stuage},
        stuaddress=#{stuaddress} where stuid=#{stuid};
    </update>
    
2.一个类一个别名 (指定别名)
<typeAliases>
    <typeAlias alias="studentBean" type="com.qing.bean.StudentBean"></typeAlias>
</typeAliases>

Sql映射文件
<resultMap id="studentMap" type="StudentBean">
        <id column="stu_id" property="stuid"></id>
        <result column="stu_name" property="stuname"></result>
        <result column="stu_password" property="stupassword"></result>
        <result column="stu_age" property="stuage"></result>
        <result column="stu_address" property="stuaddress"></result>
  </resultMap>
  
  <select id="selectStudId" parameterType="int" resultMap="studentMap" >
        select * from tb_student where stuid=#{stuid};
    </select>

3.指定包下的所有类自动生成别名 (类名,不区分大小写)
<typeAliases>
    <!--指定包下的所有类自动生成别名 (类名,不区分大小写)-->
    <package name="com.qing.bean"/>
</typeAliases>

SQL映射文件
<insert id="insertStud" parameterType="StudentBean">
        insert into tb_student values (null,#{stuname},#{stupassword},#{stuage},#{stuaddress});
    </insert>

    <update id="updeteStud" parameterType="StudentBean">
        update tb_student set stuname=#{stuname},stupassword=#{stupassword},stuage=#{stuage},
        stuaddress=#{stuaddress} where stuid=#{stuid};
    </update>

4. Sql映射文件中的select元素resultType与 resultMap属性的区别 (输出数据就是返回值)
resultType和resultMap都是查询语句执行之后的返回结果的类型表示属性会在sql映射文件中select元素中使用resultType表示的执行完数据库操作之后,返回的结果数据类型。这个结果可以用三种类型数据来处理:简单类型(包含String、封装类)、对象型、HashMap型。
4.1 数据库表中的列名称与实体类中的成员变量的名称相同时,一般设置resultType指定返回的结果数据类型。
数据库表结构:

create table tb_student(
stuid int primary key auto_increment,
stuname varchar(30),
stupassword varchar(20),
stuage int,
stuaddress varchar(30)
);

java实体类:

package com.qing.bean;

public class StudentBean {
    private int stuid;
    private String stuname;
    private String stupassword;
    private int stuage;
    private String stuaddress;

    public int getStuid() {
        return stuid;
    }

    public void setStuid(int stuid) {
        this.stuid = stuid;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public String getStupassword() {
        return stupassword;
    }

    public void setStupassword(String stupassword) {
        this.stupassword = stupassword;
    }

    public int getStuage() {
        return stuage;
    }

    public void setStuage(int stuage) {
        this.stuage = stuage;
    }

    public String getStuaddress() {
        return stuaddress;
    }

    public void setStuaddress(String stuaddress) {
        this.stuaddress = stuaddress;
    }
}

SQL映射文件:

<?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.qing.mapper.StudentMapper">

    <insert id="insertStud" parameterType="StudentBean">
        insert into tb_student values (null,#{stuname},#{stupassword},#{stuage},#{stuaddress});
    </insert>

    <update id="updeteStud" parameterType="StudentBean">
        update tb_student set stuname=#{stuname},stupassword=#{stupassword},stuage=#{stuage},
        stuaddress=#{stuaddress} where stuid=#{stuid};
    </update>

    <delete id="deleteStud" parameterType="int">
        delete from tb_student where stuid=#{stuid};
    </delete>

    <select id="selectStudId" resultType="StudentBean" >
        select * from tb_student where stuid=#{stuid};
    </select>

    <select id="selectStud" resultType="StudentBean">
        select * from tb_student;
    </select>
</mapper>

测试类:

package com.qing.test;
import com.qing.bean.StudentBean;
import com.qing.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.util.List;
public class TestMain {
    /**
     * 添加用户信息
     */
    public static void insertStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentBean studentBean = new StudentBean();
            studentBean.setStuname("寒冬");
            studentBean.setStupassword("1212");
            studentBean.setStuage(12);
            studentBean.setStuaddress("西安");
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            boolean flag = studentMapper.insertStud(studentBean);
            if (flag == true) {
                System.out.println("添加成功!!!!!!");
            } else {
                System.out.println("添加失败!!");
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据id修改用户信息
     */
    public static void updateStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentBean studentBean = new StudentBean();
            studentBean.setStuid(14);
            studentBean.setStuname("张三");
            studentBean.setStupassword("111222");
            studentBean.setStuage(121);
            studentBean.setStuaddress("北京");
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            boolean flag = studentMapper.updeteStud(studentBean);
            if (flag == true) {
                System.out.println("修改成功!!!!!");
            } else {
                System.out.println("修改失败!!");
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据id删除用户信息
     */
    public static void delectStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            boolean flag = studentMapper.deleteStud(13);
            if (flag == true) {
                System.out.println("删除成功!!!!!!!");
            } else {
                System.out.println("删除失败----");
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据id查询用户信息
     */
    public static void selectStudentId() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            StudentBean studentBean = studentMapper.selectStudId(8);
            System.out.println(studentBean.getStuid() + "\t" + studentBean.getStuname() + "\t" + studentBean.getStupassword() + "\t" +
                    studentBean.getStuage() + "\t" + studentBean.getStuaddress());
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 查询所有用户信息
     */
    public static void selectStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<StudentBean> stulist = studentMapper.selectStud();
            for (StudentBean stu : stulist) {
                System.out.println(stu.getStuid() + "\t" + stu.getStuname() + "\t" + stu.getStupassword() + "\t" + stu.getStuage() + "\t" + stu.getStuaddress());
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 测试增删改查方法
     *
     * @param args
     */
    public static void main(String[] args) {
        //insertStudent();
        //updateStudent();
        //delectStudent();
        //selectStudentId();
        selectStudent();
    }
}

4.2 ressultMap表示的执行完数据库操作之后,返回的结果数据类型。
resultMap是mybatis中最重要最强大的元素,使用resultmap可以解决JavaBean的属性名和表字段名不一致的问题。

数据库表结构:
create table tb_student(
stuid int primary key auto_increment,
stuname varchar(30),
stupassword varchar(20),
stuage int,
stuaddress varchar(30)
);

java实体类:

package com.qing.bean;
public class StudentBean {
    private int stu_id;
    private String stu_name;
    private String stu_password;
    private int stu_age;
    private String stu_address;

    public int getStu_id() {
        return stu_id;
    }

    public void setStu_id(int stu_id) {
        this.stu_id = stu_id;
    }

    public String getStu_name() {
        return stu_name;
    }

    public void setStu_name(String stu_name) {
        this.stu_name = stu_name;
    }

    public String getStu_password() {
        return stu_password;
    }

    public void setStu_password(String stu_password) {
        this.stu_password = stu_password;
    }

    public int getStu_age() {
        return stu_age;
    }

    public void setStu_age(int stu_age) {
        this.stu_age = stu_age;
    }

    public String getStu_address() {
        return stu_address;
    }

    public void setStu_address(String stu_address) {
        this.stu_address = stu_address;
    }
}

SQL映射文件:

<?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.qing.mapper.StudentMapper">
    <insert id="insertStud"  parameterType="StudentBean">
        insert into tb_student values(null,#{stu_name},#{stu_password},#{stu_age},#{stu_address});
    </insert>

    <update id="updateStud" parameterType="StudentBean">
        update tb_student set stuname=#{stu_name},stupassword=#{stu_password},stuage=#{stu_age},stuaddress=#{stu_address} where stuid=#{stu_id};
    </update>

    <delete id="deleteStud" parameterType="int">
        delete from tb_student where stuid=#{stu_id};
    </delete>

    <resultMap id="studMap" type="com.qing.bean.StudentBean">
        <id column="stuid" property="stu_id"></id>
        <result column="stuname" property="stu_name"></result>
        <result column="stupassword" property="stu_password"></result>
        <result column="stuage" property="stu_age"></result>
        <result column="stuaddress" property="stu_address"></result>
    </resultMap>
    <select id="selectStudId" parameterType="int" resultMap="studMap">
        select * from tb_student where stuid=#{stuid};
    </select>

    <select id="selectStud" parameterType="StudentBean" resultMap="studMap">
        select * from tb_student;
    </select>
</mapper>

测试类:

package com.qing.test;
import com.qing.bean.StudentBean;
import com.qing.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.util.List;
public class TestMain {
    /**
     * 添加用户信息
     */
    public static void insertStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentBean studentBean = new StudentBean();
            studentBean.setStu_name("蓝鲸");
            studentBean.setStu_password("111");
            studentBean.setStu_age(1);
            studentBean.setStu_address("大海");
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            studentMapper.insertStud(studentBean);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据id修改用户信息
     */
    public static void updateStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentBean studentBean = new StudentBean();
            studentBean.setStu_id(7);
            studentBean.setStu_name("雄鹰");
            studentBean.setStu_password("11111");
            studentBean.setStu_age(2);
            studentBean.setStu_address("天空");
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            boolean flag = studentMapper.updateStud(studentBean);
            if (flag == true) {
                System.out.println("修改成功!!!!!!!!");
            } else {
                System.out.println("修改失败");
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据id删除用户信息
     */
    public static void deleteStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            boolean flag = studentMapper.deleteStud(8);
            if (flag == true) {
                System.out.println("删除成功!!!!!!!!");
            } else {
                System.out.println("删除失败");
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 根据id查询用户信息
     */
    public static void selectStudentId() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            StudentBean stu = studentMapper.selectStudId(6);
            System.out.println(stu.getStu_id() + "\t" + stu.getStu_name() + "\t" + stu.getStu_address());
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 查询所有用户信息
     */
    public static void selectStudent() {
        SqlSession sqlSession = null;
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<StudentBean> stulist = studentMapper.selectStud();
            for (StudentBean stu : stulist) {
                System.out.println(stu.getStu_id() + "\t" + stu.getStu_name() + "\t" + stu.getStu_address());
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 测试增删改查方法
     *
     * @param args
     */
    public static void main(String[] args) {
        //insertStudent();
        //updateStudent();
        //deleteStudent();
        //selectStudentId();
        selectStudent();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值