使用Spring-Data-JPA进行Hibernate映射

时间:2015-02-02 20:33:13

标签: hibernate spring-data-jpa

我正在尝试使用Hibernate Table Per Subclass来解决我遇到的问题。我有一个Office和Employee类都使用的Workday。

@Table(name="WorkDay")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractWorkday {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long workdayId;

    @Column(nullable = false)
    private boolean active;

    @Enumerated(EnumType.STRING)
    private DayOfWeek dayOfWeek;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalTime")
    private LocalTime startTime;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalTime")
    private LocalTime endTime;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalTime")
    private LocalTime breakStartTime;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalTime")
    private LocalTime breakEndTime;
//getters and setters
}

然后是两个特定于Office和Employee的继承类

@Entity
@Table(name="EMPLOYEEWORKDAY")
@PrimaryKeyJoinColumn(name="workday_id")
public class EmployeeWorkday extends AbstractWorkday {

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "employeeId", nullable = false)
    private Employee employee;

@Entity
@Table(name="OFFICEWORKDAY")
@PrimaryKeyJoinColumn(name="workday_id")
public class OfficeWorkday extends AbstractWorkday {

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "officeId", nullable = false)
    private Office office;

然后我将每一个用作:

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


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long employeeId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "officeId", nullable = false)
    private Office office;

    @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch =    FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    List<EmployeeWorkday> workDays = new ArrayList<EmployeeWorkday>(); 
...
}

@Entity
@Table(name = "OFFICE")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "officeId")
public class Office {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long officeId;

    @OneToMany(mappedBy = "office", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    private List<Employee> employees = new ArrayList<Employee>();

     @OneToMany(mappedBy = "office", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    List<OfficeWorkday> workDays = new ArrayList<OfficeWorkday>();

我想解决的问题是Office和员工都有工作日。但由于我们之间的双向映射,将工作日分成不同类型似乎更好。

然而,这“感觉”错了。我正在尝试做多租户,以便员工和工作日可以通过办公室隔离。但这似乎很复杂,我一直在追逐休眠问题,比如当我做一个findOffice时,我得到了正确的办公室,其工作日,然后是正确的员工,但他们的工作日是空的 - 即使我看到它们仍然存在。

任何人都可以识别出这种代码气味并为其提供最佳解决方案吗?

0 个答案:

没有答案