MyBatis注解进行数据库的增删改查单表操作

一、数据准备

1、jar包

junit-4.9.jar
log4j-1.2.17.jar
mybatis-3.5-2.jar
mysql-connector-java-5.1.49.jar

2、配置文件

配置文件 jdbc.properteis

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db5
username=root
password=root
(这里删掉
第一行:调用Driver方法,是用来连接MySQL5的,固定写法
第二行:连接数据库所需数据,jdbc:mysql://IP地址:端口号/数据库名
后面两行:数据库登录用户名和密码,需要自己修改)

配置文件 log4j.properties (显示日志的,最好不要修改)

# Global logging configuration
# 这里的DEBUG 代表的是错误级别,总共有五个
# error  WARN  INFO  DUBUG
log4j.rootLogger=DEBUG, stdout
# Console cutput
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t} - %m%n

核心配置文件 MyBatisConfig,xml

<?xml version="1.0" encoding="UTF-8" ?>

<!--MyBatis的dtd约束-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--============================================核心配置文件=====================================================-->

<!--核心根标签-->
<configuration>
<!--    引入数据库连接的配置文件-->
    <properties resource="jdbc.properties"/>
    
    <!--配置LOG4J-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>
    
<!--起别名-->
    <typeAliases>
        <package name="com.yx.bean"/><!--通用的方法,所有的bean类都会被起别名,默认为类名,首字母小写-->
    </typeAliases>
    
<!--    帮助获取数据库连接的配置   -->
<!--    设置要使用的配置,这里的 default 需要和 id 保持一致-->
    <!--environments 里面配置数据库环境,环境可以有多个  default属性指定使用的是哪个环境-->
    <environments default="mysql">
        <!--environment配置数据库环境,  id为唯一标识 -->
        <environment id="mysql">
            <!--transactionManager 事务管理,采用JDBC默认的事务-->
            <transactionManager type="JDBC"></transactionManager><!--相关事务的支持,这里采用的是JDBC提供的事务-->
            <!--dataSource  代表的数据源,type属性代表连接池-->
            <dataSource type="POOLED"><!--数据源,这里代表的是一个数据库连接池-->
                <!--通过配置文件获取数据库配置-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--配置映射文件  -->
    <mappers>
        <package name="com.yx.mapper"/><!--指定接口所在的包的名称-->
    </mappers>
</configuration>

3、Javabean

准备一个Student类,包括 id int 对应主键,name String,age int

4、数据表

在数据库中创建一个数据表 student ,并插入一些数据

create table student (
	id int primary key auto_increment,
	name varchar(20),
	age int
);
insert into student values
	(null,'千',23),
	(null,'糊',21),
	(null,'没',23),
	(null,'凯',21),
	(null,'赖',112032),
	(null,'咔',26);

5、mapper接口,用来编写SQL语句

mapper接口中的内容很简单,只有方法和SQL语句,现在先创建一个空接口,内容会在下面写上
(接口中需要导入的包,在idea中会自动进行导入)

package com.yx.mapper;
public interface UseMysqlMapper {
}

以下所用注解都是导入的jar包中的

二、查询全部

目的,查询出student表中全部数据并且显示出来

mapper接口中的方法及注解编写的SQL语句

// 查询全部数据
    @Select("select * from student")   // 使用Select注解进行编写SQL语句,参数就是要执行的SQL语句,返回值由方法来决定
    public abstract List<Student> selectAll();

测试方法编写步骤:

  1. 获取核心配置文件的输入流对象
  2. 获取SqlSessionFactory工厂类对象
  3. 获取SqlSession对象
  4. 通过SqlSession对象中的getMapper()方法获取StudentMapper接口的实现类对象(底层用的是类加载器的形式)
  5. 调用实现类对象中的selectAll()方法,查询数据表中全部数据,并且返回一个封装好的List集合(泛型是Student)
  6. 输出集合内容
  7. 释放资源
// 查询全部数据
    @Test
    public void selectAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = build.openSession(true);
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List<Student> list = mapper.selectAll();
        for (Student student : list) {
            System.out.println(student);
        }

        sqlSession.close();
        is.close();
    }

根据id进行查询

mapper接口的方法及SQL语句
( #{} :从方法参数中获取数据,这里是获取方法参数中数据名为id的数据值)

    // 根据id进行查询
    @Select("select * from student where id=#{id}") //注解Select,专用来进行查询数据,
    public abstract Student selectById(Integer id); //

测试类中的方法(偷个懒,就把一些内容整合到一行了)

    @Test  /* 根据id进行查询数据表中的数据 */
    public void selectById() throws IOException {
    	// 获取UseMysqlMapper接口的实现类对象(底层用的是类加载器的形式)
        UseMysqlMapper mapper = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")).openSession(true).getMapper(UseMysqlMapper.class);
        Student student = mapper.selectById(2);
        System.out.println(student);
    }

添加数据

mapper接口中的方法及SQL语句
添加数据使用的是Insert注解,是插入数据专用,返回值是操作影响数据表的行数,即添加了几条数据
(#{}:获取数据,可以从方法参数中获取数据,这里传入的参数是自定义的Student类对象,对象中封装了三个属性,id、name、age,使用#{}可以获取这三个属性的值,可以放在SQL语句中作为可变参数使用)

    // 添加数据
    @Insert("insert into student values (null,#{name},#{age})")
    public abstract Integer insert(Student student);

测试类中的方法

    @Test  /* 向数据表中添加数据 */
    public void insert() throws IOException {
        UseMysqlMapper mapper = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")).openSession(true).getMapper(UseMysqlMapper.class);
        Student student = new Student(1, "余", 30);
        Integer insert = mapper.insert(student);
        if (insert == 1){
            System.out.println("添加成功");
            return;
        }
        System.out.println("添加失败");
    }

修改表中数据

mapper接口中的代码,根据传入的Student对象中的数据进行修改,返回值是对数据表中数据的影响函数,即修改了几行数据

    // 修改数据
    @Update("update student set name=#{name},age=#{age} where id=#{id}")
    public abstract Integer update(Student student);

测试类中的方法

    @Test  /* 向数据表中添加数据 */
    public void update() throws IOException {
        UseMysqlMapper mapper = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")).openSession(true).getMapper(UseMysqlMapper.class);
        Student student = new Student(1, "花花", 18);
        Integer insert = mapper.update(student);
        if (insert == 1){
            System.out.println("修改成功");
            System.out.println(mapper.selectById(student.getId()));
            return;
        }
        System.out.println("修改失败");
    }

删除表中数据

mapper接口中的方法

    // 删除数据
    @Delete("delete from student where id=#{id}")
    public abstract Integer delete(Integer id);

测试类中的方法

    @Test
    public void delete() throws IOException {
        UseMysqlMapper mapper = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")).openSession(true).getMapper(UseMysqlMapper.class);
        Integer delete = mapper.delete(7);
        if (delete == 1){
            System.out.println("删除成功");
            return;
        }
        System.out.println("删除失败");
    }

========================================================
到这里就已经全部写完了增删改查,通过MyBatis加上注解的方式,还是挺方便的,不过这些都是单表操作,没有多余的外键和约束。后面我会写一写关于多表查询的文章。
**

转发请标注本文链接

**!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值