skip to Main Content

I have an entity that looks like this

@Entity
@IdClass(AId.class)
class A {
    
   @Id
   private String userName
    
   @Id
   @NotNull
   @JoinColumn(name = "location_id", referenceColumnName = "id", nullable=false, foreignKey = @ForeignKey(name = ...))
   private Location location;
   
   private String userInformation;
}

The class Location looks like this:

@Entity
class Location {

   @NotNull
   private Long id;

   @NotNull
   @Column(nullable = false}
   private String name;
}

And then I have a class to define the Id

class AId implements Serializable {
  private Long locationId;
  private String userName;
}

Now, I do some manipulation on the object of class A and then want to store it. However, I get an exception that tells me that the non-nullable field Location#name that is reference by an object of A is null. I debugged through it and made sure that the field is actually not null. However, I still get this. What’s the issue? The location that A is referring to is already persisted on the database.

2

Answers


  1. This may be caused by the types of @Id fields not matching the types in id class. According to https://docs.oracle.com/javaee/7/api/javax/persistence/IdClass.html

    The names of the fields or properties in the primary key class and
    the primary key fields or properties of the entity must correspond and
    their types must be the same.

    Login or Signup to reply.
  2. Try with ManyToOne and change locationId to location :

    @Entity
    class Location {
       @Id
       @NotNull
       private Long id;
    }
    
    class AId implements Serializable {
      private Long location;
      private String userName;
    }
    
    @Entity
    @IdClass(AId.class)
    class A {
        
       @Id
       private String userName
        
       @Id
       @NotNull
       @ManyToOne
       @JoinColumn(name = "location_id", nullable=false, foreignKey = @ForeignKey(name = ...))
       private Location location;
       
    }
    

    See also https://jakartaee.github.io/jakartaee-documentation/jakartaee-tutorial/9.1/persist/persistence-basicexamples/persistence-basicexamples.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search