使用Hibernate将空值插入到外键字段中

时间:2019-02-27 21:31:47

标签: java mysql hibernate spring-boot

我有一个Question实体和一个Tag实体,该实体具有getter,setter方法以及从OneToManyquestion的{​​{1}}关系和一个{{1} }从tagOneToOne

的关系
question

标签实体

user

当我尝试使用邮递员插入具有以下详细信息的问题时:

public class Question {

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

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

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

    @Temporal(TemporalType.DATE)
    @Column(name="date_created")
    private Date date_created;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="user_id")
    private User user;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="tag_id")
    private Tag tag;

    @Column(name="answer_count")
    private int answer_count;

    @Column(name="view_count")
    private int view_count;

    public Question() {

}

QuestionRepository.java:

public class Tag {

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

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

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

    @Temporal(TemporalType.DATE)
    @Column(name="date_created")
    private Date date_created;

    public Tag() {

}

尽管我使用了{ "title": "stefanyyyxx", "body": "stefandoyee44", "date_created": "2019-02-27", "user_id" : 1, "tag_id": 1, "answer_count": 0, "view_count": 0 } ,但正在为@Override public void save(Question theQuestion) { // get the current hibernate session Session currentSession = entityManager.unwrap(Session.class); // save employee currentSession.saveOrUpdate(theQuestion); } user_id插入空值。

MySQL:

enter image description here

3 个答案:

答案 0 :(得分:1)

JSON和@Entity结构之间不匹配。 JSON包含数字标识符,而@Entity包含表示关系的实际对象。您很可能应该引入一个单独的DTO类来映射此JSON,而在@Repository中,您应根据其ID加载UserTag对象或创建新对象。您已经拥有CascadeType.ALL,因此Hibernate将层叠持久化操作。

通常,控制器层应该与存储库层分开,除非您做的事情非常非常简单。这有助于在不更改API合约的情况下发展服务,例如添加新列以审核更改。通过将@Entity公开为DTO,可以使您的生活更加艰难。

答案 1 :(得分:1)

您应在子实体外键列中添加referencedColumnName

referencedColumnName="your primaray key column name"

编辑:

referencedColumnName

  • 此外键列引用的列的名称。
  • 与案例以外的实体关系映射一起使用时 如此处所述,引用的列在目标表中 实体。
  • 与单向OneToMany外键映射一起使用时, 被引用的列在源实体的表中。
  • 在JoinTable批注中使用时,引用的键列为 在拥有实体的实体表中;如果 连接是反向连接定义的一部分。
  • 在CollectionTable映射中使用时,引用的列位于 包含集合的实体的表。
  • 默认值(仅在使用单个连接列时适用):相同 名称作为被引用表的主键列。

资产是父实体,AssetDetails是子实体 在这里,我采取了一对一关系

Asset.java

@Entity
@Table(name="asset")
public class Asset {

    @Id
    @GeneratedValue
    @Column(name="assetid")
    private BigInteger assetid;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "asset")
    @JsonBackReference
    private AssetDetails assetDetails;

     public AssetDetails getAssetDetails() {
        return assetDetails;
    }

    public void setAssetDetails(AssetDetails assetDetails) {
        this.assetDetails = assetDetails;
        assetDetails.setAsset(this);
    }

    public Asset(your fields, AssetDetails assetDetails) {
        super();
        // your fields
        this.assetDetails = assetDetails;
        this.assetDetails.setAsset(this);
    }

    public Asset() {
        super();
    }

    public BigInteger getAssetid() {
        return assetid;
    }

    public void setAssetid(BigInteger assetid) {
        this.assetid = assetid;
    }
}

AssetDetails.java

@Entity
@Table(name="assetDetails")
public class AssetDetails {

    @Id
    @GeneratedValue
    private BigInteger assetdetailid;

    @JoinColumn(name = "assetid",nullable = false, updatable = false,referencedColumnName="assetid")
    @OneToOne(cascade=CascadeType.ALL)
    @JsonManagedReference
    private Asset asset;

    public Asset getAsset() {
        return asset;
    }

    public void setAsset(Asset asset) {
        this.asset = asset;
    }

    public AssetDetails(your fields,Asset asset) {
        super();
        //your fields
        this.asset = asset;
    }   
}

答案 2 :(得分:1)

@Karol Dowbecki的建议,

将JSON转换为DTO对象,并使用该DTO从各自的存储库中获取UserTag实体。

最后创建问题实体对象并存储它。

问题实体

@Entity
@Table(name = "question")
public class Question {

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

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

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

    @Temporal(TemporalType.DATE)
    @Column(name = "date_created")
    private Date dateCreated;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "tag_id")
    private Set<Tag> tag;

    @Column(name = "answer_count")
    private int answerCount;

    @Column(name = "view_count")
    private int viewCount;

}

用户实体

@Entity
@Table(name = "user")
public class User {

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

    private String name;

}

标签实体

@Entity
@Table(name = "tag")
public class Tag {

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

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

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

    @Temporal(TemporalType.DATE)
    @Column(name = "date_created")
    private Date dateCreated;

}

DTO类

public class QuestionDTO {

    private Long id;

    private String title;

    private String body;

    private Date dateCreated;

    private Long user;

    private Long tag;

    private int answerCount;

    private int viewCount;
}

测试类

@Service
public class TestService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TagRepository tagRepository;

    public void addQuestion(QuestionDTO dto) {
        Tag tag = null;
        User user = null;
        Question question = null;

        Set<Tag> tags = null;

        tag = tagRepository.findById(dto.getTag());

        tags = new HashSet<>();
        tags.add(tag);

        user = userRepository.findById(dto.getUser());

        question = new Question();
        question.setTag(tags);
        question.setUser(user);
        question.setId(dto.getId());
        question.setBody(dto.getBody());
        question.setTitle(dto.getTitle());
        question.setViewCount(dto.getViewCount());
        question.setAnswerCount(dto.getAnswerCount());
        question.setDateCreated(dto.getDateCreated());

        questionRepository.save(question);

    }
}

注意QuestionTag之间的关系在OneToMany中,您必须使用Collection类型。