Java中使用Mybatis操作数据库主要有两种方法:注解和xml配置,注解相对比较简单和方便,两种方式的效果一致。本文以注解的方式说明用Mybatis访问数据库的方法


一、创建数据表(MySql)
1
2
3
4
5
6
7
8
9
-- ----------------------------
-- Table structure for admininfo
-- ----------------------------
DROP TABLE IF EXISTS `admininfo`;
CREATE TABLE `admininfo` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `AdminName` varchar(20) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;

二、创建mybatis的配置文件:mybatisConf.xml,由于使用maven进行管理,所以放在java-->resources文件夹下,其它位置也可以,只有最终在\target\classes\mybatisConf.xml生成文件即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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://127.0.0.1/test" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 注册映射接口,该接口文件包含了数据访问方法和SQL -->
        <mapper class="dal.dataaccess.IAdminInfoMapper" />
    </mappers>
</configuration>


三、创IAdminInfoMapper文件(本文中包名为dal.dataaccess)

    该接口的功能主要是提供对AdminInfo表的数据操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package dal.dataaccess;
 
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import dal.beans.AdminInfo;
import dal.beans.AdminRightInfo;
 
public interface IAdminInfoMapper {
     
    //使用@Select注解指明getById方法要执行的SQL
    @Select("select * from admininfo where id=#{id}")
    public AdminInfo getById(int id);
     
    //使用@Select注解指明getAll方法要执行的SQL
    @Select("select * from admininfo")
    public List<AdminInfo> getAll();
     
    //使用@Insert注解指明add方法要执行的SQL
    @Insert("insert into admininfo(adminName) values(#{adminName})")
    public int add(AdminInfo user);
     
    //使用@Update注解指明update方法要执行的SQL
    @Update("update admininfo set adminName=#{adminName} where id=#{id}")
    public int update(AdminInfo user);
     
    //使用@Delete注解指明deleteById方法要执行的SQL
    @Delete("delete from admininfo where id=#{id}")
    public int deleteById(int id);
}

四、定义操作数据库的公共方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package framework.utils;
 
import java.io.InputStream;
 
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
public class MyBatisUtil {
    /**
     * 获取SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        String resource = "mybatisConf.xml";
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        return factory;
    }
 
    /**
     * 获取SqlSession
     *
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }
 
    /**
     * 获取SqlSession
     *
     * @param isAutoCommit
     *            true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 false
     *            表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.
     *            commit()提交事务
     * @return SqlSession
     */
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}


五、对adminInfo表进行增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package test;
 
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import dal.beans.*;
import framework.utils.MyBatisUtil;
import dal.dataaccess.*;
 
public class MybatisAnnotationTest {
 
    @Test
    public void Select() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        // 得到AdminInfoMapper接口的实现类对象,IAdminInfoMapper接口的实现类对象由sqlSession.getMapper(IAdminInfoMapper.class)动态构建出来
        IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper.class);
        // 执行查询操作,将查询结果自动封装成User返回
        AdminInfo bean = mapper.getById(13);
        // 使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        System.out.println(bean.getId());
        System.out.println(bean.getAdminName());
    }
 
    @Test
    public void SelectAll() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper.class);
        List<AdminInfo> bean = mapper.getAll();
        sqlSession.close();
 
        System.out.println(bean.size());
    }
 
    @Test
    public void Insert() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper.class);
 
        AdminInfo bean = new AdminInfo();
        bean.setAdminName("Admin" + System.currentTimeMillis());
 
        int result = mapper.add(bean);
        sqlSession.commit();
        sqlSession.close();
 
        System.out.println(result);
    }
 
    @Test
    public void Update() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper.class);
 
        AdminInfo bean = new AdminInfo();
        bean.setId(12);
        bean.setAdminName("Admin" + System.currentTimeMillis());
 
        int result = mapper.update(bean);
        sqlSession.commit();
        sqlSession.close();
 
        System.out.println(result);
    }
 
    @Test
    public void Delete() {
 
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        IAdminInfoMapper mapper = sqlSession.getMapper(IAdminInfoMapper.class);
 
        int result = mapper.deleteById(12);
        sqlSession.commit();
        sqlSession.close();
 
        System.out.println(result);
    }
}


六、由于使用了maven进行依赖管理,pom.xml还需要添加

1
2
3
4
5
6
7
8
9
10
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.3.0</version>
    </dependency>



