JPA 覆蓋多對(duì)多映射示例

2018-02-23 16:57 更新

JPA教程 - JPA覆蓋多對(duì)多映射示例


以下代碼使用注釋來(lái)覆蓋多對(duì)多映射的默認(rèn)列。

    @ManyToMany
    @JoinTable(name="DEPT_EMP",
        joinColumns=@JoinColumn(name="DEPT_ID"),
        inverseJoinColumns=@JoinColumn(name="EMP_ID"))
    @AttributeOverrides({
        @AttributeOverride(
            name="first_Name",
            column=@Column(name="EMP_FNAME")),
        @AttributeOverride(
            name="last_Name",
            column=@Column(name="EMP_LNAME"))
    })
    private Map<EmployeeName, Employee> employeesByName;

例子

以下代碼來(lái)自Employee.java。

package cn.w3cschool.common;

import java.util.Collection;
import java.util.ArrayList;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Employee {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @Embedded
    private EmployeeName name;

    private long salary;
    
    @ManyToMany(mappedBy="employeesByName")
    private Collection<Department> departments;

    public Employee() {
        name = new EmployeeName();
        departments = new ArrayList<Department>();
    }
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public EmployeeName getName() {
        return name;
    }

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

    public String getFirstName() {
        return name.getFirst_Name();
    }

    public void setFirstName(String firstName) {
        this.name.setFirst_Name(firstName);
    }

    public String getLastName() {
        return name.getLast_Name();
    }

    public void setLastName(String lastName) {
        this.name.setLast_Name(lastName);
    }

    public long getSalary() {
        return salary;
    }

    public void setSalary(long salary) {
        this.salary = salary;
    }
    
    public Collection<Department> getDepartments() {
        return departments;
    }
    
    public void setDepartments(Collection<Department> departments) {
        this.departments = departments;
    }


    public String toString() {
        StringBuffer aBuffer = new StringBuffer("Employee ");
        aBuffer.append(" id: ");
        aBuffer.append(id);
        aBuffer.append(" name: ");
        aBuffer.append(getLastName());
        aBuffer.append(", ");
        aBuffer.append(getFirstName());
        aBuffer.append(" with deptCount: ");
        if(null != departments) {
            aBuffer.append(departments.size());
        }
        return aBuffer.toString();
    }
}

以下代碼來(lái)自EmployeeName.java。

package cn.w3cschool.common;


import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class EmployeeName {
    @Column(name="F_NAME", insertable=false, updatable=false)
    private String first_Name;
    @Column(name="L_NAME", insertable=false, updatable=false)
    private String last_Name;
    
    public String getFirst_Name() {
        return first_Name;
    }
    public void setFirst_Name(String firstName) {
        first_Name = firstName;
    }
    public String getLast_Name() {
        return last_Name;
    }
    public void setLast_Name(String lastName) {
        last_Name = lastName;
    }
}

下面的代碼來(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() {
    Employee e = new Employee();
    e.setFirstName("Tom");
    e.setLastName("Smith");
    Department d = new Department();
  
    d.setName("test");

    EmployeeName name = new EmployeeName();
    name.setFirst_Name("Tom");
    name.setLast_Name("Smith");
    
    e.getDepartments().add(d);
    
    d.getEmployees().put(name, e);
    
    
    em.persist(e);    
    em.persist(d);
   

  }

  @PersistenceContext
  private EntityManager em;
}

下面的代碼來(lái)自Department.java。

package cn.w3cschool.common;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;


@Entity
public class Department {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;
    
    @ManyToMany
    @JoinTable(name="DEPT_EMP",
        joinColumns=@JoinColumn(name="DEPT_ID"),
        inverseJoinColumns=@JoinColumn(name="EMP_ID"))
    @AttributeOverrides({
        @AttributeOverride(
            name="first_Name",
            column=@Column(name="EMP_FNAME")),
        @AttributeOverride(
            name="last_Name",
            column=@Column(name="EMP_LNAME"))
    })
    private Map<EmployeeName, Employee> employeesByName;
   
    
    public Department() {
        employeesByName = new HashMap<EmployeeName,Employee>();
    }
        
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String deptName) {
        this.name = deptName;
    }
    
    public Map<EmployeeName, Employee> getEmployees() {
        return employeesByName;
    }

    public void addEmployee(Employee employee) {
        EmployeeName empName = employee.getName();
        employeesByName.put(empName, employee);
    }

    public void removeEmployee(Employee employee) {
        Iterator iter = employeesByName.entrySet().iterator();
        while (iter.hasNext()) {
            Employee current = ((Map.Entry<EmployeeName,Employee>) iter.next()).getValue();
            if (current.getId() == employee.getId()) {
                iter.remove();
            }
        }
    }

    public String toString() {
        StringBuffer aBuffer = new StringBuffer("Department ");
        aBuffer.append(" id: ");
        aBuffer.append(id);
        aBuffer.append(" name: ");
        aBuffer.append(name);
        aBuffer.append(" employeeCount: ");
        aBuffer.append(employeesByName.size());
        return aBuffer.toString();
    }
}
下載 ManyToMany_EmbeddableKeyOverride.zip

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

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

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: test





Table Name: DEPT_EMP
 Row:
    Column Name: DEPT_ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: EMP_ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: F_NAME,
    Column Type: VARCHAR:
    Column Value: Tom

    Column Name: L_NAME,
    Column Type: VARCHAR:
    Column Value: Smith





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

    Column Name: F_NAME,
    Column Type: VARCHAR:
    Column Value: null

    Column Name: L_NAME,
    Column Type: VARCHAR:
    Column Value: null

    Column Name: SALARY,
    Column Type: BIGINT:
    Column Value: 0



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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)