JPA 一對(duì)多映射標(biāo)記順序列示例

2018-02-23 17:42 更新

JPA教程 - JPA一對(duì)多映射標(biāo)記順序列示例


以下代碼顯示如何在一對(duì)多映射中標(biāo)記順序列。

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

例子

以下代碼來(lái)自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;
    }    
}

以下代碼來(lái)自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;
    }
}

下面的代碼來(lái)自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

以下是數(shù)據(jù)庫(kù)轉(zhuǎn)儲(chǔ)。

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)