Mybatis獲取數據庫自增的主鍵值


在動態代理模式的xml文件中

<insert id="insertStu" parameterType="com.neuedu.bean.Student"
        useGeneratedKeys="true" keyProperty="sid">
        insert into stu1
        (sname,score,sclass) values(#{sname},#{score},#{sclass} )
    </insert>
useGeneratedKeys是代表是否使用數據庫自增的值,true表示是,false表示不是,默認是不使用的。
在useGeneratedKeys=true之后,一定要加上keyProperty,keyProperty是指定獲取數據庫自增的主鍵值賦值給哪個屬性。

測試:
@Test
    public void testInsertStu() {
        Student student = new Student(' ', "yr", "100", "1");
        try {
            SqlSessionFactory sqlSessionFactory = sqlSessionFactory();
            SqlSession openSession = sqlSessionFactory.openSession();
            Stu mapper = openSession.getMapper(Stu.class);
            mapper.insertStu(student);
            openSession.commit();
            openSession.close();
            // int sid = student.getSid();
            System.out.println(student);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

 


這樣在輸出的Student對象中就可以獲取自增的id值了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM