SpringMVC+MyBatis+MySQL 返回插入的自增主键ID

由于表与表之间的关联,表的自增主键尤为重要。那么我们如何在insert into的同时返回自增主键ID呢?

Client表字段名:

SpringMVC+MyBatis+MySQL 返回插入的自增主键ID_第1张图片

Client POJO:

public class Client {
    private int cId;
    private String cClientname;
    private String cPassword;
    private String cPhonenum;
}

xml映射器:


        insert into client (c_clientname,c_password,c_phonenum) VALUES (#{cClientname} , #{cPassword} , #{cPhonenum})
  1. 设置useGeneratedKeys参数值为true,在执行insert into之后可以获取到数据库自动生成的主键ID
  2. keyProperty = “POJO属性名”
  3. parameterType = “输入参数类型”

接口映射器:

int InsertTheClient(Client client);

Controller:

@Autowired
    ClientServiceImpl csi;

Client client = new Client();
    client.setcClientname(ClientName);
    client.setcPhonenum(ClientPhone);
    client.setcPassword("000000");
    csi.InsertTheClient(client1);
    int cId = client1.getcId();
    

 

你可能感兴趣的:(Java基础,java,mybatis,sql,springmvc,后端)