Mybatis懒加载——返回前端数据 json序列化错误

    先来个大家一大丢的错误

 

HTTP Status 500 - Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.ssm.model.domain.UserEntity_$$_jvstf7f_0["handler"])

 

背景:

mybatis级联查询,配置了懒加载模式,结果通过springMvc返回json时报的错。

推测:

因为不懂mybatis的源码怎么实现懒加载的,既然是通过用到懒加载部分,再去sql查询,那么肯定是json序列化的时候查询了,由于可能会用到mybatis的一些类,估计就json序列化失败了吧。

解决:

请忽略上面两步,直接百度就能解决了。哈哈哈哈。

在所有相关的类前加上@JsonIgnoreProperties, 作用是json序列化时忽略bean中的一些属性序列化和反序列化时抛出的异常.

 

@JsonIgnoreProperties(value = {"handler"})
public abstract class BaseEntity implements Serializable

问题篇

配置文件篇的cloumn指的是级联时传递过来的参数。

对于关联的collection的属性,一定是集合,否则mybatis会报查一条,却返回多条的错误。

看到这里就可以结束了,下面都是代码,算是本人的一个代码库。

代码篇

先说第一句话,好像mybatis在调试的情况下懒加载是不起作用的。反正我调试的时候不起作用。只有运行的时候起作用。

mapper配置篇

UserMapper配置

<resultMap type="com.ssm.model.domain.UserEntity" id="userMap"  >
        <id property="id" column="id"/>
        <result property="passWord" column="password"/>
        <result property="userName" column="username"/>
        <result property="email" column="email"/>
        <result property="created" column="created"/>
        <result property="updated" column="updated"/>
        <result property="phone" column="phone"/>
        <result property="sex" column="sex" typeHandler="com.ssm.mybatis.typehandler.SexEnumHandler"  />
        <association fetchType="lazy" property="bodyEntity" column="id"  select="com.ssm.dao.BodyMapper.findBodyByUserId">
        </association>
        <association fetchType="eager" property="cardEntity" column="id"  select="com.ssm.dao.CardMapper.findCardByUserId">
        </association>
        <collection property="scoreEntity" column="id"  select="com.ssm.dao.ScoreMapper.findScoreListByUserId">
        </collection>
    </resultMap>
    <select id="selectUserById" resultMap="userMap" >
        select * from tb_user where id = #{id}
    </select>

BodyMapper配置

<resultMap id="bodyMap" type="com.ssm.model.domain.BodyEntity">
        <id property="id" column="id"/>
        <result property="userId" column="user_id"/>
        <result property="userName" column="user_name"/>
        <result property="height" column="height"/>
        <result property="pullUp" column="pull_up"/>
        <result property="pulmonary" column="pulmonary"/>
    </resultMap>

    <select id="findBodyByUserId" resultMap="bodyMap">
        SELECT  * from tb_body
        where user_id = #{id}
    </select>

ScoreMapper配置

    <resultMap id="scoreMap" type="com.ssm.model.domain.ScoreEntity">
        <id property="id" column="id"/>
        <result property="userName" column="user_name"/>
        <result property="userName" column="user_name"/>
        <result property="score" column="score"/>
        <result property="userId" column="user_id"/>
    </resultMap>

<select id="findScoreListByUserId" resultMap="scoreMap">
    SELECT  * from tb_score
    where user_id = #{userId}
</select>

CardMapper配置

 <resultMap id="cardMap" type="com.ssm.model.domain.CardEntity">
        <id property="id" column="id"/>
        <result property="userId" column="user_id"/>
        <result property="userName" column="user_name"/>
        <result property="note" column="note"/>
        <result property="grade" column="grade"/>
    </resultMap>
    
    <select id="findCardByUserId" resultType="card">
        SELECT  * from tb_card
        where user_id = #{id}
    </select>

 

Service代码

 

 @Override
    public UserEntity selectUserById(Long userId) {
        String resource = "mybatis-config.xml";
        SqlSessionFactory sqlSessionFactory=null;
        SqlSession session = null;
        UserEntity userEntity = null;
        try{
            InputStream in = new ClassPathResource(resource).getInputStream();
            //创建单例工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            session = sqlSessionFactory.openSession();
            XmlMybatisTest xmlMybatisTest = new XmlMybatisTest();
            userEntity=xmlMybatisTest.testMapper(session);
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(session!= null){
                session.close();
            }
        }
        return userEntity;
    }

 

 

 

 

 

 

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
Mybatis懒加载是一种延迟加载的机制,只有在需要使用关联对象时才会进行加载。在Mybatis中,懒加载主要应用于关联查询,通过设置延迟规则,推迟对关联对象的查询,减轻数据库的压力。懒加载只对关联对象有延迟设置,而不会延迟主对象的查询。\[1\] 要开启懒加载,需要在Mybatis的主配置文件中的settings标签中设置lazyLoadingEnabled为true。同时,可以设置aggressiveLazyLoading为false来控制懒加载的行为。\[3\] 需要注意的是,开启懒加载是全局的设置,即对所有关联对象都生效。如果只想对部分关联对象进行懒加载,可以使用association和collection的fetchType属性来覆盖全局的懒加载状态。fetchType属性可以设置为eager表示立即加载,lazy表示使用懒加载。\[3\] 总结来说,Mybatis懒加载是一种延迟加载机制,可以减轻数据库的压力。通过在主配置文件中设置相关属性,可以控制懒加载的行为,包括全局开启懒加载、设置懒加载的延迟规则以及对部分关联对象进行懒加载。\[1\]\[3\] #### 引用[.reference_title] - *1* [Mybatis懒加载](https://blog.csdn.net/qq_52519008/article/details/127118918)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [八、(了解即可)MyBatis懒加载(或者叫延迟加载)](https://blog.csdn.net/a924382407/article/details/130505098)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [MyBatis懒加载](https://blog.csdn.net/layonly/article/details/120719900)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值