简体   繁体   English

了解注释和JPA(休眠)

[英]Understanding annotations and JPA(hibernate)

There is a structure. 有一个结构。 I want to link the three entities in this way: the Company should contain id, name of company and the list of Departments, each Department has a list of Workers, id and name of department. 我想以这种方式链接这三个实体:公司应包含ID,公司名称和部门列表,每个部门都有一个工人列表,ID和部门名称。 Each worker has name, id. 每个工人都有名字,身份证。

+Company
-int companyId
-String companyName
-Set<Department> listOfDepartments = new HashSet<Department>();

+Department
-int departmentId
-String departmentName
-Set<Worker> listOfWorkers = new HashSet<Worker>();

+Worker
-int workerId
-String workerName

I tried to make a connection with the one-to-many and many-to-one, but is not successful. 我试图与一对多和多对一建立联系,但未成功。

Сompany 公司

@Entity
@Table(name="Company")
public class Company {

@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idCompany;
private String companyName;

@OneToMany(mappedBy = "company")
private Set<Department> listOfDepartments = new HashSet<Department>();

Department

@Entity
public class Department {

@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idDepartment;
private String departmentName;

@ManyToOne
@JoinColumn(name="idCompany")
private Company company;

@OneToMany(mappedBy = "department")
private Set<Worker> listOfWorkers = new HashSet<Worker>();

Worker 工人

@Entity
public class Worker {

@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idWorker;
private String workerName;

@ManyToOne
@JoinColumn(name="idDepartment")

I start with: 我从开始:

Session session = sessionFactory.openSession();
        session.beginTransaction();
        Worker worker1 = new Worker("WorkerName1");
        Worker worker2 = new Worker("WorkerName2");
        Worker worker3 = new Worker("WorkerName3");
        Worker worker4 = new Worker("WorkerName4");
        Department department = new Department("Technical");
        department.getListOfWorkers().add(worker1);
        department.getListOfWorkers().add(worker2);
        department.getListOfWorkers().add(worker3);
        department.getListOfWorkers().add(worker4);
        company = new Company("MyCompanyName");
        company.getListOfDepartments().add(department);
        session.save(company);
        session.getTransaction().commit();
        session.close();

It fills company, but not fills other tables and also it's not creating any joins(maps) Error: 它填充公司,但不填充其他表,也没有创建任何联接(映射)错误:

Hibernate: alter table Department drop foreign key FK_l7sg67atqhnn0soqynpvxrtpk
Hibernate: alter table Worker drop foreign key FK_s53hyohtyjy93srd2wkksairk
Hibernate: drop table if exists Company
Hibernate: drop table if exists Department
Hibernate: drop table if exists Worker
Hibernate: create table Company (idCompany integer not null auto_increment, companyName varchar(255), primary key (idCompany))
Hibernate: create table Department (idDepartment integer not null auto_increment, departmentName varchar(255), idCompany integer, primary key (idDepartment))
Hibernate: create table Worker (idWorker integer not null auto_increment, workerName varchar(255), idDepartment integer, primary key (idWorker))
Hibernate: alter table Department add index FK_l7sg67atqhnn0soqynpvxrtpk (idCompany), add constraint FK_l7sg67atqhnn0soqynpvxrtpk foreign key (idCompany) references Company (idCompany)
Hibernate: alter table Worker add index FK_s53hyohtyjy93srd2wkksairk (idDepartment), add constraint FK_s53hyohtyjy93srd2wkksairk foreign key (idDepartment) references Department (idDepartment)
ноя 11, 2013 3:10:31 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Company (companyName) values (?)

In addition to the cascade mentioned in Glenn Lane's answer, you also need to understand how bidirectional associations work. 除了Glenn Lane的答案中提到的级联,您还需要了解双向关联是如何工作的。

They have an owner side, and an inverse side. 它们有一个所有者方面和一个相反方面。 JPA only cares about the owner side to decide which association exists between entities. JPA只关心所有者方面,以决定实体之间存在哪个关联。 The owner side is the one which doesn't have the mappedBy attribute. 所有者端是具有mappedBy属性的端。

Your code add depertments to the company, and workers to the departments, but it only initializes the inverse sides. 您的代码为公司增加了部门,为部门增加了工人,但是仅初始化了反面。 You forgot to initialize the owner side: 您忘记了初始化所有者方:

worker1.setDepartment(department);
worker2.setDepartment(department);
...
department.setCompany(company);

If you want JPA to automatically persist the children, you need to further decorate your @OneToMany : 如果您希望JPA自动保留子级,则需要进一步装饰@OneToMany

@OneToMany(mappedBy = "department", cascade={CascadeType.PERSIST})

If you want cascading behaviour for other operations, like remove, merge, refresh, you'll need to add those to the cascade list as well. 如果要其他操作(例如删除,合并,刷新)的级联行为,则也需要将其添加到级联列表中。

You can use another approach: 您可以使用另一种方法:

Unidirectional OneToMany: http://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Unidirectional_OneToMany.2C_No_Inverse_ManyToOne.2C_No_Join_Table_.28JPA_2.0_ONLY.29 单向OneToMany: http : //en.wikibooks.org/wiki/Java_Persistence/OneToMany#Unidirectional_OneToMany.2C_No_Inverse_ManyToOne.2C_No_Join_Table_.28JPA_2.0_ONLY.29

You still need to persist the Object and then add it into your Collection. 您仍然需要保留对象,然后将其添加到您的集合中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM