@OneToOne Spring Boot Jpa

1

I have the following class:

@Entity()
@Table(name = "user")
public class UserBean extends BaseEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Long id;

@NotNull(message = "Username  cannot be null")
@Column
@Size(min = 4, max = 25, message = "Username can not be empty")
private String username;

@NotNull(message = "First Name cannot be empty")
@Column
@Size(min = 3, max = 30, message = "First Name cannot be less than 3 characters")
private String firstName;

@NotNull(message = "Last Name cannot be empty")
@Column
private String lastName;

@Column
private String provider;

//Getter Setter

And this is the child object that represents that is associated by the userbean identifier:

@Table(name = "user_icons")
@Entity
public class UserBeanIcon implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column
@Lob
private byte[] byteContents;


@OneToOne (cascade = CascadeType.ALL)
//@PrimaryKeyJoinColumn
@JoinColumn(name = "USER_ID", unique = true, insertable = true, updatable = true)
private UserBean userBean;

I recompile Maven and reload the project and generate the tables and the relations in the database. The problem is that the relationship that generates me is a OneToMany and not the OneToOne that I expected ...

    
asked by Eduardo 06.06.2018 в 11:02
source

1 answer

0

Here the basic problem is that part of the information about the structure is controlled by JPA and that the BD only sees the part that JPA decides that it sees, with which the structure of tables can offer more functionality than strictly necessary.

In addition, we do not see directly the structure of tables but the graphic representation of the design tool 1 .

In the user_icons table you end up having an id field and an FK field, and in that FK field you can put repeated values 1

The best solution is, for @OneToOne , to use the same key in both tables 2 . Or, in other words, that the FK of user_icons is also the primary key , instead of a separate field.

You can do that using @MapsId ; in this example explain how to use it for @OneToOne

Basically, you indicate that the relationship is already mapped by the Id field (with which you will have the attribute in the entity but in the database it will use the Id field):

@Table(name = "user_icons")
@Entity
public class UserBeanIcon implements Serializable {

@Id // No "@GeneratedValue"
private Long id;
...
@OneToOne (cascade = CascadeType.ALL)
@MapsId
private UserBean userBean;

1 Even if you put unique = true to the FK column, the restriction causes the BD tool to identify the relationship as 1-to-1. Or not.

2 That is also more reasonable if you design the tables from the DER.

    
answered by 06.06.2018 в 13:16