MyBatis第三种方式,xml和接口的结合,以及如何获得插入数据的返回参数、传入空的参数

来源:互联网 发布:淘宝网上开店要钱吗 编辑:程序博客网 时间:2024/05/22 07:08

DeptMapper.xml

<!-- 第三种:命名空间映射到接口 --><mapper namespace="com.oracle.dao.DeptDao">        <!-- id是查询语句的唯一标识   resultType是返回类型(封装成Dept对象)  parameterType是传递参数的类型 --><select id="getAll" parameterType="int" resultType="com.oracle.vo.Dept">select * from dept where deptno =#{value}</select></mapper>

DeptDao.java-------com.oracle.dao

取消了@注解的方式

package com.oracle.dao;import java.util.List;import org.apache.ibatis.annotations.Insert;import com.oracle.vo.Dept;public interface DeptDao {        public void getAll(int no);}
Configuration.xml

<mappers>         <!-- 在核心配置文件中加载第四步编写的映射文件DeptMapper.xml -->         <mapper resource="com/oracle/vo/DeptMapper.xml" />         <!-- <package name="com/oracle/dao"/> --></mappers>
测试函数test3.java

import org.apache.ibatis.session.SqlSession;import com.oracle.dao.DeptDao;import com.oracle.dao.SessionFactory;import com.oracle.vo.Dept;public class test3 {public static void main(String[] args) {SessionFactory sf = new SessionFactory();SqlSession session = sf.getSession();DeptDao deptDao = session.getMapper(DeptDao.class);deptDao.getAll(6);//在SessionFactory.java中,如果openSession()中设置的不是true,//需要在这里手动提交,要不数据不能插入进数据库session.commit();session.close();}}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

其中需要返回新添加数据的部分参数的话,比如返回deptno

<insert id="in" parameterType="com.oracle.vo.dept">                <!-- selectKey这个标签在insert中使用,order是在insert语句执行before或after。接收的时候 对象.getDeptno()即可-->                <selectKey keyProperty="deptno" order="BEFORE" resultType="int">select sq_deptno.nextval from dept</selectKey>insert into ......</insert>

当传入的数据有空字段的时候,在sql语句中加入jdbcType=VARCHAR(数据类型)、NUMERIC

insert into dept values(#{deptno},#{dname,jdbcType=VARCHAR},#{loc})
这样dname可以传入空的参数

0 0
原创粉丝点击