------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
实体类
public class Book { private Integer bookID; private String bookName; private String bookAuthor; private Integer bookPrice; public Book() { } public Integer getBookID() { return this.bookID; } public void setBookID(Integer bookID) { this.bookID = bookID; } public String getBookName() { return this.bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getBookAuthor() { return this.bookAuthor; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } public Integer getBookPrice() { return this.bookPrice; } public void setBookPrice(Integer bookPrice) { this.bookPrice = bookPrice; } }
接口中的方法
//添加 public int insertBook(Book book);
小配置中
<!--返回主键列--> <insert id="insertBook"> INSERT INTO book(bookname,bookauthor,bookprice) VALUES (#{bookName},#{bookAuthor},#{bookPrice}) <selectKey resultType="int" keyProperty="bookID"> SELECT @@IDENTITY </selectKey> </insert>
测试类
///添加后返回主键列的测试方法 //加使用mybatis工具类 @Test public void t2Insert(){ SqlSession session= MyBatisUtils.getSession(); Book book=new Book(); book.setBookName("心想事成"); book.setBookAuthor("孟七"); book.setBookPrice(999); IBookDAO mapper = session.getMapper(IBookDAO.class); int i = mapper.insertBook(book); session.commit(); System.out.println("受影响的行数"+i); System.out.println("返回的主键列的id=============="+book.getBookID()); session.close(); }
它可以把id通过调用这个insertBook的方法,把id注入到传进去的这个对象里,因为他是引用类型