JPA 一对多映射标记顺序列示例

JPA教程 – JPA一对多映射标记顺序列示例

以下代码显示如何在一对多映射中标记顺序列。

@OneToMany(mappedBy="queue")
@OrderColumn(name="PRINT_ORDER")
private List<PrintJob> jobs;

例子

以下代码来自PrintJob.java。

package cn.w3cschool.common;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class PrintJob {
    @Id private int id;

    @ManyToOne
    private PrintQueue queue;

    public int getId() {
        return id;
    }

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

    public PrintQueue getQueue() {
        return queue;
    }

    public void setQueue(PrintQueue queue) {
        this.queue = queue;
    }    
}

以下代码来自PrintQueue.java。

package cn.w3cschool.common;

import java.util.List;
import java.util.ArrayList;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;

@Entity
public class PrintQueue {
    @Id private String name;

    @OneToMany(mappedBy="queue")
    @OrderColumn(name="PRINT_ORDER")
    private List<PrintJob> jobs;

    public PrintQueue() {
        jobs = new ArrayList<PrintJob>();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<PrintJob> getJobs() {
        return jobs;
    }

    public void addJob(PrintJob job) {
        this.jobs.add(job);
        job.setQueue(this);
    }

    public String toString() {
        return "PrintQueue: " + name;
    }
}

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test() {
    PrintQueue q = new PrintQueue();
    q.setName("q1");

    PrintJob j = new PrintJob();
    j.setId(1);
    j.setQueue(q);

    q.getJobs().add(j);
    em.persist(j);
    em.persist(q);
  }

  @PersistenceContext
  private EntityManager em;
}

下载 Persist_OrderedList.zip

以下是数据库转储。

Table Name: PRINTJOB
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: QUEUE_NAME,
    Column Type: VARCHAR:
    Column Value: q1

    Column Name: PRINT_ORDER,
    Column Type: INTEGER:
    Column Value: 0

Table Name: PRINTQUEUE
 Row:
    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: q1
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《JPA 一对多映射标记顺序列示例》
文章链接:https://zhuji.vsping.com/293523.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。