• JPA自定义实体的id


    背景:继上一篇文章,已经实现客户端数据库数据,存入服务器,但是,两张表的id不一样,应该是id设置自增了,所以虽然从客户端查出的实体带id,但是存入服务器时id被抹掉,按照服务端表的id序号向上自增,遂实现id存在的时候按照给定的id,不存在的时候自增

    解决:

    IdGenerator, ps:一定是继承IdentityGenerator, 刚开始写的是实现这个类,但是貌似不对,还有网上说id是long型的是继承IdentityGenerator, 如果是string的要继承UUIDGenerator

    如果写公共的方法,也可以提取公共的id,用公共类去接收obj,我这只是测试,所以直接使用的是TestEntity

    import java.io.Serializable;
    
    import org.hibernate.HibernateException;
    import org.hibernate.engine.spi.SharedSessionContractImplementor;
    import org.hibernate.id.IdentityGenerator;
    
    import com.wqq.test.TestEntity;
    
    public class IdGenerator extends IdentityGenerator{
        
        @Override
        public Serializable generate(SharedSessionContractImplementor s, Object obj) throws HibernateException {
            if (obj == null){
                throw new HibernateException(new NullPointerException()) ;
            }
            Long id = null;
            if (obj instanceof TestEntity) {
                id = ((TestEntity)obj).getId();
            }
            
            if (null == id) {
                return super.generate(s, obj);
            }else {
                return id;
            }
            
        }
        
    }

    实体类上面

            @Id
    	@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "idGenerator")
    	@GenericGenerator(name = "idGenerator", strategy = "com.wqq.test.helper.IdGenerator")
    	@Column(name = "rid")
    	private Long id;
    

      

  • 相关阅读:
    Matlab中对二维数组排序
    ATL COM对象崩溃问题一例
    CSS样式介绍
    关于php
    BootStrap介绍
    关于base系列的加密解密
    php基础知识
    任务一
    php数组
    【CV学习1】opencvpython:第一,二章
  • 原文地址:https://www.cnblogs.com/Cassie-wang/p/11176597.html
Copyright © 2020-2023  润新知