Mybatis
环境:
- JDK1.8
- Mysql5.7
- maven3.6.1
- IDEA
1.简介
1.1什么是Mybatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis。
- 2013年11月迁移到Github。
如何获得Mybatis?
- maven仓库
- Github
1.2、持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬间状态转化的过程
- 持久化:将数据保存到数据库,文档
- 瞬间状态:数据保存在内存,断电即失
1.3持久层
Dao层、Service层、Controller层。。。。
- 完成持久化工作的代码块
- 层界限十分明显。
1.4为什么需要Mybatis?
-
方便
-
传统的JDBC代码太复杂了,简化代码,框架、自动化。
-
帮助将数据存到数据库中
2.第一个Mybatis程序
思路:搭建环境–>导入Mybatis—>编写代码–>测试!
2.1、搭建环境
搭建数据库
CREATE DATABASE `Mybatis`
CREATE TABLE `user`
INSERT INTO `user`(id ,`name`,pwd) VALUES
(1001,'曹久平','123456'),
(1002,'张三','1234'),
(1003,'李四','12345')
新建项目
1、新建一个普通的maven项目
2、删除src目录
3、导入maven依赖
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2.2、创建一个模块
- 新建一个mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写mybatis工具类
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis的第一步,获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.3、编写代码
- 实体类
package com.cjp.pojo;
//实体类
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
- Dao接口
package com.cjp.dao;
import com.cjp.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
- 接口实现类(由于原来的一个实现类转化为一个Mapper配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao、Mapper接口-->
<mapper namespace="com.cjp.dao.UserDao">
<!--查询语句-->
<select id="getUserList" resultType="com.cjp.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.3、测试
注意:maven导出资源问题:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
package com.cjp.dao;
import com.cjp.pojo.User;
import com.cjp.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
//第一步,获得SqlSession对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
try {
//第二步,执行sql
//方式一:
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
/*//方式二:(不推荐使用)
List<User> users = sqlSession.selectList("com.cjp.dao.UserDao.getUserList");
for (User user : users) {
System.out.println(user);
}*/
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭SqlSession
sqlSession.close();
}
}
}
3.CRUD
1.namespace
namespace中的包名要和Dao/Mapper接口的包名一致
2.select
查询语句
- id:就是对应的namespace中的方法名;
- resultType:sql语句执行返回值;
- parameterType:参数
3.增删改查实现
在之前基础上,增删改查只需要更新UserMapper接口中的方法、UserMapper.xml中的配置、以及测试代码即可。
注意:增删改需要提交事务
UserMapper:
package com.cjp.dao;
import com.cjp.pojo.User;
import java.util.List;
public interface UserMapper {
//获取全部用户
List<User> getUserList();
//根据id查询用户
User getUserById(int id);
//添加一个用户
int insertUser(User user);
//修改用户
int updateUser(User user);
//删除用户
int deleteUser(int id);
}
UserMapper.xml文章来源:https://www.toymoban.com/news/detail-471945.html
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao、Mapper接口-->
<mapper namespace="com.cjp.dao.UserMapper">
<!--查询语句-->
<select id="getUserList" resultType="com.cjp.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" resultType="com.cjp.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.cjp.pojo.User" >
insert into mybatis.user (id,name,pwd)value (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="com.cjp.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id} ;
</update>
<delete id="deleteUser" parameterType="int" >
delete from mybatis.user where id=#{id};
</delete>
</mapper>
测试代码:文章来源地址https://www.toymoban.com/news/detail-471945.html
package com.cjp.dao;
import com.cjp.pojo.User;
import com.cjp.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
//第一步,获得SqlSession对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
try {
//第二步,执行sql
//方式一:
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
/*//方式二:(不推荐使用)
List<User> users = sqlSession.selectList("com.cjp.dao.UserDao.getUserList");
for (User user : users) {
System.out.println(user);
}*/
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭SqlSession
sqlSession.close();
}
}
@Test
public void getUserByIdTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1004);
System.out.println(user);
sqlSession.close();
}
@Test
// 增删改查需要提交事务
public void insertTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(1004, "王五", "1234567");
int i = mapper.insertUser(user);
if (i>=1){
System.out.println("插入成功!");
}else {
System.out.println("插入失败!");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUserTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.updateUser(new User(1004, "元歌", "1433223"));
if (i>0){
System.out.println("修改成功!");
}else {
System.out.println("修改失败!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(1003);
if (i>0){
System.out.println("删除成功!");
}else {
System.out.println("删除失败!");
}
sqlSession.commit();
sqlSession.close();
}
}
4.利用Map传递参数
- 只有一个基本类型参数时,可直接在sql中取到
- 多个参数可以用Map,或者注解
int addUser(Map<String,Object> map);
<insert id="addUser" parameterType="map" >
insert into mybatis.user(id,name,pwd)value (#{number},#{UserName},#{password})
</insert>
@Test
public void addUserTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap<String, Object>();
map.put("number",1006);
map.put("UserName","Bob");
map.put("password","535353");
mapper.addUser(map);
sqlSession.commit();
sqlSession.close();
}
5.模糊查询
//模糊查询
List<User> getLike(String str);
<select id="getLike" resultType="com.cjp.pojo.User" >
select * from mybatis.user where name like #{str};
</select>
@Test
public void getLikeTest(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getLike("%张%");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
到了这里,关于Mybatis学习笔记第一天的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!