如何使用Hibernate注释@manytone和@OneToMany进行关联

如何使用Hibernate注释@manytone和@OneToMany进行关联,hibernate,Hibernate,我正在使用本教程学习Spring、Hibernate和Maven:。工作正常,但我需要建立一对多关系(一名员工有许多任务)。我尝试了许多示例,但仍然不知道如何使我的代码工作: Employee.java: package com.giantflyingsaucer.simplespringhibernate.entity; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Enti

我正在使用本教程学习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;
    }
}
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;}

}
<?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 />
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
);
db config.xml:

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;
    }
}
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;}

}
<?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 />
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;
}
//Employee.java:
@OneToMany(fetch=FetchType.LAZY,mappedBy=“employees”)
公共列表getTasks(){
返回此任务;
}
公共任务(列出任务){
这个。任务=任务;
}
//Task.java:
@manytone(fetch=FetchType.LAZY)
@JoinColumn(name=“TaskSideEmployees”)
公共雇员{
将此文件退还给员工;
}
公共作废设置员工(员工){
this.employee=employee;
}

问题在于:

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

注意,LAZY是许多关联的默认值,因此没有必要指定它

虽然使用双向关系可能被认为是一个“bug”,但如果不这样做,可能会出现许多意想不到的问题。Hibernate将在单向映射中进行更多查询调用,并可能创建意外的表。请阅读此处了解更多信息: