hibernate - 如何使用Hibernate批注@ManyToOne和@OneToMany进行关联

标签 hibernate

我正在使用此教程Chad Lung: A project using Netbeans 7, JUnit, Maven, HSQLDB, Spring and Hibernate学习Spring,Hibernate,Maven。可以,但是我需要建立一对多关系(一个员工有很多任务)。我已经尝试了许多示例,但仍然不知道如何使代码正常工作:

Employee.java:

package com.giantflyingsaucer.simplespringhibernate.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "Employees")
public class Employee implements Serializable {

    private Integer employeeId;
    private List<Task> tasks;

    @Id
    @Column(name = "idEmployees", nullable=false)
    public Integer getEmployeeId() {
        return this.employeeId;
    }

    public void setEmployeeId(Integer employeeId) {
        this.employeeId = employeeId;
    }

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name="idEmployees")
    public List<Task> getTasks() {
        return tasks;
    }
}

Task.java:
package com.giantflyingsaucer.simplespringhibernate.entity;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "Tasks")
public class Task implements Serializable {

    private Integer taskId;
    private Employee employee;


    @Id
    @Column(name = "idTasks", nullable=false)
    public Integer getTaskId() {
        return this.taskId;
    }

    public void setTaskId(Integer taskId) {
        this.taskId = taskId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "TasksIdEmployees")
    public Employee getEmployee() {return employee;}

}

db-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">

    <property name="driverClass">
        <value>${jdbc.driver.className}</value>
    </property>
    <property name="jdbcUrl">
        <value>${jdbc.url}</value>
    </property>
    <property name="user">
        <value>${jdbc.username}</value>
    </property>
    <property name="password">
        <value>${jdbc.password}</value>
    </property>
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="packagesToScan" value="com.giantflyingsaucer.simplespringhibernate.entity" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">false</prop>
        </props>
    </property>
</bean>
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>
<tx:annotation-driven />

MySQL表:
CREATE TABLE employees (
`idEmployees` int(11) NOT NULL,
PRIMARY KEY (`idEmployees`)
);

CREATE TABLE tasks (
`idTasks` int(11) NOT NULL,
`TasksIdEmployees` int(11) DEFAULT NULL,
PRIMARY KEY (`idTasks`),
KEY `FkTasksEmployees_idx` (`TasksIdEmployees`),
CONSTRAINT `FkTasksEmployees` FOREIGN KEY (`TasksIdEmployees`) REFERENCES `employees`   (`idEmployees`) ON DELETE NO ACTION ON UPDATE NO ACTION
);

非常感谢!

我通过在NetBeans中自动生成映射文件和POJO找到了答案:
// Employee.java:
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
    public List<Task> getTasks() {
        return this.tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }

// Task.java:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TasksIdEmployees")
public Employee getEmployees() {
    return this.employee;
}

public void setEmployees(Employee employee) {
    this.employee = employee;
}

最佳答案

出问题的是以下内容:

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="idEmployees")
public List<Task> getTasks() {
    return tasks;
}

这是错误的,原因有两个。
  • @JoinColumn(name="idEmployees")的意思是:此OneToMany使用名为idEmployees的连接列(即外键)进行映射。但是联接列未命名为idEmployees。 idEmployees是Employee表的主键。连接列名称为TasksIdEmployees。输入正确的名称将使映射对于单向OneToMany关联正确。但是关联是双向的,这导致了第二个原因...
  • 在双向关联中,不需要(这是一个错误)在关联的两侧重复映射信息。一方(多方)必须是关联的所有者并定义映射。另一边必须是反面,只需说一下:去看另一边如何映射此关联。这是使用mapledBy属性完成的,该属性告诉Hibernate关联的另一端的字段或属性的名称:
    @OneToMany(mappedBy = "employee")
    public List<Task> getTasks() {
        return tasks;
    }
    

  • 请注意,LAZY是toMany关联的默认设置,因此没有必要指定它。

    关于hibernate - 如何使用Hibernate批注@ManyToOne和@OneToMany进行关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16511237/

    相关文章:

    hibernate - 在Grails/GORM中使用静态方法findAll关闭

    java - Hibernate:在 Weblogic 中配置数据源后出现错误 "org.hibernate.exception.GenericJDBCException: could not update"

    hibernate - 在grails中,为什么刷新后直接得到StaleObjectStateException?

    java - SpringMVC + Spring Security Hibernate + Thymeleaf - 我的 pom.xml 太多了吗?

    java - Hibernate session 不更新实体

    java - Hibernate 实体等于 var null 而不是 "same scope"中的 null

    java - 通过 SOAP 传输的 JPA 延迟加载集合

    java - 从 tomcat 8 迁移到 jetty 服务器

    java - org.hibernate.hql.internal.ast.QuerySyntaxException :

    postgresql - 在 hibernate 中获取具有时区值的 itimestamp