hiberbate 插入为空时使用数据库默认值

 

Hibernate 插入数据库时没有指定的值默认设置为null,如果数据库设置的不为空,会报错误:



 

 

org.springframework.dao.DataIntegrityViolationException: could not insert: [com.woyo.trade.model.UserOrder]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [com.woyo.trade.model.UserOrder]

Caused by:

org.hibernate.exception.ConstraintViolationException: could not insert: [com.woyo.trade.model.UserOrder]

       at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)

       at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)

       at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)

       at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)

       at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)

       at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)

       at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250

[yangfan@storage-15 back_tomcat_12]$

 

 

解决方法:

 

方法一:javaBean 里面设置默认值:

javabean里面的字段默认值设置成数据库的默认值

如下:

 

数据库设置:

 

 

          `ticketStatus` tinyint(4) NOT NULL DEFAULT '0' 

 

     java代码

   /**

     * 出票状态

     */

 

private Long ticketStatus = 0L ;

  

        这样hibernate 插入时会使用javabean设置的默认值。

    不推荐这种做法:这需要javaBean里面的默认值和数据库一致,需要多处维护。

 

 

方法二:使用hibernate机制实现

 

在插入数据时,如果数据库有默认值且插入值为null,则自动插入数据库默认值;如果插入值不为空则保留该值。看似简单一个需求,hibernate的实现都几经波折。

 

<!--[if !supportLists]-->1.    <!--[endif]-->使用HBM文件时,加入

  dynamic-insert="true  dynamic-update="true”

 

HBM配置:

<hibernate-mapping>

    <class name="com.woyo.trade.model.UserOrder" table="user_order" lazy="false"

    dynamic-insert="true" dynamic-update= "true">

   

        <id name="id" type="java.lang.Long">

            <column name="id" precision="11" scale="0" />

            <generator class="identity">

            </generator>

        </id>

……

 

 

2.使用注解时,在类级别上添加 

Java代码  

 @org.hibernate.annotations.Entity(dynamicUpdate=true,dynamicInsert=true)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值