Mybatis 实现Mysql数据库的操作

Mybatis 实现Mysql数据库的操作

  1. 环境搭建
    在这里插入图片描述

  2. Mybatis配置文件
    mybatisConfig.xml


```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.guifei.entity.Student" alias="Student"/>
        <!-- 指定包中的类都使用类名替代全限定名 -->
        <!--<package name="com.guifei.entity"/>-->
    </typeAliases>
    <!--如果项目还有其他开发环境则在这里添加-->
    <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:///0107"/>
                <property name="username" value="root"/>
                <property name="password" value="1111"/>
            </dataSource>

        </environment>

    </environments>
    <mappers>
        <!--添加映射文件-->
        <mapper resource="com/guifei/dao/impl/StudentDaoImplMapper.xml"/>
    </mappers>
</configuration>
  1. 数据操作接口
/**
 * 学生表数据操作接口
 */
public interface StudentDao {
    void insertStudent (Student student);
}
/**
 *接口实现类
 */

public class StudentDaoImpl implements StudentDao {
    @Override
    public void insertStudent (Student student) {
        //执行学生表插入学生的操作
        SqlSession sqlSession = null;
        try {
            //加载主配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatisConfig.xml");
            //创建sqlSeccionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //创建sqlSession,用于执行sql语句
            sqlSession = sqlSessionFactory.openSession();
            //执行sql语句
            sqlSession.insert("insertStudent", student);
            //手动提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            sqlSession.close();
        }
    }
}
  1. 映射文件
    StudentDaoImpMapping.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">
<!--namespace是命名空间-->
<mapper namespace="com.guifei.dao.impl.StudentDaoImpl">
    <!--id:执行数据库操作的方法的名字,parameterType:参数类型, 需要插入到student表中的是学生,添加Student的实体类全限定名 -->
    <!--<insert id="insertStudent" parameterType="com.guifei.entity.Student"></insert>-->
    
    <!--在mybatis配置文件配置别名后,这里直接使用实体类的类名,而不是上面的的全限定名-->
    <insert id="insertStudent" parameterType="Student">
        <!--需要执行的sql语句-->
        insert into student values (null, #{name}, #{gender}, #{age})
    </insert>
</mapper>
  1. 当有多张表对应多个实体类时,则在mybatis配置文件中直接配置,实体类所在的报名和映射文件所在的包名,mybatis扫描这些包,避免一个一个的配置麻烦。
<?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.guifei.entity.Student" alias="Student"/> -->
        <!-- 指定包中的类都使用类名替代全限定名 -->
        <package name="com.guifei.entity"/>
    </typeAliases>
    <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:///0107a"/>
                <property name="username" value="root"/>
                <property name="password" value="888"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!-- <mapper resource="com/guifei/dao/UserDao.xml"/>-->
        <!--当有多张表时,每张表都要配置mapper,可以直接将映射文件所在的包的配置,执行时会扫描包里面所有的映射文件-->
        <!--但是mybatis的规则是,配置包的时候,配置文件的文字必须与其对应的接口名字相同(大小写也要相同)-->
        <package name="com.guifei.dao"/>
    </mappers>
</configuration>

Mybatis 动态代理实现数据库的操作,只用编写接口实现类,通过动态代理生成接口的实现类,通过接口的全限定名+方法的id查找到唯一的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动态代理:
1、namespace必须是接口的全限定名
2、sql语句的id必须和接口中方法名一致-->
<mapper namespace="com.guifei.dao.GoodDao">
    <insert id="addGood" parameterType="Goods">
        insert into goods values (null, #{name}, #{price})
    </insert>
    <delete id="deleteGoodByID" parameterType="Goods">
        delete from goods where gid = #{id}
    </delete>


    <!--<select id="selectAllgoods" resultType="Goods">
        &lt;!&ndash;方法一:当出现表的列名与实体类的属性名不一致时可以将表的列名取别名,别名与实体类的属性名对象即可&ndash;&gt;
        select gid id, gname name, gprice price from goods
    </select>
    -->

    <select id="selectAllgoods" resultMap="goodsmapper">
        <!--方法二:当出现表的列名与实体类的属性名不一致时可以自定义一个映射规则,实现表与实体类的对应-->
        select gid id, gname name, gprice price from goods
    </select>
    <!--当表的列名与实体类的属性名不同时,编写他们之间的映射关系-->
    <resultMap id="goodsmapper" type="Goods">
        <!--主键比较特殊需要使用id标签,指定column(表的列名)property(实体类的属性名) -->
        <id column="gid" property="id"/>
        <!--其他属性使用result-->
        <result column="gname" property="name"/>
        <result column="gprice" property="price"/>
    </resultMap>

    <!--向数据表中插入一条商品数据,并获取其插入后的Id值-->
    <insert id="addGoodsAndGetId" parameterType="Goods">
        insert into goods values (null, #{name}, #{price})
        <!--keyProperty:查询的结果,给哪个属性赋值
            resultType:查询结果的类型
            order:不同的数据库自增主键产生的时间不同
            MySQL:先添加数据,后生成主键
            Oralce:先生成主键,再添加数据
            高版本的MyBatis框架,会自动识别当前数据库类型,自己选择,可以不写
         -->
        <selectKey resultType="int" keyProperty="id" order="AFTER">
            select @@identity
        </selectKey>
    </insert>


    <!--单参数查询,通过name查询商品-->
    <!--当单参数时,如果参数类型是基本数据类型或者String,占位符的名字可以任意-->
    <!--因为表的列名与实体类的属性名不相同,所以需要添加映射规则-->
    <select id="selectGoodsByname" resultMap="goodsmapper" parameterType="String">
        <!--通过字符串查询时需要使用模糊查询-->
        select * from goods where gname like '%' #{name} '%'
    </select>

    <!--通过名称和价格查询商品-->
    <select id="selectGoodsBynameAndprice" parameterType="Goods" resultMap="goodsmapper">
        select * from goods where gname like '%' #{name} '%' and gprice > #{price}
    </select>

    <!--通过名称和价格查询商品-->
    <select id="selectGoodsByobject" parameterType="Goods" resultMap="goodsmapper">
        select * from goods where gname like '%' #{goods.name} '%' and gprice > #{goods.price}
    </select>
    
</mapper>
  1. 一对一和一对多查询
<?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动态代理:
1、namespace必须是接口的全限定名
2、sql语句的id必须和接口中方法名一致-->
<mapper namespace="com.guifei.dao.TeacherDao">
    <!--一步查询:根据老师tesid查询老师所带班级所以有学生的所有成绩-->
    <select id="seletTeacherByteaid" resultMap="TeacherMapper">
        select * from teacher tea, studentclass sc,
        student stu, choose ch, course cou
        where tea.teaid = sc.teaid
        and sc.claid = stu.claid
        and stu.stuid = ch.stuid
        and cou.couid = ch.couid
        and tea.teaid = 1
    </select>
    <resultMap id="TeacherMapper" type="Teacher">
        <id column="teaid" property="teaid"/>
        <result column="teaname" property="teaname"/>
        <association property="studentClass" javaType="StudentClass">
            <id column="claid" property="claid"/>
            <result column="claname" property="claname"/>
            <collection property="studentList" ofType="Student">
                <id column="stuid" property="stuid"/>
                <result column="stuname" property="stuname"/>
                <result column="gender" property="gender"/>
                <collection property="courses" ofType="Course">
                    <id column="couid" property="couid"/>
                    <result column="couname" property="couname"/>
                    <result column="score" property="score"/>
                </collection>
            </collection>
        </association>
    </resultMap>

    <!--分步实现:根据老师tesid查询老师所带班级所以有学生的所有成绩-->
    <!--&#45;&#45;  第二种方式
    &#45;&#45; 第一步:通过教师teaid查出教师信息,将教师teaid作为参数传递  (映射教师表)
    select * from teacher where teaid=1
    &#45;&#45; 第二步:通过参数teaid将班级信息查出来,再将claid作为参数传递  (映射班级表)
    select * from studentclass where teaid=1

    &#45;&#45; 第三步:通过班级claid查出班级的学生,将stuid作为参数传递  (映射学生表)
    select * from student where claid= 2

    &#45;&#45; 第四步:通过学生stuid查出所有学生所修的课程 (映射课程表)
    select * from student stu, choose ch, course cou where stu.stuid=ch.stuid and cou.couid = ch.couid-->

    <select id="seletTeacherStepByStepByteaid" resultMap="TeacherStepMapper">
        select * from teacher where teaid= #{teaid}
    </select>
    <resultMap id="TeacherStepMapper" type="Teacher">
        <id column="teaid" property="teaid"/>
        <result column="teaname" property="teaname"/>
        <association property="studentClass" javaType="StudentClass" column="teaid" select="queryStudentClassByteaid"/>
    </resultMap>
    <select id="queryStudentClassByteaid" resultMap="queryStudentClass">
        select * from studentclass where teaid= #{teaid}
    </select>
    <resultMap id="queryStudentClass" type="StudentClass">
        <id column="claid" property="claid"/>
        <result column="claname" property="claname"/>
        <collection property="studentList" ofType="Student" column="claid" select="queryStudentSByclaid"/>
    </resultMap>
    <select id="queryStudentSByclaid" resultMap="querystudents">
        select * from student where claid=  #{claid}
    </select>
    <resultMap id="querystudents" type="Student">
        <id column="stuid" property="stuid"/>
        <result column="stuname" property="stuname"/>
        <result column="gender" property="gender"/>
        <collection property="courses" ofType="Course" column="stuid" select="queryCoursesBystuid"/>
    </resultMap>
    <select id="queryCoursesBystuid" resultMap="queryCourses">
        select * from student stu, choose ch, course cou where stu.stuid=ch.stuid and cou.couid = ch.couid and stu.stuid = #{stuid}
    </select>
    <resultMap id="queryCourses" type="Course">
        <id column="couid" property="couid"/>
        <result column="couname" property="couname"/>
        <result column="score" property="score"/>
    </resultMap>

    <!--分步实现:查询所有老师所带班级所以有学生的所有成绩-->
    <select id="seletAllTeacherStepByStepByteaid" resultMap="TeacherStepMapper">
        select * from teacher
    </select>
</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值