我还没有任何关于ORM,Hibernate,JPA等的知识,所以这是一种映射数据库中实体之间关联的有效方法,而不使用它们吗?
感谢。
用户可以注册公司。 每个公司都有很多部门。 每个部门都有很多部门,等等有办公室,员工等。
public class Company{
private String company_name;
private int company_registration_number;
private String company_address;
public Company(String company_name, int crn, String company_address) {
this.company_name = company_name;
this.company_registration_number = crn;
this.company_address = company_address;
}
/* Getters, Setters, toString */
}
系类
public class Department {
private String dept_name;
private String dept_description;
public Department( String dept_name, String dept_description) {
this.dept_name = dept_name;
this.dept_description=dept_description;
}
/*Getters, Setters, toString*/
}
CompanyDB
public class CompanyDB {
public boolean createCompany(Company company) throws SQLException {
String sql_query = "INSERT INTO " + DB_NAME + ".company VALUES (?, ?, ? )";
}
//other crud methods
}
DepartmentDB
public class DepartmentDB {
public boolean createDepartment(Department department, String company_name) throws SQLException {
String sql_query = "INSERT INTO " + DB_NAME +
".department(dept_name, dept_description, company_name)" +
" VALUES(?, ?, ?) " +
" WHERE company_name=?";
}
//other crud methods
}
SQL:
create table `company`(
`company_name` varchar(250),
`company_registration_number` int not null,
`company_address` varchar(250) not null,
primary key(`company_name`)
);
create table `department` (
`dept_id` int auto_increment,
`dept_name` varchar(250) not null unique,
`dept_description` varchar(512) not null,
`company_name` varchar(250),
primary key(`dept_id`) ,
foreign key(`company_name`) references `company`(`company_name`)
);
答案 0 :(得分:2)
您可能想查看Hibernate关系或注释,因为这可以让您的生活更轻松。
请参阅 https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html 或https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/了解一些基础知识。
看起来你已经掌握了基础知识,但是Hibernate / JPA提供的功能只需要创建数据库表和关系或带映射的实体,它将自动为你生成另一半。
您正在尝试做的一个示例
public class Company {
@Id
private Long id;
@Column(name = "company_name")
private String companyName;
@Column(name = "company_registration_number")
private int companyRegistrationNumber;
@Column(name = "company_address")
private String companyAddress;
@OneToMany
private Set<Department> departments;
/* Getters, Setters, toString */
}
和
public class Department {
@Id
private Long id;
@Column(name = "dept_name")
private String deptName;
@Column(name = "dept_description")
private String deptDescription;
@ManyToOne
private Company company;
/*Getters, Setters, toString*/
}
在这种情况下,Hibernate将通过在Department表(在公司的主键上)上创建一个列来自动将公司与所有部门相关联,以便它可以将所有部门与所述公司相关联。
答案 1 :(得分:0)
对于JPA实体映射是通过注释完成的,也可以通过Hibernate插件生成表,请阅读此内容。此链接可能会有助http://docs.jboss.org/tools/latest/en/hibernatetools/html/plugins.html