发布时间:2024-10-01 17:01
环境
基础
数据持久化
Dao层、Service层、Controller层
思路:搭建环境 --> 导入MyBatis --> 编写代码 --> 测试
搭建数据库
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE user(
id INT(20) NOT NULL PRIMARY KEY,
name VARCHAR(30) DEFAULT NULL,
pwd VARCHAR(30) DEFAULT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO user VALUES (1,'狂神','123456');
INSERT INTO user VALUES (2,'张三','123456');
INSERT INTO user VALUES (3,'李四','123456');
SELECT * FROM user
新建项目
创建一个普通的maven项目
删除src目录 (就可以把此工程当做父工程了,然后创建子工程)
导入maven依赖
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>Mybatis_StudyartifactId>
<packaging>pompackaging>
<version>1.0-SNAPSHOTversion>
<modules>
<module>Mybatis_01module>
modules>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.23version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
project>
创建Module
编写mybatis工具类
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=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
mappers>
configuration>
package com.kuang.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;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
//用Resources类把这个资源加载进来变成流
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过builder加载流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例
//SqlSession完全包含了面向数据库执行SQL命令所需的所有方法
public static SqlSession getsqlSession(){
return sqlSessionFactory.openSession();
}
}
package com.kun.pojo;
//也叫model,简单的javabean就是数据库对应的实体类
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 + '\'' +
'}';
}
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
//Dao以后相当于mapper
//DAO(Data Access Object)数据访问对象。
// 主要的功能就是用于进行数据操作的,
// 在程序的标准开发架构中属于数据层的操作
public interface UserDao {
List<User> getUserList();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.UserDao">
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user
select>
mapper>
异常:org.apache.ibatis.binding.BindingException: Type interface com.kun.dao.UserDao is not known to the MapperRegistry.
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
mappers>
MapperRegistry.–>映射器注册
java.lang.ExceptionInInitializerError---->资源导出失败的问题(资源过滤问题)
maven由于他的约定大于配置,我们之后可能遇到我的写的配置文件无法被导出或者生效的问题,jvm最后执行target目录文件,其中是没有Mapper.xml配置文件的,需要手动导入。或者作出一下操作:
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
package com.kuang.dao;
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 UserDaoTest {
@Test
public void test(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getsqlSession();
//方式一:getMapper
//执行sql,先通过接口UserDao得到接口的返回值
UserDao userDao = sqlSession.getMapper(UserDao.class);
//通过userDao调用getUserList方法拿到sql的结果集
List<User> userList = userDao.getUserList();
//方法二:
List<User> userList = sqlSession.selectList("com.kuang.UserDao.getUserList");
//需要自己根据接口返回类型去调用不同的函数,但是第一种就直接省了这一步,根据mapper里接口类型和resultType直接返回
for(User user:userList){
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
}
会出现的问题
namespace中的包名要和Dao/mapper接口的包名一致!
选择,查询语句:
1.接口编写
//查询全部用户信息
List<User> getUserList();
2.编写对应的mapper中的sql语句
<select id="getUserList" resultType="com.kun.pojo.User">
select * from mybatis.user
select>
3.测试
@Test
public void getUserList(){
//第一步: 获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
//方式二:了解
//List userList1 = sqlSession.selectList("com.kun.dao.UserDao.getUserList");
for(User user : userList){
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
查询单个用户
<select id="getUserById" parameterType="int" resultType="com.kun.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();
}
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
insert>
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getsqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4,"wangwu","888888"));
if(res>0){
System.out.println("插入成功!!!");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
<update id="updateUSer" parameterType="com.kun.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
update>
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getsqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"王五","123123"));
sqlSession.commit();
System.out.println("修改成功!!!");
sqlSession.close();
}
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
delete>
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getsqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
System.out.println("删除成功!!!");
sqlSession.close();
}
//万能的Map 一枝独秀
int addUSer2(Map<String,Object> map);
<insert id="addUSer2" parameterType="map">
insert into mybatis.user (id,name) values(#{userid},#{username});
insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("userid",7);
map.put("username","牛牛");
int res = mapper.addUSer2(map);
if(res > 0){
System.out.println("提交成功");
}
//提交事物 释放资源
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可! 【paramType = “map”】
对象传递参数,直接在sql中去对象的属性即可! 【parameterType = “Object”】
只有一个基本参数的情况下,可以直接在sql中取到! 【即parameType可省略】
多个参数用Map,或者注解!!!
模糊查询怎么写?
1.Java代码执行的时候,传递通配符%%
List<User> userlist = mapper.midUser("%大%");
2.在sql拼接中使用通配符!! (同上比更安全)
select * from mybatis.user where name like "%"#{value}"%"
//增、删、改 提交事物
sqlSession.commit();
//释放资源
sqlSession.close();
如果还出现上诉的这样的类似错误,检查UserMapper.xml的**#{ }**中是否写了类的属性!!!