mybatis 介绍
- mybatis 本是apache的一个开源项目iBatis,
2010年这个项目由apache迁移到了googlecode,并且改名为MyBatis,2013年11月迁移到Github。 - MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
- MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(普通的 Java对象)映射成数据库中的记录
Mybatis官方文档 :
http://www.mybatis.org/mybatis-3/zh/index.html
GitHub :https://github.com/mybatis/mybatis-3
代码演示
- 所需环境
- jdk1.8.0_91
- mysql-5.7.29
- apache-maven-3.6.3
- 创建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'张三','123456'),(2,'李四','abcdef'),(3,'王五','987654');
- 使用idea创建项目并导入导入mybatis所需jar包
mysql
mysql-connector-java
5.1.46
org.mybatis
mybatis
3.5.2
junit
junit
4.12
- 编写mybatis核心配置文件
该配置文件主要是配置连接mysql的基本信息及注册mapper(具体配置参考官方文档)
- 编写mybatis工具类
查看官方文档,我们这里要封装一个工具类生成SqlSession对象,SqlSession用于后面的执行sql
package com.xiezhr.util;
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 java.io.IOException;
import java.io.InputStream;
public class MysqlUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
- 创建对应数据库表的实体类
各个属性得命名必须与数据库字段一一对应,具体如下所示,数据库对应字段为id,name,pwd
package com.xiezhr.pojo;
public class User {
private int id;
private String name;
private String pwd;
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
", pwd='" + pwd + ''' +
'}';
}
}
- 编写Mapper接口
该接口对应原来的dao,具体代码如下
package com.xiezhr.dao;
import com.xiezhr.pojo.User;
import java.util.List;
public interface UserMapper {
List getUserList();
}
- 编写Mapper.xml 文件
由于我们使用了mybatis,所以这的xml文件相当于我们原来dao得实现类daoimpl。namespace属性对应着接口,不能写错,
- 到这一步我们第一个mybatis实现查询就基本大功告成了,接下来就要编写测试类测试我们写得代码
package com.xiezhr.dao;
import com.xiezhr.pojo.User;
import com.xiezhr.util.MysqlUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TestUserDao {
@Test
public void selectUser(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
}
经过测试后输出测试结果
D:Javajdk1.8.0_91binjava.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:JetBrainsIntelliJ IDEA 2019.3.3libidea_rt.jar=54576:D:JetBrainsIntelliJ IDEA 2019.3.3bin" -Dfile.encoding=UTF-8 -classpath "D:JetBrainsIntelliJ IDEA 2019.3.3libidea_rt.jar;D:JetBrainsIntelliJ IDEA 2019.3.3pluginsjunitlibjunit5-rt.jar;D:JetBrainsIntelliJ IDEA 2019.3.3pluginsjunitlibjunit-rt.jar;D:Javajdk1.8.0_91jrelibcharsets.jar;D:Javajdk1.8.0_91jrelibdeploy.jar;D:Javajdk1.8.0_91jrelibextaccess-bridge-64.jar;D:Javajdk1.8.0_91jrelibextcldrdata.jar;D:Javajdk1.8.0_91jrelibextdnsns.jar;D:Javajdk1.8.0_91jrelibextjaccess.jar;D:Javajdk1.8.0_91jrelibextjfxrt.jar;D:Javajdk1.8.0_91jrelibextlocaledata.jar;D:Javajdk1.8.0_91jrelibextnashorn.jar;D:Javajdk1.8.0_91jrelibextsunec.jar;D:Javajdk1.8.0_91jrelibextsunjce_provider.jar;D:Javajdk1.8.0_91jrelibextsunmscapi.jar;D:Javajdk1.8.0_91jrelibextsunpkcs11.jar;D:Javajdk1.8.0_91jrelibextzipfs.jar;D:Javajdk1.8.0_91jrelibjavaws.jar;D:Javajdk1.8.0_91jrelibjce.jar;D:Javajdk1.8.0_91jrelibjfr.jar;D:Javajdk1.8.0_91jrelibjfxswt.jar;D:Javajdk1.8.0_91jrelibjsse.jar;D:Javajdk1.8.0_91jrelibmanagement-agent.jar;D:Javajdk1.8.0_91jrelibplugin.jar;D:Javajdk1.8.0_91jrelibresources.jar;D:Javajdk1.8.0_91jrelibrt.jar;F:workspace_ideaMybatis-testmybatis-01targettest-classes;F:workspace_ideaMybatis-testmybatis-01targetclasses;D:mavenrepositorymysqlmysql-connector-java5.1.46mysql-connector-java-5.1.46.jar;D:mavenrepositoryorgmybatismybatis3.5.2mybatis-3.5.2.jar;D:mavenrepositoryjunitjunit4.12junit-4.12.jar;D:mavenrepositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.xiezhr.dao.TestUserDao,selectUser
Tue Apr 14 22:54:48 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
User{id=1, name='张三', pwd='322334'}
User{id=2, name='李四', pwd='123456'}
User{id=3, name='王五', pwd='123456'}
扩展
- 1.在UserMapper接口中添加相应的方法selectUserById(id)
public interface UserMapper {
//根据ID查询用户
User selectUserById(int id);
}
- 2.在UserMapper.xml 中添加相应select 语句
- 3.添加测试类
@Test
public void selectUserByid(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
}
测试通过
Wed Apr 15 23:08:00 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
User{id=1, name='张三', pwd='322334'}
- 1.在UserMapper接口中添加方法
public interface UserMapper {
//根据用户名密码查询用户信息
User selectUserByNP(@Param("name") String name,@Param("pwd") String pwd);
}
- 2.在UserMapper.xml 中添加select语句
- 3.添加测试类
@Test
public void selectUserByNP(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserByNP("张三","322334");
System.out.println(user);
}
测试成功
Wed Apr 15 23:24:02 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
User{id=1, name='张三', pwd='322334'}
以上通过用户名和密码查询用户,传参还可以通过万能的map实现,具体代码如下
- 1.向UserMapper接口中添加方法
public interface UserMapper {
//根据用户名和密码查询用户信息
User queryUserByNP(Map map);
}
- 2.向UserMapper.xml 中添加select语句,其中参数类型为map
- 添加测试,在使用过程中,map的key对应着UserMapper.xml中取值,map在put值时候没有先后顺序
@Test
public void queryUserByNp(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap();
map.put("name","张三");
map.put("pwd","322334");
User user = mapper.queryUserByNP(map);
System.out.println(user);
}
- 1.在Java代码中添加sql通配符
string wildcardname = “%smi%”;
list names = mapper.selectlike(wildcardname);
- 2.在sql语句中拼接通配符,会引起sql注入
string wildcardname = “smi”;
list names = mapper.selectlike(wildcardname);
华丽的分割线
接下来我们分别来实现insert、update、delete
insert
- 在之前编写的UserMapper 接口中添加增加方法
public interface UserMapper {
//添加一条用户信息
int addUser(User user);
}
2.在UserMapper.xml 中写insert 语句
insert into mybatis.user values(#{id},#{name},#{pwd})
- 添加测试类
insert、update、delete 一定要提交事务,千万千万不能忘记了
@Test
public void addUser(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4, "大头儿子", "123456");
mapper.addUser(user);
sqlSession.commit(); //增删改一定要提交事务
sqlSession.close();
}
update
- 在之前编写的UserMapper 接口中添加update方法
public interface UserMapper {
//修改一条记录
int updateUserById(int id);
}
2.在UserMapper.xml 中写insert 语句
update mybatis.user set name='小头爸爸' where id=#{id}
- 添加测试类
insert、update、delete 一定要提交事务,千万千万不能忘记了
@Test
public void updateUserById(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUserById(4);
sqlSession.commit(); //增删改一定要提交事务
sqlSession.close();
}
delete
- 在之前编写的UserMapper 接口中添加delete方法
public interface UserMapper {
//根据ID删除一条记录
int deleteUserById(int id);
}
}
2.在UserMapper.xml 中写insert 语句
delete from mybatis.user where id=#{id}
- 添加测试类
insert、update、delete 一定要提交事务,千万千万不能忘记了
@Test
public void deletUserById(){
SqlSession sqlSession = MysqlUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUserById(4);
sqlSession.commit(); //增删改一定要提交事务
sqlSession.close();
}
注意
- 所有的insert、update、delete 必须要提交事务
- 接口中所有的普通参数尽量写上@Param 参数,尤其是多个参数的时候一定要写上
- 有些时候由于业务需要需要可通过map传值
- 为了规范在sql配置文件中即本例的UserMapper.xml 中select inset delete update 尽量写上Parameter参数和resultType
可能出现问题说明:Maven静态资源过滤问题
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
在静态资源的过滤中,基本的元素有三种:
- directory:指定资源所在的目录,这个目录的路径是相对于pom.xml文件;
- includes:指定要包含哪些文件,其中包括inlcude子节点来指定匹配的模式;
- excludes:指定要排除哪些文件,其中包括exclude子节点来指定匹配的模式;
- filtering:指定哪些文件需要过滤,这个过滤的目的是为了替换其中的占位符${},其中的占位符属性在pom.xml文件中的
中指定;
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net