MyBatis Plus 主子表插入与查询数据

描述

在mybatis plus官网代码基础上修改

Mybatis-Plus SpringMVC 演示 demo

文件结构
MyBatis Plus 主子表插入与查询数据_第1张图片

实体类
主表:newsys_user
子表:newuser_item

package com.css.paas.ws.service.MyBatis.api;

import com.baomidou.mybatisplus.annotations.TableField;
import java.util.Date;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * 用户信息 NewSysUser 
 */
@TableName("newsys_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NewSysUser extends Model {

    private static final long serialVersionUID = 1L;

    /**
     * 编号
     */
	@TableId(value="id", type= IdType.ID_WORKER)
	private String id;
    /**
     * 姓名
     */
	private String name;
    /**
     * 昵称
     */
	private String nickname;
    /**
     * 邮箱
     */
	private String email;
    /**
     * Q号码
     */
	private String number;
    /**
     * 密码
     */
	private String password;
    /**
     * 创建时间
     */
	@TableField("create_time")
	private Date createTime;
    /**
     * 最后登录时间
     */
	@TableField("last_login_time")
	private Date lastLoginTime;
    /**
     * 状态:0 锁定、 1 正常
     */
	private Integer status;
	@Override
	protected Serializable pkVal() {
		return this.id;
	}

    // 该属性不为数据库表字段,但又是必须使用的
	@TableField(exist = false)
	private List newUserItems;
}

package com.css.paas.ws.service.MyBatis.api;

import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.Data;

/**
 * 用户子表:NewUserItem
 * Created by HHao on 2019/1/7.
 */
@TableName("newuser_item")
@Data
public class NewUserItem {

//    测试事务时将这个注解@TableId注释
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String userId;
    private String productName;
}

两个Mapper文件需要继承SuperMapper,SuperMapper继承的是BaseMapper

package com.css.paas.ws.service.MyBatis.plus.mapper;
import com.baomidou.springmvc.common.SuperMapper;
import com.css.paas.ws.service.MyBatis.api.NewSysUser;

public interface NewSysUserMapper extends SuperMapper {
}

package com.css.paas.ws.service.MyBatis.plus.mapper;
import com.baomidou.springmvc.common.SuperMapper;
import com.css.paas.ws.service.MyBatis.api.NewUserItem;

public interface NewUserItemMapper extends SuperMapper {
}

SuperMapper类,下载dome自带

package com.baomidou.springmvc.common;

