MyBatis insert 后返回数据

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/flashdream8/article/details/84359457

@ContextConfiguration("classpath*:applicationContext.xml")
public class TestTestInsert  extends AbstractJUnit4SpringContextTests{

	@Autowired
	private TestInsert testInsert;
	@Test
	public void testInsertIt(){
		TestUser tu = new TestUser();
		tu.setName("测试43");
		testInsert.insertIt2(tu);
		System.err.println("----------"+tu.getId());
		
	}
}
 

 

针对自增主键的表,在插入时不需要主键,而是在插入过程自动获取一个自增的主键,比如MySQL,可以采用如下两种配置方式:

 

<insert id="insertIt" parameterType="testUser" useGeneratedKeys="true" keyProperty="id">
		insert into test_insert (name) values (#{name})
</insert>

<insert id="insertIt3" parameterType="testUser">
		<selectKey keyProperty="id"  resultType="int" order="AFTER" >
			 SELECT LAST_INSERT_ID() AS id
		</selectKey>
		insert into test_insert (name) values (#{name})
</insert>

 

 

 

针对Sequence主键而言,在执行insert sql前必须指定一个主键值给要插入的记录,如Oracle、DB2,可以采用如下配置方式:

	<insert id="add" parameterType="vo.Category">
		<selectKey resultType="java.lang.Short" order="BEFORE"
			keyProperty="id">
			SELECT SEQ_TEST.NEXTVAL FROM DUAL
		</selectKey>
		insert into category (name_zh, parent_id,
		show_order, delete_status, description
		)
		values (#{nameZh,jdbcType=VARCHAR},
		#{parentId,jdbcType=SMALLINT},
		#{showOrder,jdbcType=SMALLINT},
		#{deleteStatus,jdbcType=BIT},
		#{description,jdbcType=VARCHAR}
		)
	</insert>

 

接口的写法:

 

 

 

 

 

public interface TestInsert {

	void insertIt(TestUser tu);
                // 这样写是不行的。不能用(@Param
	//void insertIt2(@Param(value="tu")TestUser tu);
}

 

 

 

Test

 

 

 

 

 

 

  @ContextConfiguration("classpath*:applicationContext.xml")

public class TestTestInsert  extends AbstractJUnit4SpringContextTests{

	@Autowired
	private TestInsert testInsert;
	@Test
	public void testInsertIt(){
		TestUser tu = new TestUser();
		tu.setName("测试43");
		testInsert.insertIt2(tu);
		System.err.println("----------"+tu.getId());
		
	}
}
 

 

 

 

展开阅读全文

没有更多推荐了,返回首页