2015-03-03 53 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