Home > Blockchain >  store in SQL attribute as an attribute of a class
store in SQL attribute as an attribute of a class

Time:12-15

Hi I want to create a table that in one field store one object like on exemple: and how to handle in java program

public class project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "user")
    private User user;
}

public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

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


}
CREATE TABLE project(
           id PRIMARY KEY, 
           user ???????
);

what is the type to store?

CodePudding user response:

You can use a relationship

@OneToOne
@JoinColumn(name = "user_id")
private User user;

where user_id is defined as

CREATE TABLE project(
    id PRIMARY KEY, 
    user_id INTEGER NOT NULL
);

CodePudding user response:

in this case, User has to be an entity too. Hibernate creates a relationship between these objects. You have to annotate the relation type. For example, you can add @OneToOne annotation over user field. Then Spring will add a field to table project to find that specific user from user table.

  • Related