Hibernate使用JoinColumn保存或更新

时间:2018-04-19 00:28:26

标签: java sql spring hibernate spring-mvc

如果它有一个连接列,我会遇到创建新实体的问题。

实体:

@

needsTwoOrMore(["onlyOne"]) // should have error
needsTwoOrMore(["one", "two"]) // should be allowed
needsTwoOrMore(["one", "two", "three"]) // should also be allowed

如果我发送这个json:

type ArrayTwoOrMore<T> = {
    0: T
    1: T
} & Array<T>

declare function needsTwoOrMore(arg: ArrayTwoOrMore<string>): void

needsTwoOrMore(["onlyOne"]) // has error
needsTwoOrMore(["one", "two"]) // allowed
needsTwoOrMore(["one", "two", "three"]) // also allowed

结果是:

Entity
@Table(name = "projects")
public class Project {

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    @Column(name = "id_project")
    private Long id;

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

    @JsonInclude(value = Include.NON_NULL)
    @Column(name = "project_language")  
    private String language;

    @Temporal(TemporalType.DATE)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @Column(name = "start_date")
    private Date start_date;

    @Temporal(TemporalType.DATE)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @Column(name = "end_date")
    private Date end_date;

    @NotFound(action = NotFoundAction.IGNORE)
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "id_content_manager")
    private User contentManager;

保存实体的方法:

{
    "name": "prova3",
    "language": "1",
    "start_date": "15-04-2018",
    "end_date": "26-04-2018"

}

有人可以帮我解决? 我需要了解如何将参数“contentManager”作为可选项传递,以便仅传递id,然后通过find函数检索所有内容并将其传递给contentManager

编辑:

控制器:

Hibernate: insert into projects (id_content_manager, end_date, project_language, project_name, start_date, id_project) values (?, ?, ?, ?, ?, ?)
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1452, SQLState: 23000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (`dipp`.`projects`, CONSTRAINT `projects_user_id_user_fk` FOREIGN KEY (`id_project`) REFERENCES `user` (`id_user`) ON DELETE CASCADE ON UPDATE CASCADE)
ERROR: org.hibernate.internal.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]

2 个答案:

答案 0 :(得分:1)

这不是答案。以下是我的方式,这可能会对你有所帮助。在使用之前,我将其初始化并设置然后将其设置为在父实体中使用。

Icon icon = new Icon();
icon.setIconPath(MiscUtils.getUserIconPath(user));
icon.setUser(user);
user.setIcon(icon);

答案 1 :(得分:1)

问题在于外键projects_user_id_user_fk删除&#34; ON UPDATE CASCADE&#34;并设置&#34; ON UPDATE NO ACTION&#34;,因为当你插入id时它会尝试更新用户表,你可能会尝试用空用户保存项目。