Mybatis学习day2
Mybatis初探
之前已经用利用mybatis实现链接数据库查询所有用户的信息(用的是在resources下建立和Dao层一样目录的xml实现的)。这次再来看一下增删改查等其它的操作。
利用Mybatis我们可以不用写Dao层的实现类。让代理对象去帮我们去做这件事。
注解的方式:和servlet一样不仅可以通过xml进行配置还可以用注解。下面主要展示注解方式实现。
直接在UserDao接口(不了解文件布局的可以先去看这里:https://www.cnblogs.com/cstdio1/p/11882953.html)下书写Sql语句
在这之前说一下我们测试功能都是建一个类Test在这里面进行单元测试
单元测试:
你必须在pom.xml进行配置才能使用:

查询所有:

单元测试代码:

细心的小伙伴可能已经发现这个测试代码怎么这么短,明明上个用Mybatis要有好几步呢。
其实我们将那几步进行了封装,写在两个函数中,一个用于测试前(Before)调用和一个测试后(After)调用。
用注解@Before和@After
测试前:

测试后:

之后的操作大概也是如此,不想罗嗦了·,还有一点需要说一下。
有些时候传入的参数不是简单类型而是一个类的对象,这个时候我们需要写对应类中的属性(并且通过这个属性可以找到最终查询对象的信息)
最简单的情况就是这个间接类有个属性的类型就是要查找的那个User类型
例如:

上面的user是Query类的一个变量(User类型的)然后通过user可以直接 .username,username是User类的一个属性
Query内部:

执行的SQL语句(占位符方式):

查询结果:

还有一种方式是:

执行的SQL语句(存在SQL注入):

查询结果:

因为Sql'注入问题所以一般就用第一种方式。
这里我的实体类的属性名和数据库的对应列名名称一致,如果不一致应该如何配置?
注解方式大家可以参考:https://blog.csdn.net/Hello_MAOSONG/article/details/90322089
xml方式:

以根据Id查询为例: (下面的查询引入resultMap填入上面的resultMap的id)

还有一种解决方式(SQL的起别名):

在Java中,类的全限定名往往会很繁琐,在mybatis使用这些类型的时候,需要配置很复杂的属性,例如:
<typeAliases>
<typeAlias alias="User" type="cn.mybatis.mydemo.domain.User"/>
</typeAliases>
下面的如果返回是这个实体类就可以直接写上面的别名(这里的别名不区分大小写)
<select id="getAllUsers" resultType="User">
select * from users
</select>
如果有很多个类就需要写很多个,很麻烦
<typeAlias alias="别名" type="全限定类名"/>
这个时候就可以使用package
<typeAliases>
<package name="要起别名class所在的包"/>
</typeAliases>
此时别名就是对应类名(不区分大小写)
注意:在typeAliases起的别名都是实体类的
如果是在mappers下使用package,含义是

UserDao代码:
package com.zyb.dao; import com.zyb.pojo.Query;
import com.zyb.pojo.User;
import org.apache.ibatis.annotations.*; import java.util.List; public interface UserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from my_user")
List<User> selAll(); /**
* 保存方法
*/
@Insert("insert into my_user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user); /**
*更新操作
*/
@Update("update my_user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}")
void updateUser(User user); /**
* 通过id删除记录
* @param
*/
@Delete("delete from my_user where id=#{uid}")//可以不叫uid,随便起名称
void deleUserById(Integer userId); /**
* 根据id查询
* @param userId
* @return
*/
@Select("select * from my_user where id=#{uid}")//可以不叫uid,随便起名称
User selById(Integer userId); /**
* 根据姓名模糊查询
* @return
*/
//@Select("select * from my_user where username like #{name}")//这种方式需要在外面加%
@Select("select * from my_user where username like '%${value}%' ")//不需要在外面加%,这里变量名必须是value List<User> selByName(String userName); /**
* 查询总用户数
* @return
*/
@Select("select count(id) from my_user")//使用聚合函数
int selUserNums(); /**
* 查询最后插入视频的id
* @return
*/
@SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", before = false, resultType = int.class)
int selLastInsertId(); /**
* 根据Query的信息查询用户
* @param query
* @return
*/
@Select("select * from my_user where username like #{user.username}")
List<User> selByQuery_UserName(Query query);
}
测试类源码:
package com.zyb.test; import com.zyb.dao.UserDao;
import com.zyb.pojo.Query;
import com.zyb.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before; import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.Date;
import java.util.List; public class Test {
InputStream in;
SqlSession session;
UserDao userDao; @Before
public void init() throws IOException {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
session = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
userDao = session.getMapper(UserDao.class);
} @After
public void destory() throws IOException {
session.commit();
//6.释放资源
session.close();
in.close(); } /**
* 测试查询所有
* @throws IOException
*/
@org.junit.Test
public void testSelAll() throws IOException { //5.使用代理对象执行方法
List<User> users = userDao.selAll();
for(User user : users){
System.out.println(user);
} } /**
* 测试保存操作
* @throws IOException
*/
@org.junit.Test
public void testSave() throws IOException { User user = new User();
user.setAddress("成都市");
user.setBirthday(new Date());
user.setSex("男");
user.setUsername("zs"); //5.使用代理对象执行方法
userDao.saveUser(user); } /**
* 测试更新操作
*/
@org.junit.Test
public void testUpdate(){
User user = new User();
user.setAddress("成都市");
user.setBirthday(new Date());
user.setSex("女");
user.setUsername("zj");
user.setId(51);
userDao.updateUser(user); } /**
* 测试删除操作
*/
@org.junit.Test
public void testDel(){
Integer id = new Integer(51);
userDao.deleUserById(id);
} @org.junit.Test /**
* 测试查询操作
*/
public void testSelOne(){
User user=userDao.selById(48);
System.out.println(user);
} /**
* 测试模糊查询
*/
@org.junit.Test
public void testSelByName(){
List<User> users = userDao.selByName("王");
users.forEach(x-> System.out.println(x)); } /**
* 测试总用户数
*/
@org.junit.Test
public void testSelUserNums(){
System.out.println("用户总数是:"+userDao.selUserNums());
} @org.junit.Test
public void testSelByQuery(){
Query query = new Query();
User user = new User();
user.setUsername("%王%");//模糊查询
query.setUser(user);
List<User> users=userDao.selByQuery_UserName(query);
users.forEach(x-> System.out.println(x));
} }
参考:http://www.mybatis.cn/archives/820.html
Mybatis学习day2的更多相关文章
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)
孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: m ...
- MyBatis学习总结(七)——Mybatis缓存(转载)
孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(七)--Mybatis缓存 一.MyBatis缓存介绍 正如大多数持久层框架一样,MyBatis 同样提供了一级缓存和二级缓存的 ...
- (原创)mybatis学习二,spring和mybatis的融合
mybatis学习一夯实基础 上文介绍了mybatis的相关知识,这一节主要来介绍mybaits和spring的融合 一,环境搭建 1,jar包下载,下载路径为jar包 2,将包导入到java工程中 ...
- (原创)mybatis学习一,夯实基础
一,what?(是什么) MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可 ...
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...
- 【Todo】Mybatis学习-偏理论
之前写过好几篇Mybatis相关的文章: http://www.cnblogs.com/charlesblc/p/5906431.html <SSM(SpringMVC+Spring+Myba ...
- MyBatis学习系列三——结合Spring
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ...
随机推荐
- webpack 打包增加版本信息
What do we need? 笔者目的是在vue项目打包后的 dist/index.html 文件中写入本次打包git用户.最后一次git提交信息,这样做的目的是便于线上项目的管理和防止同事之间的 ...
- HDU 3823 Prime Friend(线性欧拉筛+打表)
Besides the ordinary Boy Friend and Girl Friend, here we define a more academic kind of friend: Prim ...
- EVE-NG镜像模板资源占用统计
转:http://www.emulatedlab.com/forum.php?mod=viewthread&tid=432&extra=page%3D1 EVE Image fold ...
- Python 摄像头 树莓派 USB mjpb
import cv2 import urllib.request import numpy as np import sys host = "192.168.1.109:8080" ...
- mvc 上传文件 HTTP 错误 404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求。 maxRequestLength与 maxReceivedMessageSize 和 maxAllowedContentL区别
具体的错误信息如下: 在线上遇到了文件上传问题,在测试环境试了好久都没有发现问题到底出在哪里,以为是服务器做了各种限制,然后一点思绪都没有.最后,尝试将线上的代码包拷贝一份,在测试环境运行,刚开始的时 ...
- js 页面滚动到指定位置
当页面的长度比较长时,如果进行刷新页面,我们希望能够在刷新完成页面之后,能够停留在当前位置,而不是从头再手动滚动到当前位置. 那么这样的效果如何实现呢?下面开始简单描写(由于博客园不支持效果展示,所以 ...
- python 中对list去重
本文去重的前提是要保证顺序不变,本文给出了多种实现方法,需要的朋友可以参考下 1.直观方法 最简单的思路就是: ids = [1,2,3,3,4,2,3,4,5,6,1] news_ids = [] ...
- Spark原理概述
原文来自我的个人网站:http://www.itrensheng.com/archives/Spark_basic_knowledge 一. Spark出现的背景 在Spark出现之前,大数据计算引擎 ...
- 开学考试学生成绩管理Java
首先student类 package xuexi; public class Student { private String stunumber; private String name; priv ...
- UVA10600 ACM Contest and Blackout
用prim算法求最小生成树和次小生成树~ #include<cstdio> #include<algorithm> #include<cstring> using ...