当前位置: 首页 > 知识库问答 >
问题:

JPA命名查询中的ManyToOne关系

陶乐生
2023-03-14

我是JPA新手,现在学习如何通过manytone关系连接两个表。我得到的实体来自数据库。我有两张桌子,分别是Department和Employee。许多员工属于一个部门。

部门

@Entity
@Table(name = "DEPARTMENT")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Department.findAll", query = "SELECT d FROM Department d")
    , @NamedQuery(name = "Department.findById", query = "SELECT d FROM Department d WHERE d.id = :id")
    , @NamedQuery(name = "Department.findByName", query = "SELECT d FROM Department d WHERE d.name = :name")})
public class Department implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Column(name = "NAME")
    private String name;
    @OneToMany(mappedBy = "departmentId")
    private Collection<Employee> employeeCollection;

    public Department() {
    }

    public Department(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @XmlTransient
    public Collection<Employee> getEmployeeCollection() {
        return employeeCollection;
    }

    public void setEmployeeCollection(Collection<Employee> employeeCollection) {
        this.employeeCollection = employeeCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Department)) {
            return false;
        }
        Department other = (Department) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Department[ id=" + id + " ]";
    }

}

雇员

@Entity
@Table(name = "EMPLOYEE")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
    , @NamedQuery(name = "Employee.findByEid", query = "SELECT e FROM Employee e WHERE e.eid = :eid")
    , @NamedQuery(name = "Employee.findByDeg", query = "SELECT e FROM Employee e WHERE e.deg = :deg")
    , @NamedQuery(name = "Employee.findByEname", query = "SELECT e FROM Employee e WHERE e.ename = :ename")
    , @NamedQuery(name = "Employee.findBySalary", query = "SELECT e FROM Employee e WHERE e.salary = :salary")})
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "EID")
    private Integer eid;
    @Column(name = "DEG")
    private String deg;
    @Column(name = "ENAME")
    private String ename;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Column(name = "SALARY")
    private Double salary;
    @JoinColumn(name = "DEPARTMENT", referencedColumnName = "ID")
    @ManyToOne
    private Department department;

    public Employee() {
    }

    public Employee(Integer eid) {
        this.eid = eid;
    }

    public Integer getEid() {
        return eid;
    }

    public void setEid(Integer eid) {
        this.eid = eid;
    }

    public String getDeg() {
        return deg;
    }

    public void setDeg(String deg) {
        this.deg = deg;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (eid != null ? eid.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Employee)) {
            return false;
        }
        Employee other = (Employee) object;
        if ((this.eid == null && other.eid != null) || (this.eid != null && !this.eid.equals(other.eid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Employee[ eid=" + eid + " ]";
    }
}

多对一

public class ManyToOne {

    public static void main(String[] args) {
        EntityManagerFactory emfactory = Persistence.
                createEntityManagerFactory("JoinTablePU");
        EntityManager entitymanager = emfactory.
                createEntityManager();
        entitymanager.getTransaction().begin();

        //Create Department Entity
        Department department = new Department();
        department.setName("Development");
        //Store Department
        entitymanager.persist(department);

        //Create Employee1 Entity
        Employee employee1 = new Employee();
        employee1.setEname("Satish");
        employee1.setSalary(45000.0);
        employee1.setDeg("Technical Writer");
        employee1.setDepartment(department);

        //Create Employee2 Entity
        Employee employee2 = new Employee();
        employee2.setEname("Krishna");
        employee2.setSalary(45000.0);
        employee2.setDeg("Technical Writer");
        employee2.setDepartment(department);

        //Create Employee3 Entity
        Employee employee3 = new Employee();
        employee3.setEname("Masthanvali");
        employee3.setSalary(50000.0);
        employee3.setDeg("Technical Writer");
        employee3.setDepartment(department);

        //Store Employees
        entitymanager.persist(employee1);
        entitymanager.persist(employee2);
        entitymanager.persist(employee3);

        entitymanager.getTransaction().commit();
        entitymanager.close();
        emfactory.close();
    }
}

错误

Exception Description: The attribute [employeeCollection] in entity class [class entity.Department] has a mappedBy value of [departmentId] which does not exist in its owning entity class [class entity.Employee]. If the owning entity class is a @MappedSuperclass, this is invalid, and your attribute should reference the correct subclass.
    at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
    at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:107)
    at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at jointable.ManyToOne.main(ManyToOne.java:22)

共有2个答案

曾高杰
2023-03-14

mappedBy属性用于表示双向关系中的反向字段。它标识从数据库检索部门实体时,employeeCollection将自动填充。在您的情况下,它应该是mappedBy=department

查看此链接可以找到形成双向关系的员工-部门模型的精确表示及其详细描述。

通建安
2023-03-14

应该是的

@OneToMany(mappedBy = "department")
    private Collection<Employee> employeeCollection;

mappedBy=“department”属性指定私有部门字段拥有关系(即,包含用于查询以查找部门所有员工的外键)。

在这里你可以找到类似的例子

 类似资料:
  • 错误: beanCreationException:创建名为“post repository”的bean时出错:FactoryBean在创建对象时引发异常;嵌套异常为java.lang.IllegalArgumentException:无法为方法public抽象org.springframework.data.domain.page com.example.forumproject.authent

  • 问题内容: 我有一个抽象的DAO类,它使用参数化类型(实体)和(主键)。在每个实体中我都有一个。我想动态调用此命名查询而不知道其确切名称和参数名称。 例如,假设以下实体 和这个 我应该如何实现该方法,以便不需要知道确切的名称和参数名称? 问题答案: 在您的示例中,命名查询的命名约定通常为“ City.findByName”,因此,我将尝试更改命名查询以遵循此模式。然后,此查询的参数也应具有相同的名

  • 我们希望将字符串列表传递到名为JPA的本机查询中。我们如何才能做到这一点。它正在引发无效的查询参数异常。

  • 我正在开发一个人力资源管理应用程序,所以我对如何通过JPA管理实体感到困惑。 我的情况是一组多语言上下文中的表:-employees-departments-languages-departments_languages 在我的数据库表之后: 从这个查询中,我需要员工信息,以及部门名称(假设languageId为1) 从eclipse JPA控制台执行查询将返回一个Employee对象,该对象具有

  • 这个问题已经问过了:Spring data-ignore参数,如果它有一个空值和一个创建的票证,datajpa-209。 只要这个问题是近3年前的问题,而且票证可以追溯到2012年,我就想问是否有一种更舒适和通用的方法来避免处理和复制存储库方法的开销。2个这样的参数的解决方案看起来是可以接受的,但是我想实现4-5个参数的非常相同的过滤。

  • 所以我在网上搜索了我的问题的答案,但没有找到有帮助的东西,基本上是需要在两个类之间有一个ManyToOne关系,其中一个类有一个EmbeddedId,我要把代码留在这里,错误信息是它给(我使用野蝇来运行服务器)。 公共类InventoryPK实现可序列化{ } @实体@Table(name=“inventario”,schema=“mxnextmob”) 公共类库存扩展基本模型{ } 公共类公司扩