/**
 * 

* 测试自定义 mapper 父类 *

*/ public interface SuperMapper extends com.baomidou.mybatisplus.mapper.BaseMapper { // 这里可以写自己的公共方法、注意不要让 mp 扫描到误以为是实体 Base 的操作 }

定义接口类

import com.baomidou.mybatisplus.service.IService;
import com.css.paas.ws.service.MyBatis.api.NewSysUser;

public interface INewSysUserService extends IService {
}

接口实现,查询与插入实现了主子表的关系,
需要注意实体类NewSysUser中 ,newUserItems字段需要增加@TableField(exist = false)注解,这样list类型的字段就会自动忽略与数据库的对应关系

@TableField(exist = false)
private List newUserItems;

package com.css.paas.ws.service.MyBatis.plus.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.css.paas.ws.service.MyBatis.api.NewSysUser;
import com.css.paas.ws.service.MyBatis.api.NewUserItem;
import com.css.paas.ws.service.MyBatis.plus.mapper.NewSysUserMapper;
import com.css.paas.ws.service.MyBatis.plus.mapper.NewUserItemMapper;
import com.css.paas.ws.service.MyBatis.plus.service.INewSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * Created by huaihao on 2019/1/7.
 */
@Service
public class NewSysUserServiceImpl extends ServiceImpl implements INewSysUserService {
    @Autowired
    private NewSysUserMapper newSysUserMapper;
    @Autowired
    private NewUserItemMapper newUserItemMapper;

    /**
     * 重写 IService中 List selectList(Wrapper var1) 方法
     * @param wrapper
     * @return
     */
    public List selectList(Wrapper wrapper){
        List newSysUsers = newSysUserMapper.selectList(wrapper);
        for (NewSysUser newSysUser : newSysUsers) {
            HashMap map = new HashMap<>();
            map.put("userId", newSysUser.getId());
            List newUserItems = newUserItemMapper.selectByMap(map);
            newSysUser.setNewUserItems(newUserItems);
        }
        return newSysUsers;
    }

    /**
     * 重写 IService中 boolean insert(T var1);
     * 重写的插入方法实现了事务管理,当子表插入失败,主表已经插入的数据会回滚
     * @param newSysUser
     * @return
     */
    public boolean insert(NewSysUser newSysUser){
        try {
            newSysUserMapper.insert(newSysUser);
            List newUserItemList=newSysUser.getNewUserItems();
            for (NewUserItem newUserItem:newUserItemList) {
                newUserItemMapper.insert(newUserItem);
            }
        }catch (Exception e){
            System.out.println("error***************:"+e.getMessage());
            return false;
        }
        return true;
    }
}

spring-mybatis.xml中,最后修改 动态扫描与事务切面 配置,由于增加了新的路径包,在expression增加了一个新的execution,注意expression写法中的括号

 
    
        
    
  
    
    
        
        
    

测试类

package com.css.paas.ws.service.FMOutputCAV.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.css.paas.ws.service.MyBatis.api.NewSysUser;
import com.css.paas.ws.service.MyBatis.api.NewUserItem;
import com.css.paas.ws.service.MyBatis.plus.service.INewSysUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huaihao on 2019/1/7.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring.xml"})
public class ServiceTest {

    @Autowired
    @Qualifier("newSysUserServiceImpl")
    INewSysUserService newSysUserServiceImpl;


    @Test
    public void SysUserGetTest() throws Exception {

        List list = newSysUserServiceImpl.selectList(new EntityWrapper());
        System.out.println("****************************************");
        for(NewSysUser newSysUser:list){
            newSysUser.getNewUserItems();
            System.out.println(newSysUser);
        }
        System.out.println(list.size());
        System.out.println("****************************************");
    }

    @Test
    public void SysUserAddTest() throws Exception {
        NewSysUser newSysUser = new NewSysUser();
        newSysUser.setId("3");
        newSysUser.setName("李四");
        newSysUser.setNickname("lisi");
        newSysUser.setEmail("[email protected]");
        newSysUser.setNumber("1581019");
        newSysUser.setPassword("654321");
        newSysUser.setStatus(1);

        NewUserItem newUserItem1 = new NewUserItem();
        newUserItem1.setUserId(newSysUser.getId());
        newUserItem1.setProductName("栗子");
        NewUserItem newUserItem2 = new NewUserItem();
        newUserItem2.setUserId(newSysUser.getId());
        newUserItem2.setProductName("西瓜");

        List list = new ArrayList<>();;
        list.add(newUserItem1);
        list.add(newUserItem2);
        newSysUser.setNewUserItems(list);
        
        boolean insert = newSysUserServiceImpl.insert(newSysUser);
        System.out.println("****************************************");
        System.out.println(insert);
        System.out.println("****************************************");
    }

}

最后有几个遇到的坑,总结一下
1.因为我是把mybatis plus整合到已有的项目中,在测试类执行的时候,一直提示解决 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type,最后发现在使用@Autowired引用 INewSysUserService时,发现的实现类不是唯一,此处有两个解决办法

  • 增加@Qualifier(“newSysUserServiceImpl”) 注释
  • 直接接口定义的时候,使用实现类的名字:INewSysUserService newSysUserServiceImpl;

2.使用@RunWith(SpringJUnit4ClassRunner.class)时,也会报错,最后看错误报告,发现使用的是junit5运行测试用了,在pom中引用了junit-jupiter-api模块,去除掉即可
JUnit5IdeaTestRunner错误

你可能感兴趣的:(总结)