我正在使用Spring框架4.0.5和Spring Data jpa 1.3.5开发GAE。 我'尝试检索OneToMany关系中的对象列表,但我收到以下错误:
您刚刚尝试访问字段" organizationMemberships"分离对象时,此字段未分离。要么不访问此字段,要么在分离对象时将其分离。
用户实体是:
@Entity
@Table(name="users")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Long id;
private String email;
private String password;
private String salt;
private String slug;
private int status;
private String username;
//bi-directional one-to-one association to UserContact
@OneToOne(mappedBy="user")
private UserContact userContact;
//bi-directional one-to-one association to UserDetail
@OneToOne(mappedBy="user", cascade = CascadeType.ALL)
private UserDetail userDetail;
//bi-directional many-to-one association to UsersApisession
@OneToMany(mappedBy="user")
private List<UsersApisession> usersApisessions;
@OneToMany(mappedBy="user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<OrganizationMember> organizationMemberships;
...
}
虽然OrganizationMember是:
@Entity
@Table(name="organization_members")
@NamedQuery(name="OrganizationMember.findAll", query="SELECT o FROM OrganizationMember o")
public class OrganizationMember implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
private Long id;
private String email;
private int status;
//bi-directional many-to-one association to Organization
@ManyToOne
private Organization organization;
//bi-directional many-to-one association to User @JoinColumn(name="member_id")
@ManyToOne(fetch = FetchType.LAZY)
private User user;
//bi-directional many-to-one association to OrganizationPosition
@ManyToOne
@JoinColumn(name="position_id")
private OrganizationPosition organizationPosition;
...
}
我的userRepository是一个根据Spring JPA的接口:
@Transactional
public interface UserRepository extends JpaRepository<User, Long>{
User findByEmail(String email);
User findBySlug(String slug);
}
我的控制器的代码如下:
@Controller
public class ProtectedSiteController {
...
@Autowired
private UserRepository userRepo;
@RequestMapping(method = RequestMethod.GET, value="/afterLogin")
public String afterLogin(HttpServletRequest request, HttpServletResponse response){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userRepo.findByEmail(auth.getName());
List<OrganizationMember> memberList = user.getOrganizationMemberships();
...
}
}
这是我的交易配置:
@Configuration
@EnableJpaRepositories("com.example.repository")
@EnableTransactionManagement
public class JpaApplicationConfig {
private static final Logger logger = Logger
.getLogger(JpaApplicationConfig.class.getName());
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
Map<String, String> map = new HashMap<String, String>();
map.put("datanucleus.NontransactionalRead","true");
map.put("datanucleus.NontransactionalWrite","false");
map.put("datanucleus.storeManagerType","rdbms");
map.put("datanucleus.autoCreateSchema" ,"false");
map.put("datanucleus.validateTables" ,"false");
map.put("datanucleus.validateConstraints" ,"false");
map.put("datanucleus.jpa.addClassTransformer" ,"true");
map.put("datanucleus.singletonEMFForName", "true");
LocalContainerEntityManagerFactoryBean lce= new LocalContainerEntityManagerFactoryBean();
lce.setPersistenceProviderClass(org.datanucleus.api.jpa.PersistenceProviderImpl.class);
DriverManagerDataSource dmds = new DriverManagerDataSource();
dmds.setDriverClassName("com.mysql.jdbc.Driver");
dmds.setUrl("jdbc:mysql://localhost:3306/example");
dmds.setUsername("example");
dmds.setPassword("example");
lce.setDataSource(dmds);
lce.setPackagesToScan("com.example.models");
lce.setJpaPropertyMap(map);
lce.setLoadTimeWeaver(new org.springframework.instrument.classloading.SimpleLoadTimeWeaver());
return lce;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
logger.info("Loading Transaction Manager...");
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
@Bean
public PersistenceAnnotationBeanPostProcessor postProcessor(){
return new PersistenceAnnotationBeanPostProcessor();
}
}
我跟随GAE教程要么是Spring教程。我的错是什么? 谢谢。
答案 0 :(得分:1)
快速技巧是
使用方法afterLogin(..)@Transactional
..
问题是当用户返回时,事务被关闭,因此无法检索组织成员资格(已分离)。
另一个解决方案是更改EAGER中的获取类型,默认情况下@OneToMany
为LAZY。
@Service
public class ServiceClass {
...
@Autowired
private UserRepository userRepo;
@Transactional
public List<OrganizationMember> method(String name){
User user = userRepo.findByEmail(name);
return user.getOrganizationMemberships();
}
}
@Controller
public class ProtectedSiteController {
...
@Autowired
private ServiceClass serviceClass;
@RequestMapping(method = RequestMethod.GET, value="/afterLogin")
public String afterLogin(HttpServletRequest request, HttpServletResponse response){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<OrganizationMember> memberList = serviceClass.method(auth.getName());
...
}
}
我希望我已经向你提供了有关你问题的所有答案。