简体   繁体   English

强制 JPA 接受外键值,而不仅仅是实体

[英]Force JPA to accept foreign keys value and not only the entities

I imported some JPA model classes from a MySQL schema.我从 MySQL 模式导入了一些 JPA model 类。

Here is one of the sample classes that are auto generated by JPA:这是 JPA 自动生成的示例类之一:


import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;


/**
 * The persistent class for the surveys database table.
 * 
 */
@Entity
@Table(name="surveys")
@NamedQuery(name="Survey.findAll", query="SELECT s FROM Survey s")
public class Survey implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false)
    private int id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="done_at")
    private Date doneAt;

    //bi-directional many-to-one association to Form
    @ManyToOne
    @JoinColumn(name="form_id", nullable=false)
    private Form form;

    //bi-directional many-to-one association to User
    @ManyToOne
    @JoinColumn(name="user_id", nullable=false)
    private User user;

    public Survey() {
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Date getDoneAt() {
        return this.doneAt;
    }

    public void setDoneAt(Date doneAt) {
        this.doneAt = doneAt;
    }

    public Form getForm() {
        return this.form;
    }

    public void setForm(Form form) {
        this.form = form;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

The problem of this JPA model is, it just accepts entities for the foreign keys.这个 JPA model 的问题是,它只接受外键的实体。 I mean here I have form_id and user_id as the foreign keys: However I don't have any set functions like the following:我的意思是我有form_iduser_id作为外键:但是我没有任何设置函数,如下所示:

public void setForm(int formId) {
    Form form = find from table forms with id equal to formId; 
    this.form = form;
}

or 

public void setForm(int formId) {
    this.formId = formId;
}

How can I force JPA to generate such kind of functions also when it tries to import the schema??当它尝试导入架构时,如何强制 JPA 生成此类功能?

If it is not possible what are the best practices for extending the JPA model class?如果不可能,扩展 JPA model class 的最佳做法是什么? I mean as it may happen in the future by changing of the database schema I need to import the JPA models again, maybe it is not a good idea to implement these functions by hand inside the JPA model and manipulate it by hand.我的意思是因为它可能在未来通过更改数据库模式发生,我需要再次导入 JPA 模型,也许在 JPA Z20F35E630DAF44DBFA4C3F68F69D8F53 中手动实现这些功能并不是一个好主意。

Maybe you ask why do I need such kinds of set functions that accept ids instead of entities?也许你会问为什么我需要这种接受 id 而不是实体的集合函数? My program reads some mockdata and tries to fill the tables in the MySQL.我的程序读取了一些模拟数据并尝试填写 MySQL 中的表格。 The problem is in the mock data I have foreign key of the User and Form entities.问题出在模拟数据中,我有UserForm实体的外键。 They are already exist in the DB, and I don't need to create them again.它们已经存在于数据库中,我不需要再次创建它们。

You cannot use FK-s in JPA as is.您不能按原样在 JPA 中使用 FK-s。 You can use JPQL/SQL to update the given row's field with the FK or you can create a service class, where you load the Form by id and then set it to the given Survey.您可以使用 JPQL/SQL 使用 FK 更新给定行的字段,或者您可以创建服务 class,在其中按 id 加载表单,然后将其设置为给定的调查。 You should avoid to extend an auto generated class (and its agains Open-Close principle too).您应该避免扩展自动生成的 class (以及它的反开闭原则)。

Edit: Create a class, for example FormService.编辑:创建一个 class,例如 FormService。 There you can create a method and use Spring Data JPA, JpaTemplate, Plain JPA or other methods to retrieve the Form.在那里您可以创建一个方法并使用 Spring Data JPA、JpaTemplate、Plain JPA 或其他方法来检索表单。 For example, with hibernate:例如,对于 hibernate:

Form form = session.load(Form.class, id);

Then you set this to the Survey.然后将其设置为调查。

survay.setForm(form);

And now just save it back (persist if it is a new survey or merge if not).现在只需将其保存回来(如果是新调查则保留,如果不是则合并)。

session.merge(survay);

If you use Spring, it may easier and better to use Data Jpa or JpaTemplate, but the previous one will work with Hibernate (and other JPA implementations) in any java environment. If you use Spring, it may easier and better to use Data Jpa or JpaTemplate, but the previous one will work with Hibernate (and other JPA implementations) in any java environment.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM