二、MyBatis日常积累:postgresql+mybatis自增序列返回值

postgresql+mybatis自增序列返回值

  • 1. 建表语句
  • 2. mapper.xml

1. 建表语句

/** 
* sa_service_block_id 类型设为serial(自增列),数据库中会自动为序列(sequence)sa_service_block_id 加上:
* nextval('mgmt.sa_service_block_sa_service_block_id_seq'::regclass);
* sa_service_block_id 真实类型为Integer
*/
create table mgmt.sa_service_block(
    sa_service_block_id serial not null, 
    block_name text not null, 
    domain_name text, 
    public_ip text not null, 
    openresty_server_info jsonb, 
    app_server_info jsonb, 
    db_server_info jsonb, 
    constraint PK_SA_SERVICE_BLOCK_ID primary key(sa_service_block_id)
);
comment on table mgmt.sa_service_block is '云平台逻辑部署单元,包含一组LB+APP集群+DB服务';
comment on column mgmt.sa_service_block.sa_service_block_id is 'service block主键ID';
comment on column mgmt.sa_service_block.block_name is 'service block名称';
comment on column mgmt.sa_service_block.domain_name is 'service block域名信息';
comment on column mgmt.sa_service_block.public_ip is '该service block对外的公网IP地址';
comment on column mgmt.sa_service_block.openresty_server_info is 'openresty信息';
comment on column mgmt.sa_service_block.app_server_info is '应用服务器信息,含IP地址,管理员帐号和密码';
comment on column mgmt.sa_service_block.db_server_info is '数据库服务器IP,连接用帐号和密码';

2. mapper.xml

<insert id="insert" parameterType="com.gantang.mgmt.block.model.ServiceBlock">
      <selectKey keyProperty="saServiceBlockId" resultType="Integer" order="AFTER">
          SELECT currval('mgmt.sa_service_block_sa_service_block_id_seq'::regclass)
      selectKey>
    insert into sa_service_block (block_name, domain_name, public_ip, openresty_server_info, app_server_info, 
      db_server_info)
    values (#{blockName,jdbcType=VARCHAR}, #{domainName,jdbcType=VARCHAR}, #{publicIp,jdbcType=VARCHAR}, 
    #{openrestyServerInfo,jdbcType=OTHER}, #{appServerInfo,jdbcType=OTHER}, #{dbServerInfo,jdbcType=OTHER})
  insert>
  1. selectKey标签:将insert自动生成的主键返回
  2. order="AFTER":对应着currval(‘mgmt.sa_service_block_sa_service_block_id_seq’::regclass),
  3. currval(regclass)函数:获取指定序列最近一次使用nextval后的数值,如果没有使用nextval而直接使用currval会报错

你可能感兴趣的:(#,MyBatis日常积累)