问题描述:查询用户信息时想级联查出用户订单以及订单详情,在查询用户的时候JDBC是will be managed by Spring,但懒加载用户订单以及订单详情时就will not be managed by Spring
2018-07-30 12:25:33.498 DEBUG [main]org.mybatis.spring.SqlSessionUtils.getSqlSession():104 -Creating a new SqlSession
2018-07-30 12:25:33.502 DEBUG [main]org.mybatis.spring.SqlSessionUtils.getSqlSession():120 -Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62010f5c]
2018-07-30 12:25:33.510 DEBUG [main]org.mybatis.spring.transaction.SpringManagedTransaction.openConnection():86 -JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@558bdf1f] will be managed by Spring
2018-07-30 12:25:33.512 DEBUG [main]com.dsy.dao.UserMapper.selectByPrimaryKey.debug():139 -==>  Preparing: select user_id, user_name, user_password from user where user_id = ? 
2018-07-30 12:25:33.528 DEBUG [main]com.dsy.dao.UserMapper.selectByPrimaryKey.debug():139 -==> Parameters: 1(Integer)
2018-07-30 12:25:33.622 DEBUG [main]com.dsy.dao.UserMapper.selectByPrimaryKey.debug():139 -<==      Total: 1
2018-07-30 12:25:33.637 DEBUG [main]org.mybatis.spring.SqlSessionUtils.closeSqlSession():163 -Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62010f5c]
2018-07-30 12:25:33.637 DEBUG [main]org.mybatis.spring.SqlSessionUtils.beforeCommit():261 -Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62010f5c]
2018-07-30 12:25:33.637 DEBUG [main]org.mybatis.spring.SqlSessionUtils.beforeCompletion():287 -Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62010f5c]
2018-07-30 12:25:33.637 DEBUG [main]org.mybatis.spring.SqlSessionUtils.beforeCompletion():292 -Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@62010f5c]
2018-07-30 12:25:33.637 DEBUG [main]org.mybatis.spring.transaction.SpringManagedTransaction.openConnection():86 -JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@e8df99a] will not be managed by Spring
2018-07-30 12:25:33.637 DEBUG [main]com.dsy.dao.UserOrderMapper.selectByPrimaryKey.debug():139 -==>  Preparing: select order_id, user_id, address_id, total_price, order_time, order_state from user_order where order_id = ? 
2018-07-30 12:25:33.637 DEBUG [main]com.dsy.dao.UserOrderMapper.selectByPrimaryKey.debug():139 -==> Parameters: 1(Integer)
2018-07-30 12:25:33.653 DEBUG [main]com.dsy.dao.UserOrderMapper.selectByPrimaryKey.debug():139 -<==      Total: 1
2018-07-30 12:25:33.653 DEBUG [main]org.mybatis.spring.transaction.SpringManagedTransaction.openConnection():86 -JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@45fd9a4d] will not be managed by Spring
2018-07-30 12:25:33.653 DEBUG [main]com.dsy.dao.OrderItemsMapper.selectByPrimaryKey.debug():139 -==>  Preparing: select item_id, good_id, order_id, buy_num from order_items where item_id = ? 
2018-07-30 12:25:33.653 DEBUG [main]com.dsy.dao.OrderItemsMapper.selectByPrimaryKey.debug():139 -==> Parameters: 1(Integer)
2018-07-30 12:25:33.669 DEBUG [main]com.dsy.dao.GoodMapper.selectByPrimaryKey.debug():139 -====>  Preparing: select good_id, category_id, good_name, good_price, good_img, good_state from good where good_id = ? 
2018-07-30 12:25:33.669 DEBUG [main]com.dsy.dao.GoodMapper.selectByPrimaryKey.debug():139 -====> Parameters: 1(Integer)
2018-07-30 12:25:33.669 DEBUG [main]com.dsy.dao.GoodMapper.selectByPrimaryKey.debug():139 -<====      Total: 1
2018-07-30 12:25:33.669 DEBUG [main]com.dsy.dao.OrderItemsMapper.selectByPrimaryKey.debug():139 -<==      Total: 1
ASUS_001Spring配置
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.dsy.service"/>    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>UserMapper.xml:
<resultMap id="BaseResultMap" type="com.dsy.entity.User" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_password" property="userPassword" jdbcType="VARCHAR" />
      <collection property="orders" column="user_id" select="com.dsy.dao.UserOrderMapper.selectByPrimaryKey" fetchType="lazy"/>
  </resultMap>  <sql id="Base_Column_List" >
    user_id, user_name, user_password
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where user_id = #{userId,jdbcType=INTEGER}
  </select>
UserOrderMapper.xml
<resultMap id="BaseResultMap" type="com.dsy.entity.UserOrder" >
    <id column="order_id" property="orderId" jdbcType="INTEGER" />
    <result column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="address_id" property="addressId" jdbcType="INTEGER" />
    <result column="total_price" property="totalPrice" jdbcType="DOUBLE" />
    <result column="order_time" property="orderTime" jdbcType="TIMESTAMP" />
    <result column="order_state" property="orderState" jdbcType="INTEGER" />
    <collection property="items" column="order_id" select="com.dsy.dao.OrderItemsMapper.selectByPrimaryKey"/>
  </resultMap>
  <sql id="Base_Column_List" >
    order_id, user_id, address_id, total_price, order_time, order_state
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user_order
    where order_id = #{orderId,jdbcType=INTEGER}
  </select>
