传递的分离实体持久保存主键也是外键

时间:2017-02-17 12:38:20

标签: postgresql hibernate jpa

我在postgres中有以下表格:

create table USER(
    USER_ID SERIAL primary key,
    USER_NAME varchar(50) not null,
    PASSWORD varchar(120) not null,
)

create table ACCESS_TOKEN(
    USER_CODE INTEGER,
    TOKEN_CREATED DATE,
    TOKEN_VALUE VARCHAR(100),

    primary key (USER_CODE, TOKEN_CREATED),
    foreign key (USER_CODE) references USER(USER_ID),
)

我创建了以下实体

@Entity
@Table(name="USER")
public class User implements Serializable{

    @Id
    @SequenceGenerator(name = "USER_USER_ID_SEQ_GEN", sequenceName = "USER_USER_ID_SEQ", initialValue=1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_USER_ID_SEQ_GEN")
    @Column(name="USER_ID")
    private int id;

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

    @Column(name="PASSWORD")
    private String password;
}

@Entity
@Table(name = "ACCESS_TOKEN")
@IdClass(AccessToken.AccessTokenPK.class)
public class AccessToken implements Serializable{

    @Id
    @JoinColumn(name="USER_CODE", referencedColumnName = "USER_ID")
    @ManyToOne
    private User user;

    @Id
    @Column(name="TOKEN_CREATED")
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;


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


    public static class AccessTokenPK implements Serializable{
        protected int user;
        protected Date created;

        //constructor, hashbode, and equals
    }

}

但是,当我尝试将访问令牌保留为以下内容时:

AccessToken accessToken = new AccessToken();
accessToken.setUser(userEntity);
accessToken.setCreated(new Date());
accessToken.setToken("some string");
// persist token
dao.persist(accessToken);

我收到以下错误

detached entity passed to persist: User

1 个答案:

答案 0 :(得分:0)

Hibernate通过其主键识别实体。 尝试将GenerationType.AUTO设置为用户的主键,

@Entity
@Table(name="USER")
public class User implements Serializable{

    @Id
    @SequenceGenerator(name = "USER_USER_ID_SEQ_GEN", sequenceName = "USER_USER_ID_SEQ", initialValue=1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "USER_USER_ID_SEQ_GEN")
    @Column(name="USER_ID")
    private int id;

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

    @Column(name="PASSWORD")
    private String password;
}




@Entity
@Table(name = "ACCESS_TOKEN")
@IdClass(AccessToken.AccessTokenPK.class)
public class AccessToken implements Serializable{

    @Id
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name="USER_CODE", referencedColumnName = "USER_ID")
    @ManyToOne
    private User user;

    @Id
    @Column(name="TOKEN_CREATED")
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;


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


    public static class AccessTokenPK implements Serializable{
        protected int user;
        protected Date created;

        //constructor, hashbode, and equals
    }

}