环境:
思路:搭建环境–>导入Mybatis–>编写代码–>测试!
Github 代码(可以直接运行):
https://github.com/KUANG-CHENG/Spring
Mybatis_sql 文件夹
UPDATE `mybatis`.`user` SET `id` = '1', `name` = 'kc', `pwd` = '123' WHERE (`id` = '1');
UPDATE `mybatis`.`user` SET `id` = '2', `name` = 'kobe', `pwd` = '456' WHERE (`id` = '2');
UPDATE `mybatis`.`user` SET `id` = '3', `name` = 'bryant', `pwd` = '789' WHERE (`id` = '3');
(1)新建一个普通的 Maven 工程
(2) 删除 src 目录
导入3个jar包:
Maven工程中 pom.xml 导入依赖代码:
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
编写 Mybatis-config.xml 配置文件。
XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)。后面会再探讨 XML 配置文件的详细内容,这里先给出一个简单的示例:
<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"/>
<property name="username" value="root"/>
<property name="password" value="Kc635908933"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml">mapper>
mappers>
configuration>
编写 MybatisUtils 工具类,代码如下:
package com.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();
}
}
创建 User 实体类,与数据库相对应:
package com.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 + '\'' +
'}';
}
}
创建 UserDao 接口类:
package com.dao;
import com.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
接口实现类由原来的 UserDaoImpl 转变为一个 Mapper配置文件:
<mapper namespace="com.dao.UserDao">
<select id="getUserList" resultType="com.pojo.User">
select * from mybatis.user
select>
mapper>
通用步骤:
编写接口 --> 编写对应的UserMapper中的 sql 语句 --> 测试
接口类如下:
public interface UserMapper {
// 查询所有用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
// 模糊查询
List<User> getUserLike(String value);
// 使用map添加用户
int addUser2(Map<String, Object> map);
// 插入
int addUser(User user);
// 更新
int updateUser(User user);
// 删除
int deleteUser(int id);
}
UserMapper.xml:
<select id="getUserList" resultType="com.pojo.User">
select * from mybatis.user
select>
test 测试代码:
@Test
public void getUserList() {
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
UserMapper.xml:
<select id="getUserById" resultType="com.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
select>
test 测试代码:
@Test
public void getUserById(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(4);
System.out.println(user);
//关闭SqlSession
sqlSession.close();
}
UserMapper.xml:
<insert id="addUser" parameterType="com.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
insert>
test 测试代码:
@Test
public void addUser(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.addUser(new User(4,"kuangcheng","123456"));
System.out.println(num);
// 提交事物
sqlSession.commit();
// 查询所有事物
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
UserMapper.xml:
<update id="updateUser" parameterType="com.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
update>
test 测试代码:
@Test
public void updateUser(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.updateUser(new User(4,"kc","88888888"));
System.out.println(num);
// 提交事物
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
UserMapper.xml:
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
delete>
mapper>
test 测试代码:
@Test
public void deleteUser(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方式一:getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.deleteUser(52);
System.out.println(num);
// 提交事物
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
UserMapper.xml:
<insert id="addUser2" parameterType="map">
insert into mybatis.user(id, name, pwd) values (#{Userid},#{Username},#{Userpwd})
insert>
test 测试代码:
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 创建 map
Map map = new HashMap();
map.put("Userid", 12);
map.put("Username", "cat");
map.put("Userpwd", "1234595");
int num = userMapper.addUser2(map);
System.out.println(num);
// 提交事物
sqlSession.commit();
// 关闭 sqlSession
sqlSession.close();
}
UserMapper.xml:
<select id="getUserLike" resultType="com.pojo.User" parameterType="String">
select * from mybatis.user where name like "%"#{value}"%"
select>
test 测试代码:
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserLike("李");
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}