建表SQL:

DROP TABLE IF EXISTS person;
CREATE TABLE person(
person_id serial PRIMARY KEY NOT NULL,
person_name VARCHAR(60),
gender INT,
person_addr VARCHAR(100),
birthday DATE
);

注意:在postgresql中建表的时候,将主键id字段设置成serial类型,会自动生成一个关联主键id的序列(如下图中的数据库会创建一个隐含序列"person_person_id_seq"),SERIAL类型的字段和MySQL中的自增唯一ID等价。

当你在你的数据表中定义了一个SERIAL类型的列后,SERIAL的自增功能会被自动添加到数据库。

--------------------------------------------------------------------------------------

接口Controller:

@Component
@Path("/person")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class PersonController {
@Autowired
PersonService personService; @POST
@Path("/insert")
@Consumes(MediaType.APPLICATION_JSON)
public ResultModel insert() {
Person person = new Person();
person.setBirthday(new Date());
person.setGender();
person.setPersonAddr("广州");
person.setPersonName("小红");
personService.insert(person);
return ResultModel.ok(person);
}

注意上面的Person对象没有为personId赋值。因为person表的主键列person_id是自增的。

下面是使用mybatis的逆向工程生成的PersonMapper接口:

public interface PersonMapper {
@Insert({
"insert into person (" +
"PERSON_ID, " +
"PERSON_NAME, " +
"GENDER, " +
"PERSON_ADDR, " +
"BIRTHDAY)",
"values (" +
"#{personId,jdbcType=INTEGER}, " +
"#{personName,jdbcType=VARCHAR}, " +
"#{gender,jdbcType=INTEGER}, " +
"#{personAddr,jdbcType=VARCHAR}, " +
"#{birthday,jdbcType=DATE})"
})
int insert(Person person);
}

由于person表的主键person_id是自增的,所以访问Controller中的"/person/insert"方法插入数据的时候会报如下错误:

HTTP Status 500 - org.springframework.dao.DataIntegrityViolationException:
type Exception report
message org.springframework.dao.DataIntegrityViolationException:
description The server encountered an internal error that prevented it from fulfilling this
request.
exception
javax.servlet.ServletException: org.springframework.dao.DataIntegrityViolationException:
### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
### The error may involve com.zhaopin.dao.PersonMapper.insert-Inline
### The error occurred while setting parameters
### SQL: insert into person (PERSON_ID, PERSON_NAME, GENDER, PERSON_ADDR, BIRTHDAY) values (?, ?, ?, ?, ?)
### Cause: org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
; SQL []; ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).; nested exception is org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:391)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause org.springframework.dao.DataIntegrityViolationException:
### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
### The error may involve com.zhaopin.dao.PersonMapper.insert-Inline
### The error occurred while setting parameters
### SQL: insert into person (PERSON_ID, PERSON_NAME, GENDER, PERSON_ADDR, BIRTHDAY) values (?, ?, ?, ?, ?)
### Cause: org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
; SQL []; ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).; nested exception is org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:243)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:74)
org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:399)
com.sun.proxy.$Proxy23.insert(Unknown Source)
org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:253)
org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:52)
org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
com.sun.proxy.$Proxy31.insert(Unknown Source)
com.zhaopin.service.impl.PersonServiceImpl.insert(PersonServiceImpl.java:30)
com.zhaopin.api.PersonController.insert(PersonController.java:58)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:269)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:252)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1025)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause org.postgresql.util.PSQLException: ERROR: null value in column "person_id" violates not-null constraint
详细:Failing row contains (null, 小兰, 2, 重庆, 2017-06-04).
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:413)
com.alibaba.druid.pool.DruidPooledPreparedStatement.execute(DruidPooledPreparedStatement.java:493)
org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:45)
org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:73)
org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:49)
org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:115)
org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:75)
org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:170)
org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:157)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:386)
com.sun.proxy.$Proxy23.insert(Unknown Source)
org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:253)
org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:52)
org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
com.sun.proxy.$Proxy31.insert(Unknown Source)
com.zhaopin.service.impl.PersonServiceImpl.insert(PersonServiceImpl.java:30)
com.zhaopin.api.PersonController.insert(PersonController.java:58)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:269)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:252)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1025)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.53 logs. Apache Tomcat/7.0.53

意思是说"person_id"这一列违反非空约束,不能为null。

解决办法:修改PersonMapper中的@Insert注解中的SQL语句,首先把person_id列去掉。

然后增加一个@Options注解,声明主键列是自增的:

public interface PersonMapper {
@Insert({
"insert into person (" +
"person_name, " +
"gender, " +
"person_addr, " +
"birthday)",
"values (#{personName,jdbcType=VARCHAR}, " +
"#{gender,jdbcType=INTEGER}, " +
"#{personAddr,jdbcType=VARCHAR}, " +
"#{birthday,jdbcType=DATE})"
})
@Options(useGeneratedKeys=true, keyProperty="personId",keyColumn = "person_id")
int insert(Person person);
}

表名都改为了小写,数据库中表字段名也都是小写。保持一致。经测试,如果数据库中的表字段名是大写的话,会报错。

