【发布时间】:2017-04-28 14:41:59
【问题描述】:
我正在创建一个应用程序,它使用员工和班次之间的多对多关系。但是,我很难理解如何将员工分配/连接到轮班。
@Data
@Entity
public class Employee {
private @Id @GeneratedValue long employeeID;
private String Name;
@OneToMany(cascade = CascadeType.ALL)
private Set<Shift> shifts;
private Employee() {
}
public Employee(long employeeID, String Name) {
this.employeeID = employeeID;
this.Name = Name;
}
public Employee(long employeeID, String Name, Set<Shift> shifts) {
this.employeeID = employeeID;
this.Name = Name;
this.shifts = shifts;
}
public void setShift(Set<Shift> shifts) {
this.shifts = (Set<Shift>) shifts;
}
}
@Data
@Entity
public class Shift {
private @Id @GeneratedValue long Id;
private String shifts;
private Set<Employee> employee;
private Shift() {
}
public Shift(String shifts) {
this.shifts = shifts;
}
public Shift(String shiftPeriod,Set<Employee> employee ) {
this.shifts = shifts;
this.employee=employee;
}
public void setEmployee(Set<Employee> employee) {
this.employee = employee;
}
}
@Component
public class DatabaseLoader implements CommandLineRunner {
private final EmployeeRepository repository;
@Autowired
public DatabaseLoader(EmployeeRepository repository) {
this.repository = repository;
}
@Override
public void run(String... strings) throws Exception {
Shift shift = new Shift("Friday Morning");
Employee employee = new Employee(0001, "Adam Smith");
employee.setShift(shift);
this.repository.save(employee);
}
}
public interface ShiftRepository extends CrudRepository<Shift, Long>
public interface EmployeeRepository extends CrudRepository<Employee, Long>
添加到员工和班次中的实体已保存,但有没有办法可以在 DatabaseLoader 类中为员工分配班次,因为我一直在寻找解决方案。
我知道我没有包含尝试连接员工和轮班的方法,但我不知道如何解决这个问题。
提前致谢
**编辑:我现在遇到的新问题是在春季尝试部署时收到以下消息:
无法构建 Hibernate SessionFactory:无法确定类型:java.util.Set,表:shift,列:[org.hibernate.mapping.Column(employee)]
【问题讨论】:
-
在 JPA 中,我总是将多对多分解为一对多和多对一,它可以让您更好地控制级联,并且在以下情况下更容易移动关系映射表是显式的。
标签: java spring jpa spring-data-jpa h2