博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mybatis基础-完整CRUD操作
阅读量:4517 次
发布时间:2019-06-08

本文共 7627 字,大约阅读时间需要 25 分钟。

步骤一:mybatis基本配置

1)创建Java项目,在lib下导入mybatis所需要的Jar包,包括链接mysql的mysql-connector-java-5.1.7-bin.jar。

2)在src目录下新建一个mybatis的配置文件

mybatis_conf.xml的内容如下

 db.properties

jdbc.user = rootjdbc.password=123456jdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis0814?useUnicode=true&characterEncoding=utf-8

步骤二:

1)新建表t_user,因为Mybatis不会自动创建数据表,和hibernate不一样,只专注sql

2)定义表的实体类,必须一一对应,否则需要在映射里面设置resultMap结果集映射

User

package com.feng.domain;import java.util.Date;public class User{    // 和表中的字段一一对应,否则需要在对应的Mapper配置文件用到resultMap结果集映射。    private Integer id;    private String username;    private int age;    private Date registerDate;        public User(){}    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public Date getRegisterDate() {        return registerDate;    }    public void setRegisterDate(Date registerDate) {        this.registerDate = registerDate;    }    @Override    public String toString() {        return "User [id=" + id + ", username=" + username + ", age=" + age                + ", registerDate=" + registerDate + "]";    }

 3)在dao的包下,新建sql映射配置xml

UserMapper.xml   必须和实体类对应  格式:实体类+Mapper ,否则自动扫描不出来

insert into t_user(username,age,registerDate) values(#{username},#{age},#{registerDate})
delete from t_user where id = #{id}
update t_user set username = #{username},age=#{age},registerDate=#{registerDate} where id = #{id}

这里注意一点,update、delete 返回值是:更新或删除的行数;无需指明resultClass;但如果有约束异常而删除失败,只能去捕捉异常。 

insert,返回值是:新插入行的主键(primary key);需要包含<selectKey>语句,才会返回主键,否则返回值为null。

4)操作接口

UserMapper.java

package com.feng.dao;import java.util.List;import java.util.Map;import com.feng.domain.User;public interface UserMapper {    //增加一个用户    public void addUser(User user);        //删除一个用户    public void deleteUser(Integer id);        //修改用户信息    public void updateUser(User user);        //得到一个用户    public User getUserById(Integer id);        //得到所有用户    public List
getAllUser(); // 多入参情况下用map public List
getAllUser1(Map
map);}

步骤三

1)新建测试类Test_Crud.java

package com.feng.test;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.HashMap;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.Before;import org.junit.Test;import com.feng.domain.User;public class Test_Crud {    private SqlSessionFactory sqlSessionFactory = null;    @Before    public void init() throws IOException {        // 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)        InputStream inputStream = Resources                .getResourceAsStream("mybatis_conf.xml");        // 创建SqlSessionFactory工厂        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);    }    @Test    public void addUser() {        // 创建并且打开sqlsession        SqlSession sqlSession = null;        try {            sqlSession = sqlSessionFactory.openSession();            User user = new User();            user.setAge(22);            user.setRegisterDate(new Date());            user.setUsername("feng");            sqlSession.insert("com.feng.dao.UserMapper.addUser", user);            sqlSession.commit();            System.out.println(user.getId());        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    @Test    public void deleteUser() {        // 创建并且打开sqlsession        SqlSession sqlSession = null;        try {            sqlSession = sqlSessionFactory.openSession();            sqlSession.delete("com.feng.dao.UserMapper.deleteUser", 2);            sqlSession.commit();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    @Test    public void updateUser() {        // 创建并且打开sqlsession        SqlSession sqlSession = null;        try {            sqlSession = sqlSessionFactory.openSession();            User user = new User();            user.setAge(22);            user.setId(1);            user.setRegisterDate(new Date());            user.setUsername("wei");            sqlSession.update("com.feng.dao.UserMapper.updateUser", user);            sqlSession.commit();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    @Test    public void getUserById() {        // 创建并且打开sqlsession        SqlSession sqlSession = null;        try {            sqlSession = sqlSessionFactory.openSession();            User user = sqlSession.selectOne(                    "com.feng.dao.UserMapper.getUserById", 1);            System.out.println(user.toString());            sqlSession.commit();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    @Test    public void getAllUser() {        // 创建并且打开sqlsession        SqlSession sqlSession = null;        try {            sqlSession = sqlSessionFactory.openSession();            java.util.List
list = sqlSession .selectList("com.feng.dao.UserMapper.getAllUser"); for (User user : list) { System.out.println(user.toString()); } sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } @Test // 多入参情况下,用map public void getAllUser1() { // 创建并且打开sqlsession SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); HashMap
map = new HashMap
(); map.put("age", 20); map.put("username", "feng"); java.util.List
list = sqlSession.selectList( "com.feng.dao.UserMapper.getAllUser1", map); for (User user : list) { System.out.println(user.toString()); } sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } }}

最后的结构图如下

 

转载于:https://www.cnblogs.com/jinghuyue/p/9487377.html

你可能感兴趣的文章
运维角度浅谈MySQL数据库优化
查看>>
ORA-02049: 超时: 分布式事务处理等待锁
查看>>
后缀数组SA
查看>>
bzoj3011 可并堆
查看>>
bzoj 3580 冒泡排序 乱搞+思维
查看>>
AJAX实例演示加载xml
查看>>
MyBatis笔记二:配置
查看>>
更换pip源,解决pip install安装包慢的问题
查看>>
php 装饰者模式
查看>>
zabbix 监控基础
查看>>
Java BigDecimal类
查看>>
公务员“上班睡觉”为何会被强势围观?
查看>>
string
查看>>
2018福大软工实践第七次作业
查看>>
Gradle 构建 android 应用常见问题解决指南
查看>>
对话框--pop&dialog总结
查看>>
Array.isArray() 和 isObject() 原生js实现
查看>>
1064. Complete Binary Search Tree
查看>>
DOM元素的大小和位置
查看>>
进程间通信
查看>>