写点什么

MyBatis 入门

用户头像
小马哥
关注
发布于: 2021 年 02 月 04 日
MyBatis入门

代码实例: 使用 MyBatis 实现 user 表的增删改查 CRUD

准备

创建数据库表


#创建数据库create database mybatis_demo;#创建user表create table user(	uid int primary key auto_increment,    username varchar(40),    sex varchar(10),    birthday date,    address varchar(40));
复制代码


创建 Maven 工程


<dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>      <scope>test</scope>    </dependency>        <!--引入lombok的依赖-->    <dependency>      <groupId>org.projectlombok</groupId>      <artifactId>lombok</artifactId>      <version>1.18.10</version>    </dependency>        <!--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.3</version>    </dependency></dependencies>
复制代码


创建 Mybatis 快速入门

1.创建 POJO 类

package com.nengli51.pojo;
import lombok.Data;
import java.util.Date;
/** * @Date 2021/2/4 */@Datapublic class User {
private int uid; private String username; private String sex; private Date birthday; private String address;}
复制代码


2. 创建 UserDao

package com.nengli51.dao;
import com.nengli51.pojo.User;
import java.util.List;
public interface UserDao { /** * 添加用户 * * @param user */ void addUser(User user);
/** * 删除用户 * * @param uid */ void deleteUser(int uid);
/** * 修改用户 * * @param user */ void updateUser(User user);
/** * 查找用户 * * @param uid * @return */ User findUser(int uid);
/** * 查找所有 * * @return */ List<User> findAll();}
复制代码


3. 创建 UserDao.xml 映射文件


注意: 放置在 resources/"UserDao 相同的路径下"/UserDao.xml

这里的"UserDao 相同的路径下" = 上面的 UserDao 接口的位置: com/nengli51/dao/下面

<?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.nengli51.dao.UserDao">    <select id="findUser" resultType="com.nengli51.pojo.User" parameterType="int">        select *        from user        where uid = #{id};    </select>    <select id="findAll" resultType="com.nengli51.pojo.User">        select *        from user    </select>
<insert id="addUser" parameterType="com.nengli51.pojo.User"> insert into user values (null, #{username}, #{sex}, #{birthday}, #{address}) </insert>
<delete id="deleteUser" parameterType="int"> delete from user where uid = #{uid} </delete>
<update id="updateUser" parameterType="com.nengli51.pojo.User"> update user set username=#{username}, sex=#{sex}, birthday=#{birthday}, address=#{address} where uid = #{uid} </update></mapper>
复制代码

4. 创建 SqlMapConfig.xml 核心配置文件

放置在: resources/目录下


<?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="dev">        <environment id="dev">            <transactionManager type="JDBC"></transactionManager>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>                <property name="username" value="root"/>                <property name="password" value="root"/>            </dataSource>        </environment>    </environments>
<mappers> <mapper resource="com/nengli51/UserDao.xml"></mapper> </mappers></configuration>
复制代码


5. 测试 CRUD

import com.nengli51.dao.UserDao;import com.nengli51.pojo.User;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 org.junit.After;import org.junit.Before;import org.junit.Test;
import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.List;
/** * @Author MaLi * @Date 2021/2/4 */public class TestMybatis {
private UserDao userDao; private SqlSession sqlSession; private InputStream is;
@Before public void init() { try { //1. 创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2. 读取核心配置文件,转换成字节输入流 is = Resources.getResourceAsStream("SqlMapConfig.xml");
//3. 创建SqlSessionFactory对象 SqlSessionFactory sessionFactory = sessionFactoryBuilder.build(is);
//4. 创建SqlSession对象 sqlSession = sessionFactory.openSession();
//5. 创建UserDao的代理对象 userDao = sqlSession.getMapper(UserDao.class);
} catch (IOException e) { e.printStackTrace(); } }
@Test public void testAddUser() { User user = new User(); user.setUsername("小马哥"); user.setAddress("Beijing"); user.setBirthday(new Date()); user.setSex("Male"); userDao.addUser(user); user = userDao.findUser(4); System.out.println(user); }
@Test public void testDeleteUser() { userDao.deleteUser(1); }
@Test public void testUpdateUser() { User user = userDao.findUser(1); user.setUsername("马斯克"); userDao.updateUser(user); user = userDao.findUser(1); System.out.println(user); }
@Test public void testFindUser() { User user = userDao.findUser(1); System.out.println(user); }
@Test public void testFindAll() { List<User> userList = userDao.findAll(); //6, 使用UserDao进行操作 for (User user : userList) { System.out.println(user); }
}
@After public void destroy() throws IOException { //7.提交事务, 关闭资源 sqlSession.commit(); sqlSession.close(); is.close(); }}
复制代码


发布于: 2021 年 02 月 04 日阅读数: 33
用户头像

小马哥

关注

自强不息,厚德载物 2018.12.22 加入

像一棵竹子那样, 不断的扎根积累, 活出节节高的人生!

评论

发布
暂无评论
MyBatis入门