【问题标题】:Have a String name as an Id with JPA使用 JPA 将字符串名称作为 Id
【发布时间】:2019-08-20 07:53:55
【问题描述】:

我想要做的是将我的 id 从浮点数更改为字符串。

我有这个代表一个组的实体:

@Entity
@Table(name="group")
public class GroupEntity {

@Id
private String name;

@ManyToMany
private List<UserEntity> users;

在我的引导文件中我有这个:

    Password p = new Password("test");

    UserEntity user = new UserEntity("pedro", p);
    List<UserEntity> users = new ArrayList<UserEntity>();

    List<GroupEntity> groupEntities=new ArrayList<GroupEntity>();

    users.add(user);

    GroupEntity r1 = new GroupEntity("Integrations");

    groupEntities.add(r1);
    user.getGroups().add(r1); //this user has a group

    r1.setUsers(users);  // this group has a user

我的 UserEntity 类如下所示:

@Entity
@Table(name="user")
public class UserEntity {

@Id
@GeneratedValue
private Long id;

private String name;

这样,我的程序就可以正常运行了,您可以看到组以 id 作为他们的名字保存:

但是当我将 UserEntity 类从那个更改为这个时:

@Entity
@Table(name="user")
public class UserEntity {

@Id 
private String name;

出现这个错误:

org.springframework.beans.factory.BeanCreationException: 错误 创建名为“bootstrap”的 bean:调用 init 方法失败; 嵌套异常是 org.springframework.orm.jpa.JpaObjectRetrievalFailureException:无法 找到具有 id 集成的 com.alert.interservices.uaa.RoleEntity; 嵌套异常是 javax.persistence.EntityNotFoundException: Unable 找到带有 id 集成的 com.alert.interservices.uaa.RoleEntity

我认为问题出在 id 上,但不知道如何解决。

更新 1-application.properties:

spring.datasource.url=jdbc:h2:file:~/test2;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
spring.datasource.username=admin
spring.datasource.password=password
spring.h2.console.enabled=true

【问题讨论】:

  • 我认为表user的字段name必须是主键才能使用@Id
  • 看起来您还应该更改数据库结构,将 name 设为主键并删除旧的主键 id。因为关系数据库有一个预定义的模式,你应该随着 ORM 映射的变化迁移模式
  • 您是否还有需要以某种方式更新的 RoleEntity?你是如何创建数据库模式的?它是由 Hibernate 使用 create-drop 创建的吗?
  • 我正在使用 h2 和 spring,配置在我的 applications.properties 文件中,我用它更新了我的问题
  • 你必须把 application.properties - spring.jpa.properties.hibernate.ddl-auto=create-drop

标签: java spring spring-boot spring-mvc jpa


【解决方案1】:

首先,是的,您可以使用 String 作为 Id 类型。但我认为你的问题是你在没有删除旧数据库的情况下编辑了实体,所以为了防止这个问题,你必须在持久性单元中更改策略以删除和创建,因为你使用的是可以使用的 spring 数据:

spring.jpa.hibernate.ddl-auto=create-drop

但你可以只用它来测试,但在生产环境中你必须将它切换到spring.jpa.hibernate.ddl-auto=update. 注意:update 选项只添加列但从不删除列。

【讨论】:

  • 我如何使用 h2 和 spring 做到这一点?
  • 我在我的 application.properties 上做了这个 (spring.jpa.hibernate.ddl-auto=create-drop),但是没有用
  • 您好,抱歉让您久等了,是的,您可以使用 spring.jpa.hibernate.ddl-auto=create-drop 但只是在生产环境中的测试期间您将其切换为:spring.jpa.hibernate .ddl-auto=更新
  • 所以尝试手动删除数据库,然后重新运行项目。
猜你喜欢
  • 2011-07-13
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多