Mybatis持久层框架入门之CRUD实例
关于作者
🍓 博客主页:作者主页
🍓 简介:JAVA领域优质创作者🥇、一名在校大三学生🎓、在校期间参加各种省赛、国赛,斩获一系列荣誉🏆
🍓 关注我:关注我学习资料、文档下载统统都有,每日定时更新文章,励志做一名JAVA资深程序猿👨?💻
3、MyBatis第一个程序
思路流程:搭建环境–>导入Mybatis—>编写代码—>测试
3.1、代码演示
? 1.搭建实验数据库
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,'hhh','123456'),(2,'张
三','abcdef'),(3,'李四','987654');
? 2.导入MyBatis相关 jar 包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
- 编写MyBatis核心配置文件
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>
<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=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/sxau/dao/UserMapper.xml"/>
</mappers>
</configuration>
- 编写MyBatis工具类
MybatisUtils.java
package com.sxau.utils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils{
private static SqlSessionFactory sqlSessionFactory;
static {
try {
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();
}
}
- 创建实体类
package com.sxau.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 + '\'' +
'}';
}
}
- 编写Mapper接口类
package com.sxau.dao;
import com.sxau.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
}
- 编写Mapper.xml配置文件
namespace 十分重要,不能写错!
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxau.dao.UserMapper">
<select id="getUserList" resultType="com.sxau.pojo.User">
select * from mybatis.user
</select>
</mapper>
- 编写测试类Junit 包测试
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
List<User> userList = sqlSession.selectList("com.sxau.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
- 运行测试
3.2、问题说明
可能出现问题说明:Maven静态资源过滤问题
在pom.xml中加入以下代码块
<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>
4、CRUD操作
4.1、namespace
- 将上面案例中的UserMapper接口改名为 UserDao;
- 将UserMapper.xml中的namespace改为为UserDao的路径 .
- 再次测试
结论
配置文件中namespace中的名称为对应Mapper接口或者Dao接口的完整包名,必须一致!
4.2、select
- select标签是mybatis中最常用的标签之一
- select语句有很多属性可以详细配置每一条SQL语句
- id
- 命名空间中唯一的标识符
- 接口中的方法名与映射文件中的SQL语句ID 一一对应
- parameterType
- 传入SQL语句的参数类型 。【万能的Map,可以多尝试使用】
- resultType
需求:根据id查询用户
- 在UserMapper中添加对应方法
package com.sxau.dao;
import com.sxau.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
}
- 在UserMapper.xml中添加Select语句
<select id="getUserById" parameterType="int" resultType="com.sxau.pojo.User">
select * from mybatis.user where id = #{id}
</select>
- 测试类中进行测试
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
小练习:根据 密码 和 用户名 查询用户信息
思路一:直接在方法中传递参数
- 在接口方法的参数前加 @Param属性
- Sql语句编写的时候,直接取@Param中设置的值即可,不需要单独设置参数类型
User selectUserByNameAndPwd(@Param("username") String username,@Param("pwd") String pwd);
思路二:使用万能的Map
? 1. 在接口方法中,参数直接传递Map;
User selectUserByNP2(Map<String,Object> map);
- 编写sql语句的时候,需要传递参数类型,参数类型为map
<select id="selectUserByNP2" parameterType="map"
resultType="com.sxau.pojo.User">
select * from user where name = #{username} and pwd = #{pwd}
</select>
- 在使用方法的时候,Map的 key 为 sql中取的值即可,没有顺序要求!
@Test
public void selectUserByNP2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("username","hhh");
map.put("pwd","123456");
User user = mapper.selectUserByNP2(map);
sqlSession.commit();
sqlSession.close();
}
如果参数过多,我们可以考虑直接使用Map来实现参数传递,如果参数比较少,直接传递参数即可
4.3、insert
我们一般使用insert标签进行插入操作,它的配置和select标签差不多!
需求:给数据库增加一个用户
- 在UserMapper接口中添加对应的方法
int addUser(User user);
- 在UserMapper.xml中添加insert语句
<insert id="addUser" parameterType="com.sxau.pojo.User">
insert into mybatis.user(id, name, pwd) VALUES (#{id},#{name},#{pwd});
</insert>
? 3.在测试类中进行测试
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4,"hahah","123123"));
sqlSession.commit();
sqlSession.close();
}
注意点:增、删、改操作需要提交事务!
4.4、update
我们一般使用update标签进行更新操作,它的配置和select标签差不多!
需求:修改用户的信息
- 在UserMapper接口中添加对应的方法
int updateUser(User user);
- 在UserMapper.xml中添加update语句
<update id="updateUser" parameterType="com.sxau.pojo.User">
update mybatis.user
set name=#{name},pwd=#{pwd}
where id=#{id};
</update>
? 3.在测试类中进行测试
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"qqq","123123"));
sqlSession.commit();
sqlSession.close();
}
4.5、delete
我们一般使用delete标签进行删除操作,它的配置和select标签差不多!
需求:根据id删除一个用户
- 在UserMapper接口中添加对应的方法
int deleteUser(int id);
- 在UserMapper.xml中添加delete语句
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
? 3.在测试类中进行测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
小结
- 所有的增删改操作都需要提交事务!
- 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
- 根据业务的需求,可以考虑使用map传递参数!
- 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!
4.6、拓展思维
在MyBatis中模糊查询like语句该怎么写?
第1种:在Java代码中添加sql通配符。
List<User> getUserLike(String value);
<select id="getUserLike" resultType="com.sxau.pojo.User">
select * from mybatis.user where name like #{value}
</select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("%李%");
for (User user : userLike) {
System.out.println(user);
}
}
第2种:在sql语句中拼接通配符,会引起sql注入
List<User> getUserLike(String value);
<select id=”getUserLike”>
select * from foo where bar like "%"#{value}"%"
</select>
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userLike = mapper.getUserLike("李");
for (User user : userLike) {
System.out.println(user);
}
}
|