【问题标题】:Retrieve an object which has a POJO as a primary key with Spring JPA使用 Spring JPA 检索具有 POJO 作为主键的对象
【发布时间】:2016-11-13 12:22:36
【问题描述】:

我有以下类:DepartmentMember 和 Account,由 OneToOne 关系映射。

这是 DepartmentMember 类:

@Entity(name="departmentmember")
@Table(name="departmentmember")
@Embeddable
public class DepartmentMember {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int id;

   @Column(name="name", nullable=false)
   private String nume;

   @Column(name="lastName", nullable=false)
   private String prenume;

   @OneToOne(mappedBy="departmentMember",cascade=CascadeType.ALL,fetch=FetchType.LAZY, optional=false)
   @JsonIgnore
   private Account account;

   public DepartmentMember() {}

   public DepartmentMember(String nume, String prenume, String cNP, String email) {
       super();
       this.nume = nume;
       this.prenume = prenume;

     }

  //getters and setters

}

这是 Account 类:

@Entity(name="users")
@Table(name="users")
public class Account {

    @Id
    private int id;

    @Column(name="username", unique=true, nullable=false)
    private String username;

    @Column(name="password", nullable = false)
    private String password;

    @Column(name="authorities", nullable=false)
    private String authorities;

    @OneToOne(fetch=FetchType.EAGER)
    @MapsId
    @Embedded
    private DepartmentMember departmentMember;

    public Account() {}


    public Account(String username, String password, String authorities) {
    super();
    this.username = username;
    this.password = password;
    this.authorities = authorities;
}

//getters and setters
}

我定义了一个接口 AccountRepository,它扩展了 Spring JPA 提供的 CrudRepository 接口。 我想要做的是定义一个查询,它将 DepartmentMember id 作为参数并检索该成员的关联帐户。现在这是 Account 对象的样子:

{
"username": "Maria_Popescu",
"password": "4ec38c6e-2463-4562-99ba-9f6c2b4528c4",
"authorities": "ROLE_USER",
"departamentMember": {
  "id": 2,
  "nume": "Popescu",
  "prenume": "Maria",
}

我尝试使用 findOne(int id) 方法,但它不起作用,那么解决这个问题的正确方法是什么?

编辑: 在 AccountRepository 中,我定义了以下方法:

Account findByDepartmentMemberId(int id) 我仍然收到未找到错误。

【问题讨论】:

  • 我从上面有点困惑,你确定你的映射是正确的吗?我不认为 Account DepartmentMember 可以同时是 Embedded 和 OneToOne。
  • @garfield 我后来实际上删除了这些,但它并没有改变事情的行为方式。我的查询仍然无法正常工作:(

标签: spring hibernate jpa spring-boot spring-data-jpa


【解决方案1】:

实际上我的控制器还有另一个问题。我设法通过添加

让它工作
Account findByDepartmentMemberId(@Param("id")int id);

在 AccountRepository 中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多