一种可能的解决方案是使用一个单独的实体及其自己的表,该表将仅封装新字段并与该实体具有OneToOne映射。然后,仅当遇到需要附加序列号的对象时,才实例化新实体。然后,您可以使用任何生成器策略来填充它。
@Entitypublic class FooSequence { @Id @GeneratedValue(...) private Long value;}@Entity public class Whatever { @oneToOne(...) private FooSequnce newColumn;}看到:
- hibernateJPA序列(非ID)
- https://forum.hibernate.org/viewtopic.php?p=2405140
Gradle 1.11可运行的SSCCE(使用Spring Boot):
src / main / java / JpaMultikeyDemo.java
import java.util.List;import javax.persistence.*;import lombok.Data;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.annotation.Configuration;import org.springframework.transaction.annotation.EnableTransactionManagement;import org.springframework.transaction.annotation.Transactional;@Configuration@EnableTransactionManagement@EnableAutoConfigurationpublic class JpaMultikeyDemo { @Entity @Data public static class FooSequence { @Id @GeneratedValue private Long value; } @Entity @Data public static class FooEntity { @Id @GeneratedValue private Long id; @oneToOneprivate FooSequence sequence; } @PersistenceContext EntityManager em; @Transactional public void runInserts() { // Create ten objects, half with a sequence value for(int i = 0; i < 10; i++) { FooEntity e1 = new FooEntity(); if(i % 2 == 0) { FooSequence s1 = new FooSequence(); em.persist(s1); e1.setSequence(s1); } em.persist(e1); } } public void showAll() { String q = "SELECt e FROM JpaMultikeyDemo$FooEntity e"; for(FooEntity e: em.createQuery(q, FooEntity.class).getResultList()) System.out.println(e); } public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(JpaMultikeyDemo.class); context.getBean(JpaMultikeyDemo.class).runInserts(); context.getBean(JpaMultikeyDemo.class).showAll(); context.close(); }}build.gradle
apply plugin: 'java'defaultTasks 'execute'repositories { mavenCentral() maven { url "http://repo.spring.io/libs-milestone" }}dependencies { compile "org.springframework.boot:spring-boot-starter-data-jpa:1.0.0.RC5" compile "org.projectlombok:lombok:1.12.6" compile "com.h2database:h2:1.3.175"}task execute(type:JavaExec) { main = "JpaMultikeyDemo" classpath = sourceSets.main.runtimeClasspath}另请参阅:http :
//docs.spring.io/spring-boot/docs/current-
SNAPSHOT/reference/htmlsingle/#boot-features-configure-
datasource



