Mybatis取值在Map中传入的对象和字符串

  • Post author:
  • Post category:其他




Mybatis取值在Map中传入的对象和字符串


当我们在使用Mybatis查询或添加数据时,可能会遇到在Map中添加一个对象和字符串等操作。



下面我来分享一下解决方法



Controller层代码

package com.xzly.controller;
@RestController
@RequestMapping("/user")
@CrossOrigin
public class RegisterController {
    @Autowired
    private RegisterService registerService;

	@RequestMapping("/register")
    public String register(@RequestBody String Params) {
	//这里的参数为假数据,作为前端传入参数
		String id = 1;
		String userName = admin;
		String userPass = admin123;
    	//各个参数封装到user中
        User user = new User();
        user.setId(id).setUserName(userName).setUserPass(userPass);
	    String MAXTables = "MAXTables";
		Map<String,Object> map = new HashMap<String,Object>();
            map.put("MAXTables",MAXTables);
            map.put("user",user);
			//根据传表名执行添加语句
            int registering = registerService.insertUser(map);
	}
}



Service接口方法

package com.xzly.service;

public interface RegisterService {
	 /**
     * 根据传表名执行添加语句
     * @param map
     * @return
     */
    int insertUser(Map<String,Object> map);
}



ServiceImpl实现类

package com.xzly.service.serviceImpl;

@Service
public class RegisterServiceImpl extends ServiceImpl<RegisterMapper, User> implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;

	  /**
     * 根据传表名执行添加语句
     * 作者:rosyclouds.sss
     * @param map 表名(字符串)和user对象
     * @return
     */
    @Override
    public int insertUser(Map<String,Object> map) {
        System.out.println(map);
        System.out.println("===========" + map);
        return registerMapper.insertUser(map);
    }
}



Dao层

package com.xzly.dao;

@Mapper
public interface RegisterMapper extends BaseMapper<User> {

	 /**
     * 根据传表名执行添加语句
     * @param map 表名(字符串)和user对象
     * @return
     */
    int insertUser(Map<String,Object> map);

}



Mybatis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xzly.mapper.RegisterMapper">
	<!--    根据传表名执行添加语句-->
    <insert id="insertUser" parameterType="map" useGeneratedKeys="true">
        INSERT INTO ${MAXTables1}
                (ID, User_Name,User_Pass)
        VALUES
                (#{user.id,jdbcType=DECIMAL},
                 #{user.userName,jdbcType=VARCHAR},
                 #{user.userPass,jdbcType=VARCHAR})
    </insert>
</mapper>



谢谢大家的支持



版权声明:本文为JunLiYun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。