How do I set @entity without the @id element?

I have this bean:

@Entity
@Table(name = "accesos")
public class Acceso implements Serializable {
    /** */
    @Column(name = "idUser")
    private String idUser;
    /** */
    @ManyToOne
    @JoinColumn(name = "idArea")
    private Area area;
    /** */
    @ManyToOne
    @JoinColumn(name = "idRol")
    private Rol rol;

      

But I am getting this error:

Caused by: org.hibernate.AnnotationException: ID for object: com ... Acceso

How do I install this bean? What I need based on the user ID gets all the ROL-AREA that it has access to.

I tried to change @Entity

to @Embedded

, but when I do a search, no result is returned and even no SQL statement is executed in the log.

+3


source to share


3 answers


You must have an identity for each bean, there is no way around. However, you can use a combined key if none of your fields are unique.



If the combination of all of your fields is unique, try annotating all fields with @Id

. Take as few fields as possible, but as many as possible, so that the combination is unique.

+4


source


The JPA spec states that all objects must have an ID ( JSR 317 section 2.4 ). It can be a single column or a compound key.

You can put an identifier idAcceso

in an object, Acceso

or not make Acceso

an object, but rather a "component" (which is the target of the annotation @Embeddable

). Components do not require an ID, but cannot be requested separately (i.e. you cannot execute select a from Acceso a

, but you need to request User

and then use an accessor user.getAccesos()

.



You cannot replace @Entity

with @Embedded

in this context.

@Embeddable
public class Acceso {
  // ...
}

@Entity
public class User {
  @Id protected String id;
  // ...

  @ElementCollection
  @CollectionTable(
    name="USER_ACCESSES",
    joinColumns=@JoinColumn(name="USER_ID")
  protected Set<Acceso> accesos = new HashSet<Acceso>();
}

      

+1


source


You don't have an ID and you MUST add an @Id note on idUser

@Id
@Column(name = "idUser")
private String idUser;

      

-1


source







All Articles