BaseServiceImpl:
package com.dsy.service.impl;import com.dsy.dao.BaseMapper;
import com.dsy.service.BaseService;
import org.springframework.transaction.annotation.Transactional;/**
 * Created by dsy on 2018/7/29
 * Package com.dsy.service.impl
 */
//一定要加上否则下面的方法不会被事务控制
@Transactional(value = "transactionManager")
public abstract class BaseServiceImpl<T> implements BaseService<T> {    public abstract BaseMapper<T> getMapper();    @Override
    public int deleteByPrimaryKey(Integer id) {
        return getMapper().deleteByPrimaryKey(id);
    }    @Override
    public int insert(T record) {
        return getMapper().insert(record);
    }    @Override
    public int insertSelective(T record) {
        return getMapper().insertSelective(record);
    }    @Override
    public T selectByPrimaryKey(Integer id) {
        return getMapper().selectByPrimaryKey(id);
    }    @Override
    public int updateByPrimaryKeySelective(T record) {
        return getMapper().updateByPrimaryKeySelective(record);
    }    @Override
    public int updateByPrimaryKey(T record) {
        return getMapper().updateByPrimaryKey(record);
    }
}
UserServiceImpl:
package com.dsy.service.impl;import com.dsy.dao.BaseMapper;
import com.dsy.dao.UserMapper;
import com.dsy.entity.User;
import com.dsy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;/**
 * Created by dsy on 2018/7/29
 * Package com.dsy.service.impl
 */
@Service
@Transactional(value = "transactionManager")
public class UserServiceImpl extends BaseServiceImpl implements UserService {    @Autowired
    private UserMapper userMapper;    @Override
    public BaseMapper<User> getMapper() {
        return userMapper;
    }}
Test:import com.dsy.entity.OrderItems;
import com.dsy.entity.User;
import com.dsy.entity.UserOrder;
import com.dsy.service.UserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;import java.util.List;/**
 * Created by dsy on 2018/7/28
 * Package PACKAGE_NAME
 */
public class UserTest extends BaseTest {    @Autowired
    private UserService userService;    @Test
    public void testFindUserById(){
        User user = (User) userService.selectByPrimaryKey(1);
        List<UserOrder> orders = user.getOrders();
        for (UserOrder order : orders){
            List<OrderItems> items = order.getItems();
            for (OrderItems items1:items){
                System.out.println(items1.getGood().getGoodName());
            }
        }
    }}日志打印结果在最上面

解决方案 »

  1.   

    小白感觉是my batis 和 spring 整合的问题
      

  2.   

    我把配置贴出来
    mybatis-config.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <!--使用jdbc的getGeneratedKeys获取数据库自增主键值-->
            <setting name="useGeneratedKeys" value="true"/>        <!-- 使用列别名替换列名 默认:true -->
            <setting name="useColumnLabel" value="true" />        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
            <setting name="mapUnderscoreToCamelCase" value="true" />        <!--开启延迟加载-->
            <setting name="lazyLoadingEnabled" value="true"/>        <!--取消层级加载-->
            <setting name="aggressiveLazyLoading" value="false"/>
        </settings>    <plugins>
            <!-- com.github.pagehelper为PageHelper类所在包名 -->
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!--指定方言-->
                <property name="helperDialect" value="mysql"/>
                <!--分页参数合理化,pageNum<=0时会查询第一页,pageNum>pages(超过总数时),会查询最后一页-->
                <property name="reasonable" value="true"/>        </plugin>
        </plugins></configuration>
    spring-dao.xml
    <?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:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <!--1.引入外部文件配置数据库相关参数-->
        <context:property-placeholder location="classpath:jdbc.properties"/>    <!--2.配置数据库连接池-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!--配置连接池属性-->
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>        <!--连接池其他属性-->
            <property name="maxPoolSize" value="30"/>
            <!--关闭连接后不自动commit-->
            <property name="autoCommitOnClose" value="false"/>
            <!--获取连接超时时间-->
            <property name="checkoutTimeout" value="10000"/>
        </bean>    <!--3.配置SQLSessionFactory对象-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!--注入连接池-->
            <property name="dataSource" ref="dataSource"/>
            <!--扫描entity使用别名-->
            <property name="typeAliasesPackage" value="com.dsy.entity"/>
            <!--引入Mybatis全局配置文件-->
            <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
            <!--扫描SQL配置文件,Mapper需要的xml文件-->
            <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        </bean>    <!--4.配置扫描dao接口包,动态实现Dao接口,注入到Spring容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!--注入SQLSessionFactory-->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!--给出需要扫描Dao接口包-->
            <property name="basePackage" value="com.dsy.dao"/>
        </bean></beans>
    spring-service.xml<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 扫描service包下所有使用注解的类型 -->
        <context:component-scan base-package="com.dsy.service"/>    <!-- 配置事务管理器 -->
        <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource" />
        </bean>    <!-- 配置基于注解的声明式事务 -->
        <tx:annotation-driven transaction-manager="transactionManager" />
    </beans>
      

  3.   

    <context:component-scan base-package="com.dsy.service"/>
    这一句改成
    <context:component-scan base-package="com.dsy.service.impl"/>
    只是针对你当前报错的情况