栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JPA-以编程方式通过序列增加数字字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JPA-以编程方式通过序列增加数字字段

一种可能的解决方案是使用一个单独的实体及其自己的表,该表将仅封装新字段并与该实体具有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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/385319.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号