2015-03-03 54 views
0

我尝试通过jpa-hibernate获取数据,但是我得到一个错误。
这里我的东西:我有jpa-hibernate中的“没有会话”错误

USER_ROLE

user_role_id username ROLE 
2 petroff ROLE_ADMIN 

用户

id username password salt email profile phone repassword 
6 petroff  12345  ${config.salt} [email protected]еуые.com test petroff prifile "" 12345 

部件类用户

@Entity 
@Table(name = "tbl_user") 
@Repassword(pass = "password", repass = "repassword") 
public class User { 

    @Id 
    @Column(name = "id") 
    private int id; 
    @NotNull 
    @Size(min = 2, max = 64) 
    @Column(name = "username") 
    private String username; 
    @NotNull 
    @Size(min = 2, max = 64) 
    @Column(name = "password") 
    private String password; 
    @Column(name = "salt") 
    private String salt; 
    @Email 
    @Column(name = "email") 
    private String email; 
    @NotEmpty 
    @Column(name = "profile") 
    private String profile; 
    private String repassword; 
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") 
    private Set<UserRole> userRole = new HashSet<UserRole>(); 

    public Set<UserRole> getUserRole() { 
     return userRole; 
    } 

    public void setUserRole(Set<UserRole> userRole) { 
     this.userRole = userRole; 
    } 

部件类的UserRole

@Entity 
@Table(name = "user_roles") 
public class UserRole { 

    @Id 
    @Column(name = "user_role_id") 
    private Integer userRoleId; 
    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "username", nullable = false) 
    private com.blog.blog.entity.User user; 
    @Column(name = "role", nullable = false, length = 45) 
    private String role; 

    //getter and setter methods 
    public Integer getUserRoleId() { 
     return userRoleId; 
    } 

    public void setUserRoleId(Integer userRoleId) { 
     this.userRoleId = userRoleId; 
    } 

调用方法

@Autowired 
UserService us; 

@RequestMapping(value = "/test", method = RequestMethod.GET) 
    public String printHello(ModelMap model, HttpSession session) { 

     com.blog.blog.entity.User u = us.getByUserName("petroff"); 
     Set<UserRole> userRoles = u.getUserRole(); 
     return "hello"; 
    } 

服务

@Service 
@Transactional(readOnly = true) 
public class UserServiceImpl implements UserService { 

    @Autowired 
    private UserRepository userRepository; 
    @PersistenceContext 
    private EntityManager entityManager; 

    @Override 
    public User addUser(User u) { 
     User savedUser = userRepository.saveAndFlush(u); 
     return savedUser; 
    } 

    @Override 
    public void delete(Integer id) { 
     userRepository.delete(id); 
    } 

    @Override 
    public User editUser(User u) { 
     return userRepository.saveAndFlush(u); 
    } 

    @Override 
    public List<User> getAll() { 
     return userRepository.findAll(); 
    } 

    @Override 
    public User getByUserName(String name) { 
     return userRepository.findByUserName(name); 
    }  
} 

配置文件

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
      http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> 
    <bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
      p:location="/WEB-INF/config.properties"/> 
    <context:component-scan base-package="com.blog.blog.service.impl"/> 
    <jpa:repositories base-package="com.blog.blog.repositories"/> 

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="${jdbc.drivers}"/> 
     <property name="url" value="${jdbc.url}"/> 
     <property name="username" value="${jdbc.username}"/> 
     <property name="password" value="${jdbc.password}"/> 
    </bean> 

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
     <property name="showSql" value="true"/> 
     <property name="generateDdl" value="true"/> 
     <property name="database" value="MYSQL"/> 
    </bean> 

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
     <property name="dataSource" ref="dataSource"/> 
     <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> 
     <!-- spring based scanning for entity classes--> 
     <property name="packagesToScan" value="com.blog.blog.entity"/> 
    </bean> 
    <tx:annotation-driven/> 
    <bean id="userDetailsService" 
      class="com.blog.blog.service.impl.UserDetailsImpl"> 
    </bean> 
    <import resource="spring-security.xml"/> 

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/> 

    <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
     <tx:attributes> 
      <tx:method name="get*" read-only="true"/> 
      <tx:method name="find*" read-only="true"/> 
      <tx:method name="*"/> 
     </tx:attributes> 
    </tx:advice> 

    <bean id="sessionFactory" class="org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean"> 
     <property name="entityManagerFactory" ref="entityManagerFactory"/> 
    </bean> 

    <aop:config> 
     <aop:pointcut id="userServicePointCut" 
         expression="execution(* com.blog.blog.service.impl.*Service.*(..))"/> 
     <aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut"/> 

    </aop:config> 
</beans> 

我得到用户OBJ

com.blog.blog.entity.User u = us.getByUserName("petroff"); 

但是当我打电话

Set<UserRole> userRoles = u.getUserRole(); 

我得到了一个错误:

Exception occurred in target VM: failed to lazily initialize a collection of role: com.blog.blog.entity.User.userRole, could not initialize proxy - no Session 
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.blog.blog.entity.User.userRole, could not initialize proxy - no Session 
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566) 
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186) 
    at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:137) 
    at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:156) 
    at com.blog.blog.controller.Main.printHello(Main.java:37) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) 
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) 
    at 
+0

删除了用户介绍,清理了代码,格式化了问题 – CSchulz 2015-03-06 08:02:37

回答

0

您需要在服务初始化延迟集合,如果你想使用它的调用者侧。试试这个

@Override 
public User getByUserName(String name) { 
    User u = userRepository.findByUserName(name); 
    Hibernate.initialize(u.getUserRole()); 
    return u; 
} 

在网上有很多关于这个主题的讨论,如果你想了解更多关于这个主题的背景信息,请看它。

+0

是的,我试过了,现在我没有得到错误,但返回的结果等于“0” – 2015-03-03 15:04:11

+0

打开SQL日志记录,直接执行生成的查询在数据库上查看它是否返回任何结果。另外,发布'UserRepository#findByUserName(name)'的代码,也许这就是问题所在。 – 2015-03-03 15:08:11

+0

信息:Hibernate:选择user0_.id为id1_1_,user0_.email为email2_1_,user0_.password为password3_1_,user0_.profile为profile4_1_,user0_.repassword为repasswo5_1_,user0_.salt为salt6_1_,user0_.username为username7_1_,来自tbl_user user0_其中user0_.username =? 信息:休眠:选择userrole0_.username作为username3_1_1_,userrole0_.user_role_id作为user_rol1_2_1_,userrole0_.user_role_id作为user_rol1_2_0_,userrole0_.role作为role2_2_0_,userrole0_.username作为username3_2_0_从user_roles userrole0_ where userrole0_.username =? – 2015-03-03 15:19:44