目录
目录
环境配置
增删改查的实现
查询全部
查询单个ID
添加用户
修改用户
删除用户
增删改查-使用注解开发
思路流程:搭建环境-->导入Mybatis--->编写代码--->测试
选择Maven直接点击下一步
删除src文件,只保留pow文件
环境准备
创建子模块 mybatis-01
mybatis-01下的pow文件添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Mybatis-zsgc</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-01</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
</project>
Mybatis-zsgx下的pow文件添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Mybatis-zsgc</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatis-01</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/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>
</dependency>
</dependencies>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
创建数据库mybatis数据库下的user表 id int name String pwd String
补全目录
环境配置
在resources下创建mybatis-config.xml
<?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>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="com.liujia.pojo.User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.liujia.dao.UserMapper"/>
</mappers>
</configuration>
在resources下创建db.properties资源包
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&acharacterEncoding=UTF-8
#url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=111111
完成如下:ehcache.xml是文件缓存 先不要管 不影响使用
在com.liujia.dao下
创建UserMapper接口 两个文件名要保持完全一致
创建UserMapper.xml
<?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">
<mapper namespace="com.liujia.dao.UserMapper">
</mapper>
在com.liuijia.pojo下创建实体类 创建User
因为pow文件加入 lombok插件依赖
@Data @AllArgsConstructor @NoArgsConstructor
代表的意思是 构造函数 有参无参 虽然省事 但不利于代码的查阅性
在com.liujia.utils编写MyBatis工具类
return sqlSessionFactory.openSession(true) 设置为true可以自动提交事物
package com.liujia.utils;
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;
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
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();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
// SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
在test.jiava下创建测试类MyTest
注意:UserMapper为接口
UserMapper.xml是写sql语句
MyTest是用来实现方法的
增删改查的实现
查询全部
主要用来看环境配置是否正确
接口
package com.liujia.dao;
import com.liujia.pojo.User;
import java.util.List;
public interface UserMapper {
//查询全部
List<User> selectById();
}
sql
<?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">
<mapper namespace="com.liujia.dao.UserMapper">
<select id="selectById" resultType="com.liujia.pojo.User">
select * from mybatis.user
</select>
</mapper>
实现方法
import com.liujia.dao.UserMapper;
import com.liujia.pojo.User;
import com.liujia.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
//查询全部
@Test
public void selectById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectById();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
}
结果如下:
注意:columnNumber: 18; 1 字节的 UTF-8 序列的字节 1 无效。
提示这个报错 将UTF-8 修改成 UTF8
查询单个ID
接口
package com.liujia.dao;
import com.liujia.pojo.User;
import java.util.List;
public interface UserMapper {
//查询全部
List<User> selectById();
//查询单个ID
User selectById2(int id);
}
sql
<?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">
<mapper namespace="com.liujia.dao.UserMapper">
<select id="selectById" resultType="com.liujia.pojo.User">
select * from mybatis.user
</select>
<select id="selectById2" resultType="com.liujia.pojo.User">
select *
from mybatis.user
where id = #{id};
</select>
</mapper>
实现方法
import com.liujia.dao.UserMapper;
import com.liujia.pojo.User;
import com.liujia.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
//查询全部
@Test
public void selectById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectById();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
//查询单个ID
@Test
public void selectById2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectById2(2);
System.out.println(user);
sqlSession.close();
}
}
结果
添加用户
第一种 Map实现(Map很万能 推荐使用)
接口
//添加用户
int Insertadd(Map map);
sql 注意:id是自增 可以不添加(看个人喜好)
<!-- 添加-->
<insert id="Insertadd" parameterType="map">
insert into mybatis.user( name, pwd)
values (#{name},#{pwd});
</insert>
实现方法
//添加用户
@Test
public void Insertadd(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<Object, Object> map = new HashMap<>();
map.put("name","豆豆");
map.put("pwd","852");
int add = mapper.Insertadd(map);
System.out.println(add);
sqlSession.commit();
sqlSession.close();
}
结果 (需要看数据库有没有数据)
第二种 方法
接口
//添加用户方法2
int Insertadd2(User user);
sql
<!-- 添加2-->
<insert id="Insertadd2" parameterType="com.liujia.pojo.User">
insert into mybatis.user( name, pwd)
values (#{name},#{pwd});
</insert>
实现方法(虽然没有设置ID 但因为IDEA连接数据库 依然要输入ID值 不然会报错)
//添加用户2
@Test
public void Insertadd2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int add = mapper.Insertadd2(new User(17, "我爱", "编程"));
System.out.println(add);
sqlSession.close();
}
结果
修改用户
接口(万能的map 方法一)
//修改用户
int updatexiugai(Map map);
sql
<!-- 修改用户 -->
<update id="updatexiugai" parameterType="map">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
实现方法
//修改用户
@Test
public void updatexiugai(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<Object, Object> map = new HashMap<>();
map.put("id","16");
map.put("name","点点");
map.put("pwd","999");
int xiugai = mapper.updatexiugai(map);
if (xiugai>0){
System.out.println("修改成功");
}
sqlSession.close();
}
结果
方法二
接口
//修改一个用户2
int updateUser(User user);
sql
<!-- 修改用户2 -->
<update id="updateUser" parameterType="com.liujia.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
实现方法
//修改用户2
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int Ikun = mapper.updateUser(new User(17, "爱Ikun", "111"));
if (Ikun>0){
System.out.println("chengong");
}
sqlSession.close();
}
结果
删除用户
map方法
接口
//删除用户2
int deleteById2(Map map);
sql
<!-- 删除2 -->
<delete id="deleteById2" parameterType="map">
delete from mybatis.user where id=#{id};
</delete>
实现
//删除用户2
@Test
public void deleteById2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<Object, Object> map = new HashMap<>();
map.put("id",18);
int sc = mapper.deleteById2(map);
System.out.println(sc);
sqlSession.close();
}
接口(第二种方法)
//删除用户
int deleteById(int id);
sql
<!-- 删除 -->
<delete id="deleteById" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
实现方法
//删除用户
@Test
public void deleteById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int sc = mapper.deleteById(17);
System.out.println(sc);
sqlSession.close();
}
增删改查-使用注解开发
- 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
- 根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
- 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
- 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
万变不离其宗
注意:利用注解开发就不需要mapper.xml映射文件了 .
我们在我们的接口中添加注解
package com.kuang.dao;
import com.kuang.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
//查询全部
@Select("select * from user")
List<User> getUser();
//查询ID(@Param("id") int id);可以有多个参数
@Select("select * from user where id=#{id}")
User selectUserById(@Param("id") int id);
//添加
@Insert("insert into user(id, name, pwd) VALUE (#{id},#{name},#{pwd})")
int addUsers(User user);
//修改
@Update("update user set name = #{name},pwd=#{pwd} where id=#{id}")
int updatedemo(User user);
//删除
@Delete("delete from user where id=#{id};")
int shanchu( int id);
}
在mybatis的核心配置文件中注入(一开始的时候已经添加 自行查看)
<!--使用class绑定接口-->
<mappers>
<mapper class="com.kuang.mapper.UserMapper"/>
</mappers>
实现方法、进行测试 (创建一个UserMapperTest)
import com.kuang.dao.UserMapper;
import com.kuang.pojo.User;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
//查询全部
@Test
public void getUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.getUser();
System.out.println(user);
sqlSession.close();
}
//查询用户id
@Test
public void selectUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(2);
System.out.println(user);
sqlSession.close();
}
//添加
@Test
public void addUsers(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUsers(new User(10, "上弹", "545"));
// MybatisUtils设置为true 自动提交事务不再需要
//sqlSession.commit();
sqlSession.close();
}
//修改
@Test
public void UserMapper(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int xiugai = mapper.updatedemo(new User(10, "修改", "666888"));
System.out.println(xiugai);
sqlSession.close();
}
//删除
@Test
public void shanchu(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int shanchu = mapper.shanchu(10);
System.out.println(shanchu);
sqlSession.close();
}
}