MyBatis添加数据

传递 pojo 包装对象

开发中通过 pojo 传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查 询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。 Pojo 类中包含 pojo。 需求:根据用户名查询用户信息,查询条件放到 QueryVo 的 user 属性中。

在这里插入图片描述

当parameterType的类型为对象 的时候name的值不能随便命名,必须与实体类的属性名相同

在这里插入图片描述
在这里插入图片描述

获取主键自增后的ID属性

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

test类

 @Test
    public void InsertEmployee() {
        String resource = "mybatis-config.xml";//配置文件名
        Reader reader = null; //读取配置文件的工具
        SqlSession session = null;
        try {
            //使用MyBatis提供的Resources类加载mybatis的配置文件
            reader = Resources.getResourceAsReader(resource);
            //构建sqlSession的工厂
            SqlSessionFactory sessionFactory =
                    new SqlSessionFactoryBuilder().build(reader);
            //创建能执行映射文件中sql的sqlSession
            session = sessionFactory.openSession();
            //创建实体对象,将它insert到数据库中
            Employee e = new Employee();
            e.setName("张三");
            e.setBirthday(new Date());
            e.setDept(2);
            e.setSalary(9809F);
            session.insert("EMPLOYEE.insertEmployee",e );
            session.commit();//增删改要提交事务
            //insert标签中设置keyProperty和useGeneratedKeys后才能看到值,否则是null
            System.out.println(e .getId());
        } catch (Exception ex) {
            ex.printStackTrace();
            session.rollback();//有异常事务回滚
        } finally {//关闭资源
            if (session != null) {
                session.close();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

实体类

public class Employee {
    private Integer id;
    private String name;
    private Date birthday;
    private Integer dept;
    private Float salary;
    //getter/setter方法略
    }

EmployeeMapper

<!--映射文件-->
<mapper namespace="EMPLOYEE">
    <insert id="insertEmployee" parameterType="pojo.Employee" keyProperty="id" useGeneratedKeys="true">
    insert into Employee(name,birthday,dept,salary) values(#{name},#{birthday},#{dept},#{salary})
  </insert>
</mapper>

配置文件里添加

   <mapper resource="dao/mapper/EmployeeMapper.xml"/>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值