添加并返回 自增的主键:
改变 insert标签的属性
注意keyProperty对应的是实体类中的id,而不是数据库中的
//增加insert的属性返回结果:
addUserInfo 添加了1记录
userId=6
基础实现:
// 1.mapper xml:
insert into userinfo(username,password,photo,state)values(#{username},#{password},#{photo},1)
// 2.mapper interface:
Integer add(User user);//3.test实现
@Test
void addUserInfo() {Userinfo userinfo = new Userinfo();userinfo.setUsername("test");userinfo.setPassword("test");userinfo.setCreatetime(LocalDateTime.now());userinfo.setUpdatetime(LocalDateTime.now());int result = userinfoMapper.addUserInfo(userinfo);//默认返回受影响的行数System.out.println("addUserInfo 添加了" + result + "记录");Assertions.assertEquals(1, result);int userId = userinfo.getId();System.out.println("userId=" + userId);
}
//运行结果:
addUserInfo 添加了1记录
userId=0
// 1.mapper interface:
int deleteById(Integer id);
// 2.mapper xml:
delete from userinfo where id=${id}
//3.test实现
@Test
void deleteById() {Integer id = 8;int result = userinfoMapper.deleteById(id);Assertions.assertEquals(1, result);
}
// 1.mapper interface:
int updateUserNameById(Userinfo userinfo);
// 2.mapper xml:
insert into userinfo(username,password,createtime,updatetime)values(#{username},#{password},#{createtime},#{updatetime});
//3.test实现
@Test
void updateUserNameById() {Userinfo userinfo = new Userinfo();userinfo.setId(2);userinfo.setUsername("小明");int result = userinfoMapper.updateUserNameById(userinfo);Assertions.assertEquals(1,result);
}
// 1.mapper interface:
Userinfo getUserInfoById(@Param("id") Integer id);
List getAllUserInfo();
List getAllUserInfoByOrder(String key,String arrange);
//2.mapper xml:
//注意这里的 ${key} ${arrange} 必须使用$进行链接
% 匹配任意 _ 匹配一个字符
如上面代码 会发生报错!!
like查询不能直接使用 # { } ,'% 'username' %' ,会自动加入'',而导致报错。
而也不能使用 $ { } ,因为是不可穷举的参数,我们无法保证安全性!
应该使用concat拼接,如下面代码
对于
id 属性:用于标识实现接口中的那个方法
结果映射属性:结果映射有两种实现标签:
绝大数查询场景可以使用 resultType 进行返回,如下代码所示:
// 1.mapper interface:
Userinfo getNameById(@Param("id") Integer id);
// 2.mybatis.userMapper:
它的优点是使用方便,直接定义到某个实体类即可。
功能:
实现程序中 属性 和 表字段 的映射功能
resultMap 使用场景(什么时候需要手动映射):
字段名称和程序中的属性名不同的情况,可使用 resultMap 配置映射;
一对一和一对多关系可以使用 resultMap 映射并查询数据。
命名不同的两种原因:
通常数据库代码有DBA(数据库管理员)进行设计,而不是我们自己设计
命名规则不同,比如数据库中经常使用 _ 进行连接,而Java中通常使用 小驼峰
如下面的情况 password 和 pwd 的区别:
这个时候当我们依旧使用resultType的时候,就会出现pwd为空的情况,后端的pwd字段无法接收数据库的password内容!
因为名称不一样,MyBatis无法自动映射赋值,这时候我们就需要使用resultMap
看下面代码
在 mybatis.userMapper.xml中 分两部分写,分别是 映射和语句
//这里的 resultMap 和上面 标签里的 id 对应!
这样是不是很麻烦?
只有一个字段不同,但是其他的每一个也都需要进行映射,那么有没有更加简单的解决方案?当然有,我们可以把mysql中的字段进行别名!这样的话就不需要映射了。看下面代码 as
数据库字段名 和 实体类属性名 不同的时候 如何解决:
①使用resultMap进行映射
②直接对数据库字段名添加别名 (企业经常使用)
解决方案:联表查询语句(left join / inner join)+VO对象(Value Object值对象)
比如一下场景:blog管理系统,有user表 和 Blog表,使用的userId进行关联。目前在一个界面上想要获取Blog的所有信息 和 这个博客对应user表中的userName。我们怎么实现呢?
① 在实体类中创建一个VO类
②在接口mapper处编写代码
③在mybatisMapper处编写代码