springboot @Select @Insert @Update @Delete@Options

	@RequestMapping("/select")
	@ResponseBody
	public void select() {
		System.out.println(userMapper.findByName("Michael").toString());
	}
	@RequestMapping("/select2")
	@ResponseBody
	public void select2() {
		System.out.println(userMapper.findByName2("Michael").toString());
	}
	@RequestMapping("/select3")
	@ResponseBody
	public void select3() {
		System.out.println(userMapper.findByName3("Michael").toString());
	}
	@RequestMapping("/insert")
	@ResponseBody
	public void insert() {
		System.out.println(userMapper.insert("sasa"));
	}

	@RequestMapping("/insert2")
	@ResponseBody
	public void insert2() {
		Map<String, Object> map=new HashMap<>();
		map.put("name","zhangsan");
		System.out.println(userMapper.insert2(map));
	}


	@RequestMapping("/insert3")
	@ResponseBody
	public void insert3() {
		User user=new User();
		user.setName("lisi");
		System.out.println(userMapper.insert3(user));
	}

    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO USER(NAME) VALUES(#{name})")
    int insert(@Param("name") String name);

    @Update("update user set name =#{name} where id=#{id}")
    int update(@Param("id") int id,@Param("name") String name);

    @Delete("delete from user where name =#{name}")
    int delete(@Param("name") String name);

    //注解中动态拼接sql
    @Select("<script>" +
            "SELECT * FROM USER WHERE NAME = #{name}" +
            "</script>")
    User findByName2(@Param("name") String name);
    //拼装返回结果在该配置中故意没有查出id属性,只对User对应中的name做了映射配置,
    // 这样可以通过下面的单元测试来验证查出的id为空,而其他属性不为null
    @Select("<script>" +
            "SELECT name FROM USER WHERE NAME = #{name}" +
            "</script>")
    @Results(
            @Result(property ="name" ,column ="name" )
    )
    User findByName3(@Param("name") String name);
    //Map参数传递
    @Insert("INSERT INTO USER(NAME) VALUES(#{name})")
    int insert2(Map<String, Object> map);
    //对象参数传递
    @Insert("INSERT INTO USER(NAME) VALUES(#{name})")
    int insert3(User user);

如果再插入数据库的时候想要返回主键最大值可用@Options注解,在插入成功后,即可获取主键字段的值。

    @Insert("<script>" +
            "INSERT INTO USER(NAME) VALUES(#{name})" +
            "</script>")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    int insert3(User user);

这里的int返回值是操作数据库成功的次数,user.getId()可得到主键int的值。

发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *