8°

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
</span><span style="color: #0000ff;">public</span> Serializable generate(SharedSessionContractImplementor s, Object obj) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> HibernateException {
    </span><span style="color: #0000ff;">if</span> (obj == <span style="color: #0000ff;">null</span><span style="color: #000000;">){
        </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> HibernateException(<span style="color: #0000ff;">new</span><span style="color: #000000;"> NullPointerException()) ;
    }
    Long id </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
    </span><span style="color: #0000ff;">if</span> (obj <span style="color: #0000ff;">instanceof</span><span style="color: #000000;"> TestEntity) {
        id </span>=<span style="color: #000000;"> ((TestEntity)obj).getId();
    }
    
    </span><span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">null</span> ==<span style="color: #000000;"> id) {
        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">super</span><span style="color: #000000;">.generate(s, obj);
    }</span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
        </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> id;
    }
    
}

}

 

实体类上面

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

  

原文链接:https://www.cnblogs.com/Cassie-wang/p/11176597.html

全部评论: 0

    我有话说: