目录
1.查询
序号参数绑定
一个参数形式
多个参数形式
map参数绑定
实体对象参数绑定
2.添加
3.删除
4.修改
5.模糊查询
6.主键回填
查询这里会展示四种参数绑定的形式,帮助理解,但在这四种参数中最为推荐的是注解参数绑定,能够帮助我们极大程度的简化代码,因为mybatis就是未来能够完成增删改查操作,使得我们能够只关注参数绑定
dao层语句
public User selectById(Integer id);
mapper语句
测试层
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
//序号参数绑定下单个参数
User user = mapper.selectById(1);
System.out.println(user);
dao层语句
//多种参数的情况
//1.匹配注解param
public User selectByIdAndPwd(@Param("id") Integer id, @Param("pwd") String pwd);
//2.变化在mapper那边,有两种不同的参数
public User selectByIdAndPwd(Integer id, String pwd);
mapper语句
测试层
//多个参数绑定
User user = userDao.selectByIdAndPwd(2, "456");
System.out.println(user);
dao层语句
//3.使用map集合
public User selectMap(Map map);
mapper语句
测试层
//map参数
Map map=new HashMap();
map.put("id",1);
map.put("pwd","123");
User user = userDao.selectMap(map);
System.out.println(user);
dao层语句
User selectUser(User user);
public List selectByLikeName(String username);
mapper语句
测试层
//实体传参
User user=new User();
user.setId(1);
user.setPassword("123");
User user1=userDao.selectUser(user);
System.out.println(user1);
dao层语句
public int addUser(User user);
mapper语句
insert into t_users(name,password,sex) values(#{name},#{password},#{sex})
测试层
User user4=new User();
user4.setName("wyz");
user4.setPassword("789");
user4.setSex("男");
int i = userDao.addUser(user4);
System.out.println(i);
dao层语句
public int delUser(Integer id);
mapper语句
delete from user where id=#{id}
测试层
int res=userDao.delUser(3);
System.out.println(res);
dao层语句
public int updateUser(User user);
mapper语句
update user set name=#{name},password=#{password},sex=#{sex} where id=#{id}
测试层
User user4=new User();
user4.setName("张国荣");
user4.setPassword("789");
user4.setSex("男");
int i = userDao.addUser(user4);
System.out.println(i);
dao层语句
public List selectByLikeName(String username);
mapper语句
测试层
List z = userDao.selectByLikeName("z");
System.out.println(z);
dao层语句
//当主键为int类型
public int selectUserPrimary(User user);
//当主键为string类型
public int selectOrderPrimaryId(Order order);
mapper语句
#在添加完成(order="AFTER")之后,执行的指令 keyProperty="id":将查询的值注入到实体属性
select last_insert_id()
insert into user(name,password,sex) values (#{name},#{password},#{sex})
select uuid()
insert into orders(id,name) values(#{id},#{name})
测试层
User user=new User();
user.setName("wyz");
user.setPassword("789");
user.setSex("男");
userDao.selectUserPrimary(user);
System.out.println(user);
Order order=new Order();
order.setName("yyy");
userDao.selectOrderPrimaryId(order);
System.out.println(order);
//事务的提交,要提交成功才能狗将数据库中的数据修改或者添加成功
sqlSession.commit();
sqlSession.close();