基于maven实现mybatis的简单操作(增删改查)

本文档详细介绍了如何使用MyBatis框架进行数据库操作,包括创建数据库表、建立Maven项目、配置相关依赖、编写实体类、DAO接口及Mapper文件,以及主配置文件的设置。同时,提供了测试代码以展示增删查改操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先创建一个数据库中的表格可以通过ddl和dmlSQL语句创造

create database mybatis_demo; use mybatis_demo; CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL COMMENT '用户名称', `birthday` datetime default NULL COMMENT '生日', `sex` char(1) default NULL COMMENT '性别', `address` varchar(256) default NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'老王','2018-02-27 17:47:08','男','北京'),(2,'熊大','2018-03-02 15:09:37','女','上海'),(3,'熊二','2018-03-04 11:34:34','女','深圳'),(4,'光头强','2018-03-04 12:04:06','男','广州');

 2、建立maven项目,并在pom.xml文件中根据定位依赖导入包

1. 引入MyBatis的3.4.5的版本的坐标

2. 引入MySQL驱动的jar包,5.1.6版本

3. 引入Junit单元测试的jar包

4. 引入log4j的jar包,1.2.12版本(需要引入log4j.properties的配置文件,放到resource文件夹下)

<dependencies>
<!--mybatis核心包--> 
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

3、编写User的实体类,属性尽量使用包装类型

package com.qcby.entity;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private Integer id;
    private  String username;
    private  String sex;
    private  Date birthday;
    private  String address;

    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 String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}

4、编写UserDao的接口和方法

package com.qcby.dao;

import com.qcby.entity.User;

import java.util.List;

public interface UserDao {
    public List<User> findAll();
    public List<User> findById(int id);
    public void add(User user);
    public void delete(int id);
    public void update(User user);
}

5、在resources目录下,创建mapper文件夹。编写UserDao.xml的配置文件,导入约束文件

<?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.qcby.dao.UserDao">
    <select id="findAll" resultType="com.qcby.entity.User">
        select * from user;
    </select>
    <select id="findById" parameterType="int" resultType="com.qcby.entity.User">
        select * from user where id=#{id};
    </select>
    <insert id="add" parameterType="com.qcby.entity.User">
        insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});
    </insert>
    <delete id="delete" parameterType="int">
        delete from user where id=#{id};
    </delete>
    <update id="update" parameterType="com.qcby.entity.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id};
    </update>

</mapper>

6、编写主配置文件,在resources目录下创建SqlMapConfig.xml的配置文件(其实名称可以任意),导入对应的约束,编写主配置文件。

这里需要注意的是,代码连的是我的MySQL所以如果用代码,就改成你自己的。

<?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="mysql">
        <environment id="mysql">
            <!--配置事务的类型,使用本地事务策略-->
            <transactionManager type="JDBC"></transactionManager>
            <!--是否使用连接池 POOLED表示使用连接池,UNPOOLED表示不使用连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_day1"/>
                <property name="username" value="root"/>
                <property name="password" value="2020"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserDao.xml"></mapper>
    </mappers>

</configuration>

7、测试程序

package com.qcby.test;

import com.qcby.dao.UserDao;
import com.qcby.entity.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.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class TestUser {
    InputStream in;
    SqlSession session;
    UserDao mapper;
    @Before
    public void init() throws IOException {
        //加载主配置文件,目的是为了构建SqlSessionFactory对象
        in = Resources.getResourceAsStream("mybatis.xml");
        //创建sqlsessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //创建sqlsession对象
        session = factory.openSession(true);
        //调用方法
        mapper = session.getMapper(UserDao.class);

    }
    @Test
    public void run(){
        List<User> users = mapper.findAll();
        for (User user:users){
            System.out.println(user);
        }
    }
    @Test
    public void run1(){
        List<User> users = mapper.findById(2);
        System.out.println(users);
    }
    @Test
    public void run2(){
        User user = new User();
        user.setUsername("帅哥");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("邢台");
        mapper.add(user);
        System.out.println("添加用户成功");

    }
    @Test
    public void run3(){
        mapper.delete(2);
        System.out.println("删除用户成功");
    }
    @Test
    public void run4(){
        User user = new User();
        user.setId(4);
        user.setUsername("消水");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("张家口");

        mapper.update(user);
        System.out.println("修改用户成功");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值