我还没有任何与 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 */
}
院系类(class)
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*/
}
公司数据库
public class CompanyDB {
public boolean createCompany(Company company) throws SQLException {
String sql_query = "INSERT INTO " + DB_NAME + ".company VALUES (?, ?, ? )";
}
//other crud methods
}
部门数据库
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`)
);
最佳答案
您可能想要查看 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 将通过在部门表(在公司的主键上)上创建一个列来自动将公司与所有部门关联起来,以便它可以将所有部门与所述公司关联起来。
关于java - 在数据库中保留java实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997449/