spring-boot控制器中的持久实体

时间:2017-07-11 07:28:50

标签: java spring hibernate jpa

我正在使用spring-bootsping-data开发Hibernate个应用程序。我创建了一些具有OneToManyManyToMany等关联的实体,如:

@Entity
public class Department {

@OneToMany(mappedBy="department", cascade=CascadeType.ALL)
private Set<Employee> employees;

public void addEmployee(Employee emp) {
  emp.setDepartment(this);
  employees.add(emp);
}

}
默认FetchType OneToMany的{​​{1}} LAZY位于JPAHibernate。我使用Department的方法在Transactional Service内使用实体JpaRepository加载:

@Service
@Transactional
public class DepartmentService {

DepartmentRepository repo;

public Department findById(Long id) {
  return repo.findOne(id);
}

}

public interface DepartmentRepository extends JpaRepository {

}

当我在@ControllerPOST方法中使用GET注释的类中加载实体时:

public class DepartmentController {

DepartmentService departmentService;

@RequestMapping(value = "/admin/departments/{did}", method = RequestMethod.POST)
    public String update() {
 Department dep = departmentService.findById(did);
 dep.add(new Employee());

  ...

}

}

然后我可以访问这些关联,我可以将Employees添加到Department。实体似乎是persistent而不是detached。 当我在Unit Test中执行相同操作时,实体Departmentdetached我获得LazyInitializationException,除非我使用{{1注释Unit Test类}}。我没有在@Transactional配置中设置OpenSessionInViewFilter。为什么Spring / Hibenate中的实体是持久性的?

0 个答案:

没有答案