码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis_插入数据

时间:2018-05-02 18:09:50      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:void   XML   oid   end   person   提交   tac   数据   public   

插入一条数据

<insert id = "insert" parameterType="xxx.x.Person">
        insert into person (person_id, gender, person_addr, birthday)
        values(#{personId},#{name},#{gender},#{personAddr},#{birthday})
    </insert>

java语句

SqlSessionFactory sessionFactory;
    public void setUp() throws Exception {
        InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
        sessionFactory = new SqlSessionFactoryBuilder().build(in);
    }
    public void insert() {
        //创建SqlSession
        SqlSession session = sessionFactory.openSession();
        try {
            Person p = new Person();
            p.setName("李四");
            p.setGender(1);
            p.setAddress("上海");
            p.setBirthday(new Date());
            int count = session.insert("xxx.x.mapper.PersonTestMapper.insert",p); //此处有一个返回值,是影响的行数
            session.commit(); //数据库的变更(增删改)都要提交事务
            System.out.println(count);
        }catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
        
    }

 

返回主键插入:

<!--
        selectKey:是做主键返回的
        keyProperty:接收返回主键的属性
        order:insert语句和生成主键的sql的执行顺序mysql是AFTER,oracle是BEFORE
        resultType:返回主键的数据类型
        生成主键的sql select LAST_INSERT_ID()
    -->        
        <selectKey keyProperty="personId" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into person (person_id, gender, person_addr, birthday)
        values(#{personId},#{name},#{gender},#{personAddr},#{birthday})
    </insert>

 

Mybatis_插入数据

标签:void   XML   oid   end   person   提交   tac   数据   public   

原文地址:https://www.cnblogs.com/lonske/p/8981547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!