再次测试插入,成功,接口返回结果:

如果觉得本文对您有帮助,不妨扫描下方微信二维码打赏点,您的鼓励是我前进最大的动力:

mybatis使用注解往postgresql数据库表insert数据[主键自增]的写法的更多相关文章

  1. Mybatis里Mapper映射sql文件里insert的主键返回selectKey使用

    有时候新增一条数据,知道新增成功即可,但是有时候,需要这条新增数据的主键,以便逻辑使用,再将其查询出来明显不符合要求,效率也变低了. 这时候,通过一些设置,mybatis可以将insert的数据的主键 ...

  2. mysql数据库单表只有一个主键自增id字段,ibatis实现id自增

    mysql数据库单表只有一个主键自增id字段,ibatis实现id自增 <insert id="autoid">        insert into user_id ...

  3. 使用navicat操作PostPreSql创建表并设置主键自增和触发器

    使用navicat操作PostPreSql创建表并设置主键自增和触发器 1).创建递增序列 2).创建表,使用序列,设置主键递增 3)定义触发函数 自动生成时间戳函数 CREATE OR REPLAC ...

  4. 更新oracle数据库表如何实现主键自增长

     在数据库中实现主键自动增长有利于我们做数据插入操作,在SQL SERVER上创建表时可以在int类型的字段后加上identity(1,1),该字段就会从1开始,按照+1的方式自增,将这个字段设置 ...

  5. Mybatis insert 获取主键自增id

    Mybatis insert 返回自增主键 mysql 准备一张带有自增主键的表users 字段:id,name,phone sql <!--插入记录并获取刚插入记录的主键--> < ...

  6. Oracle 创建表并设置主键自增

    创建数据库 CREATE TABLE STUDENT(ID NUMBER PRIMARY KEY, NAME VARCHAR(200) NOT NULL, SEX VARCHAR(200), CREA ...

  7. Oracle创建表(包含、主键自增)

    注意:Oracle导出建表语句不会导出触发器及自增索引 第一步:创建一张表 create table member( memberId number primary key, --主键.自增长 mem ...

  8. oracle建表 和 设置主键自增

    1.新建table CREATE TABLE ysb_log( id ) primary key not null , tbdate ) NULL, tb_time ) NOT NULL, tblog ...

  9. 通过DbVisualizer 工具运行DB2存储过程实现INSERT语句主键自增造数

    1.需求简介 最近开发人员需要进行一批数据进行生产上SQL语句耗时过长问题的验证与优化.所以在性能测试库中批量建造数据,由于交易本身业务逻辑过于复杂以及需要各种授权,最后决定采用插表的方式完成. 2. ...

随机推荐

  1. RabbitMQ.Client API (.NET)中文文档

    主要的名称空间,接口和类 核心API中定义接口和类 RabbitMQ.Client 名称空间: 1 using RabbitMQ.Client; 核心API接口和类 IModel :表示一个AMQP ...

  2. MongoDB 2.6配置副本集,支持端口号修改和用户登录认证

    mongoDB系列之(二):mongoDB 副本集 Mongodb2.6副本集验证部署和认证 副本集有以下特点: 1. 最小构成是:primary,secondary,arbiter,一般部署是:pr ...

  3. 数十种TensorFlow实现案例汇集:代码+笔记

    这是使用 TensorFlow 实现流行的机器学习算法的教程汇集.本汇集的目标是让读者可以轻松通过案例深入 TensorFlow. 这些案例适合那些想要清晰简明的 TensorFlow 实现案例的初学 ...

  4. Checkstyle-Configuration

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE module PUBLIC "-/ ...

  5. iOS 11和xcode9

    最近发现了比较奇怪的问题,就是 ios10.几以前的版本,用xcode9 编写的程序   如果程序写的table是  plain的  ,那么  在  ios10.几及以下版本都会显示成group样式, ...

  6. 【Algorithm】自顶向下的归并排序

    一. 算法描述 自顶向下的归并排序:采用分治法进行自顶向下的程序设计方式,分治法的核心思想就是分解.求解.合并. 先将长度为N的无序序列分割平均分割为两段 然后分别对前半段进行归并排序.后半段进行归并 ...

  7. list、map、数组 转换

    list,set,map,数组间的相互转换1.list转setSet set = new HashSet(new ArrayList()); 2.set转listList list = new Arr ...

  8. Struts2之数据标签(二)

    Struts2之数据标签(一):http://blog.csdn.net/u012561176/article/details/46848817 1.action标签:使用此标签能够同意在JSP页面中 ...

  9. [转]单元测试利器 JUnit 4

    引言 毋庸置疑,程序员要对自己编写的代码负责,您不仅要保证它能通过编译,正常地运行,而且要满足需求和设计预期的效果.单元测试正是验证代码行为是否满足预期的有效手段之一.但不可否认,做测试是件很枯燥无趣 ...

  10. 搭建Dubbo+Myeclipse2015+Maven3.3.1的过程遇到问题集锦

    1. 找不到dubbo2.8.4包的问题 在编译Maven工程的过程中,出现如下问题: Description Resource Path Location Type ArtifactDescript ...