Mybatis注解方法操作数据库的更多相关文章

  1. JavaWeb_(Mybatis框架)JDBC操作数据库和Mybatis框架操作数据库区别_一

    系列博文: JavaWeb_(Mybatis框架)JDBC操作数据库和Mybatis框架操作数据库区别_一 传送门 JavaWeb_(Mybatis框架)使用Mybatis对表进行增.删.改.查操作_ ...

  2. JavaWeb_(Spring框架)整合Mybatis加入事务操作数据库

    整合Mybatis a)导包: i.Spring:基本包.aop.aspects.jdbc.tx.test: ii.Mybatis:mybatis-3.4.6 iii.整合包:mybatis-spri ...

  3. php 用封装类的方法操作数据库和批量删除

    封装类 <?php class DBDA { public $host="localhost"; //服务器地址 public $uid="root"; ...

  4. Android中SQLite数据库操作(2)——使用SQLiteDatabase提供的方法操作数据库

    如果开发者对SQL语法不熟,甚至以前从未使用过任何数据库,Android的SQLiteDatabase提供了insert.update.delete或query语句来操作数据库. 一.insert方法 ...

  5. MyBatis中sqlSession操作数据库,不报错但无法实现数据修改(增、改、删)

    public void addCustomerTest() throws Exception { SqlSession sqlSession = MyBatisUtils.getSession(); ...

  6. DatabaseFactory.CreateDatabase 方法操作数据库

    using Microsoft.Practices.EnterpriseLibrary.Data;using Microsoft.Practices.EnterpriseLibrary.Data.Sq ...

  7. 05 Mybatis的CRUD操作和Mybatis连接池

    1.CRUD的含义 CRUD是指在做计算处理时的增加(Create).读取(Retrieve)(重新得到数据).更新(Update)和删除(Delete)几个单词的首字母简写.主要被用在描述软件系统中 ...

  8. Mybatis高级:Mybatis注解开发单表操作,Mybatis注解开发多表操作,构建sql语句,综合案例学生管理系统使用接口注解方式优化

    知识点梳理 课堂讲义 一.Mybatis注解开发单表操作 *** 1.1 MyBatis的常用注解 之前我们在Mapper映射文件中编写的sql语句已经各种配置,其实是比较麻烦的 而这几年来注解开发越 ...

  9. 使用mybatis plus 操作数据库

    mybatis plus 是基于mybatis 的一个增强包,比 mybatis 更加容易使用. 特点: 1.分页支持 2.支持自定义查询. 3.简单的情况下,不需要写map.xml 文件 4.支持租 ...

随机推荐

  1. 设计模式之笔记--原型模式(Prototype)

    原型模式(Prototype) 定义 原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象. 类图 描述 提供一个克隆自身的接口--Clone方法. 应用场景 ...

  2. UNIX shell 学习笔记 一 : 几个shell的规则语法对比

    1. 查看系统有哪些可用的shell cat /etc/shell 2. 每种shell都有一个特殊内置变量来存上一条命令的退出状态,例: C/TC shell $status % cp fx fy ...

  3. 关于HTML,css3自适应屏幕,自适应宽度

    设置了在不同分辨率下,显示的css样式: @media screen and (min-width:1080px){ .box{ width: 1080px;}.content{width: 1040 ...

  4. linux命令(29):cd命令

    例1:进入系统根目录 cd  / cd ../.. // [直接退到当前根目录] 例2:使用 cd 命令进入当前用户主目录 cd 例3:跳转到指定目录 cd  /home/test 例4:返回进入此目 ...

  5. 使用python读取文本中结构化数据

    需求 read some .txt file in dir and find min and max num in file. solution: echo *.txt > file.name ...

  6. BootStrap 实现导航栏nav透明,nav子元素文字不透明

    在给nav 的属性赋值 opacity:0.0透明度时会导致nav内子元素会继承opacity属性.此时再对子元素赋值opacity:1.0 时会导致 子元素实际opacity值为0.0*1.0=0. ...

  7. js解析与序列化json数据(一)json.stringify()的基本用法

    对象有两个方法:stringify()和parse().在最简单的情况下,这两个方法分别用于把JavaScript对象序列化为JSON字符串和把JSON字符串解析为原生JavaScript 早期的JS ...

  8. 用webpy实现12306余票查询

    效果

  9. web前端零基础入门学习!前端真不难!

    现在互联网发展迅速,前端也成了很重要的岗位之一,许多人都往前端靠拢,可又无能为力,不知所措,首先我们说为什么在编程里,大家都倾向于往前端靠呢?原因很简单,那就是,在程序员的世界里,前端开发是最最简单的 ...

  10. CentOS7.5安装下载工具

    ### 视频下载工具 [you-get](https://github.com/soimort/you-get) 和 [youtube-dl](https://github.com/rg3/youtu ...