簡體   English   中英

Hibernate使用REST添加具有外鍵的實體

[英]Hibernate add an entity with foreign key using REST

首先,我沒有編寫任何SQL語句來創建表。 我嘗試僅在不編寫SQL的情況下使用Hibernate / jpa。

我的關系如下:一個用戶可以有多個任務,一個任務只有一個用戶。

我是這樣創建模型的:

用戶表:

@Entity
@Table(name="T_USER")
@EntityListeners(AuditingEntityListener.class)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "uid")
    private Long uid;
...
}

任務表:

@Entity
@Table(name = "T_TASK")
@EntityListeners(AuditingEntityListener.class)
public class TASK{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long tid;

    @ManyToOne
    @JoinColumn(name ="oid")
    private User owner;

    public User getOwner() {
        return owner;
    }

    public void setOwner(User owner) {
        this.owner = owner;
    }
...
}

關系是任務的ownerid(oid)是用戶的uid。

要將用戶保存到數據庫,我使用具有以下參數的郵遞員:

{
    "username": "firstuser",
    "email": "firstuser@email.com"
}

要將任務保存到數據庫中,我正在使用以下命令:

{
    "description": "some description",
    "oid": "12" // I also can state username of the user rather than ID
}

但是,當我執行保存任務時,任務的oid為NULL。 在數據訪問對象中,我具有:

@PostMapping("/save")
public QR createTask(@Valid @RequestBody Task task)
{
    return taskDAO.save(task);
}

1-我在做什么錯? 我只想將具有所有者ID的任務添加到數據庫,但是它會返回null作為所有者ID。

2-我應該首先使用SQL創建表

 Create table task(
     tid BIGINT,
     description VARCHAR(255),
     oid BIGINT,
     PRIMARY KEY(tid), FOREIGN KEY(oid) REFERENCES (user.uid))

3-我應該在TaskDAO中更改保存方法嗎?

 public Task save(Task task)
 {
    return taskRepository.save(task);
 }

4-我應該更改控制器方法(使用RESTcall的createTask方法)

5-假設以上所有問題均已解決。 如何獲取用戶的所有任務?

6-刪除用戶后如何刪除任務(SQL中為小寫,但Hibernate中有任何方法)

我希望我能解釋我的問題。 任何反饋將不勝感激。

oid為null,因為Task沒有這樣的字段。 我認為您在這里混入兩個概念。 第一個是代表您的REST數據結構的數據傳輸對象。 這個應該有一個oid字段。 第二個是持久實體。 您擁有的這是Task類。

我將實現一個TaskDTO,使用Hibernate的會話通過其ID加載User ,然后根據UserTaskDTO的其他字段構建Task ,然后像您一樣保存Task。

關於其他問題

2-使用hibernate.hbm2ddl.autocreateupdate值,啟動應用程序時,Hibernate可以生成或更新表。

5-您可以擁有此界面

@GetMapping("/user/{id}")
public List<TaskDTO> getTasks(@PathVariable Long id)

然后,我認為您無法避免對某種標准查詢進行編碼。

6-通過使用cascade = CascadeType.ALL配置關系來完成

1-我在做什么錯? 我只想將具有所有者ID的任務添加到數據庫,但是它會返回null作為ownerid

首先,我將確保所有者被持久保存在數據庫中,只是為了確保您具有要引用的值

2-我應該首先使用SQL創建表

由於您使用的是ORM,因此編寫SQL查詢將無法達到目的,但您不必這樣做,因為已經指定了關系

3-我應該在TaskDAO中更改保存方法嗎?

4-我應該更改控制器方法(使用RESTcall的createTask方法)

我認為最好更改您的createTask方法,可以將用戶ID包含為pathvariable或queryparameter,在該方法中,您可以使用其ID查找用戶並在任務中設置用戶字段,然后再將其傳遞給dto到保存值。 oid為null的原因是因為那里沒有這樣的字段。

5-假設以上所有問題均已解決。 如何獲取用戶的所有任務?

在您的任務庫中,您可以創建類似

Collection<Task> findAllTasksByOwnerId(Long id);

6-刪除用戶后如何刪除任務(SQL中為小寫,但Hibernate中有任何方法)

您可以在指定任務和用戶之間的關系的地方指定級聯類型

您可以查看此鏈接以獲取有關如何在春季級聯的簡單教程

The hibernate builds table and foreign keys automatically.Complex queries we can write in repo/controller in hibernate syntax.
With Crud repository we can delete , create update and read data easily.

    for example we have student to course one to many relation.

@OneToMany
@JoinColumn(name = "studentId", referencedColumnName = "studentId", insertable = false, updatable = false)
private List<StudentCourses> studentCourses;

in StudentController I will write

    @CrossOrigin(origins = "http://localhost:8090")
    @RequestMapping(value = "/registerStudentCourse",  method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = 
            MediaType.APPLICATION_JSON_VALUE )
    public StudentCourses registerStudentCourse(@RequestBody StudentCourses studentCourse) {
        if (studentCourse != null) {
            studentCourse.setLastupdated(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
            studentCourse = studentCourseRepository.save(studentCourse);
        }
        return studentCourse;
    }

    @CrossOrigin(origins = "http://localhost:8090")
    @RequestMapping(value = "/findStudentCourses",  method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = 
            MediaType.APPLICATION_JSON_VALUE )
    public List<StudentCourses> findStudentCourses(@RequestBody String studentId) {
        List<StudentCourses> courses = new ArrayList<>();
        JSONObject requestedJSONObject;
        try {
            requestedJSONObject = new JSONObject(studentId);
            String student = requestedJSONObject.getString("studentId");
            courses = 
 studentCourseRepository.findCoursesByStudent(Long.parseLong(student));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
        }
        return courses;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM