首页 > 代码库 > mybatis高级(1)(入门回顾)

mybatis高级(1)(入门回顾)

首先入门案例(并且拿到新增记录当前id)

1.创建mybatis-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>
    <!-- 使用别名 -->
    <typeAliases>
        <!-- 为包下所有类使用别名,默认是简单类名 -->
        <package name="cn.cnsdhzzl.entity" />
        <!-- 对单个类,按类型名使用别名 -->
        <!-- <typeAlias type="cn.cnsdhzzl.entity.Student" alias="student" /> -->
    </typeAliases>

    <!-- 开发模式 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc的事务 -->
            <transactionManager type="JDBC" />
            <!-- 使用自带的连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
                <property name="username" value="bdqn" />
                <property name="password" value="bdqn" />
            </dataSource>
        </environment>
    </environments>

    <!-- 映射小配置 -->
    <mappers>
        <mapper resource="cn/cnsdhzzl/dao/StudentDAO.xml" />
    </mappers>
</configuration>

 

 

2.创建分层搭建架构

技术分享

 

3.创建StudentDAO.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="cn.cnsdhzzl.dao">
    <!-- 添加操作 -->
    <insert id="insertStudent" parameterType="student">
        insert into student(id,name,address,sex) values(seq_ssm.nextval,#{name},#{address},#{sex})
        <selectKey keyProperty="id" resultType="int">
            select seq_ssm.currval from dual
        </selectKey>
    </insert>
</mapper>

 

4.实现接口方法

@Override
    public Integer addStudent(Student stu) {
        SqlSession sqlSession = SessionUtil.getSqlSession();
        int result = sqlSession.insert("insertStudent", stu);

        sqlSession.commit();
        sqlSession.close();

        System.out.println("保存结果" + result);
        return result;
    }

 

5.测试

@Test
    public void frist() {
        Student stu = new Student("BBB", "北京", "男");
        StudentDaoImpl dao = new StudentDaoImpl();
        dao.addStudent(stu);
        System.out.println("成功");
    }

 结果图

技术分享

 

注意事项:

语句后面不能加‘;‘(分号),会报sql异常

 

mybatis高级(1)(入门回顾)