mybatis+sqlserver中返回非自增主键

首先把实体类贴出来(这里只贴出属性,其它的就是getter和setter方法):

public class Around {
     private String xccd;  //对应主键
     private String xcnm;
     private String stcd;
     private String sttp;
     private BigDecimal lnth;
     private String lead;
     private String mans;
     private String side;
     private Date sttm;
     private Date edtm;
     private String rmk;
     private String addvcd;

     //getter and setter  ....此处省略

}

数据库表(一定要在数据库表中配置好主键,对应实体类的属性xccd):

 1. Mysql,sqlserver数据库的主键是具有自增类型的,oracle没有,有的是序列。mybatis对于自增类型的主键新增或者修改返回比较容易实现:直接在mapper.xml文件中这样配置

<insert id="Savedata" parameterType="entity.Around"  useGeneratedKeys="true" keyProperty="xccd">  
          INSERT INTO Around(stcd,sttp,xcnm,sttm,lead,mans,addvcd) VALUES {#{stcd},#{sttp},#{xcnm},#{sttm},#{lead},#{mans},#{addvcd})
</insert>

其中keyProperty为主键的值赋值到实体类的对应属性。oracle的实现方法可以百度,这里不做赘述。

2. 对于非自增类型的配置方式。uuid()和newId()获取主键的方式,这里选择newId()方式生成主键,mapper.xml的配置如下:

<insert id="Savedata" parameterType="entity.Around" useGeneratedKeys="true" keyProperty="id">
        <selectKey keyProperty="xccd" resultType="java.lang.String" order="BEFORE">
               select newId()
        </selectKey>   这里的selectkey的顺序一定在这里,keyProrty为主键对应的实体类属性,返回类型对应的uuid() newId() 一般为String,根据自己的返回类型决定。order=before为在插入当条数据之前执行,也就是生成一个主键并赋值给xccd属性。还有个order=after,为相反。
        INSERT INTO Around(xccd,stcd,sttp,xcnm,sttm,lead,mans,addvcd) VALUES (#{xccd},#{stcd},#{sttp},#{xcnm},#{sttm},#{lead},#{mans},#{addvcd})  //一定要带上实体类对应主键的属性

</insert>

 3.调用示例:省略dao,service层,跟平时的一样。

//将参数封装给对应的对象

Around  around = new around();   这里的主键是自生成的,所以不用赋值

around.setStcd("111");

...

//调用service层的新增方法

aroundService.add(around);

//执行完成,没有错误可以获取到新增的主键

String xxcd = around.getXccd();  //获取到返回的主键。

原文地址:https://www.cnblogs.com/xiangxinhouse/p/8780454.html