带有JPA的Java EE,生成了奇怪的数据库

时间:2014-08-21 15:02:45

标签: mysql java-ee jpa glassfish-3 netbeans-8

我试图通过自己制作一些POC来了解JPA是如何工作的。

我创建了一些类似的实体:

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

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    private String firstName;

    private String lastName;

    @ManyToMany
    @JoinTable(name="SKILLS_EMPLOYEES")
    private List<Skill> skills;

    @ManyToOne
    private Company company;


    public Employee() {
    }

    public Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

//[..getters & setters...]

    public void addSkill(Skill skill) {
        this.skills.add(skill);
        skill.addEmployee(this);
    }

    public void setCompany(Company company) {
        this.company = company;
        this.company.addEmployee(this);
    }

}


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

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    private String companyName;

    private List<Employee> employee;

    public Company() {
    }

    public Company(String companyName) {
        this.companyName = companyName;
    }

//[..getters & setters...]

    public void setEmployee(List<Employee> employee) {
        this.employee = employee;
    }

    public void addEmployee(Employee employee) {
        this.employee.add(employee);
    }
}

因此,公司可以拥有员工,员工只能拥有一家公司,但在我的数据库中,glasshfish在员工和公司之间创建了一个表格。

员工:

  • ID
  • FIRSTNAME
  • LASTNAME
  • COMPANY_ID

公司:

  • ID
  • COMPANYNAME

Company_Employee:

  • COMPANY_ID
  • 的Employee_ID

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您忘了告诉JPA company.employeesemployee.company的反面:

@OneToMany(mappedBy = "company")
private List<Employee> employees;

请注意,我在字段名称中添加了s。这是一份员工名单,因此有很多员工。