使用Ibatis的简单demo

本文介绍如何使用Ibatis框架实现数据库的基本操作,包括创建数据库和表、配置Ibatis环境、编写Java代码实现增删改查等功能。

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

1.准备工作
安装好mysql数据库、eclipse和jdk,下载好ibatis-2.3.0.677.jar,mysql-connector-java-5.1.18-bin.jar

2.创建数据库,表
1>.进入mysql的安装目录,使用root账号密码登录
这里写图片描述
2>.创建数据库bbs,创建用户,并授权

--创建数据库
create database bbs;
--使用数据库
use bbs;
--创建用户并授权
create user 'test1'@'localhost' identified by '123';
grant all on bbs.* to test1@localhost;
--创建表
create table user(
  id int not null auto_increment primary key,
  name varchar not null,
  email varchar,
  password varchar not null
);

3.创建项目,我这边创建的是Web项目
这里写图片描述

1>.config目录下:
db.properties是数据库的属性配置,
SqlMapConfig.xml是ibatis的配置
ibatis文件夹下的user.xml为具体sql配置
2>.test目录下:
LoginServiceTest.java为测试类
3>src目录下为具体实现代码

代码如下:
User.java

package com.bbs.bean;

public class User {
    private int id;
    private String name;
    private String password;
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

LoginService.java

package com.bbs.service;

import java.sql.SQLException;
import java.util.List;

import com.bbs.bean.User;
import com.bbs.dao.LoginDao;
import com.bbs.dao.impl.LoginDaoImpl;

public class LoginService {

    private static LoginDao loginDao = null;

    static {
        loginDao = new LoginDaoImpl();
    }

    public void queryUserList() {
        System.out.println("queryUserList...");
        try {
            List<User> userList = loginDao.queryUserList();

            if (userList != null) {
                for (User user : userList) {
                    System.out.println("name==" + user.getName());
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void addUser(User user) {
        System.out.println("addUser...");
        try {
            loginDao.addUser(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void updateUsr(User user) {
        System.out.println("updateUsr...");
        try {
            loginDao.updateUser(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void deleteUser(int id) {
        System.out.println("deleteUser...");
        try {
            loginDao.deleteUser(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}

LoginDao.java

package com.bbs.dao;

import java.sql.SQLException;
import java.util.List;

import com.bbs.bean.User;

public interface LoginDao {

    List<User> queryUserList() throws SQLException;

    void addUser(User user) throws SQLException;

    void updateUser(User user) throws SQLException;

    void deleteUser(int id) throws SQLException;
}

LoginDaoImpl.java

package com.bbs.dao.impl;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import com.bbs.bean.User;
import com.bbs.dao.LoginDao;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class LoginDaoImpl implements LoginDao {

    private static SqlMapClient sqlMapClient = null;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            System.out.println("初始话 sqlMapClient.....");
            sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> queryUserList() throws SQLException {
        return sqlMapClient.queryForList("queryUserList");
    }

    @Override
    public void addUser(User user) throws SQLException {
        sqlMapClient.insert("addUser", user);
    }

    @Override
    public void updateUser(User user) throws SQLException {
        sqlMapClient.update("updateUser", user);

    }

    @Override
    public void deleteUser(int id) throws SQLException {
        sqlMapClient.delete("deleteUser", id);

    }

}

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bbs
username=test1
password=123

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <!-- 读取数据库配置文件 -->
    <properties resource="db.properties" />

    <!-- 使用JDBC的事务管理 -->
    <transactionManager type="JDBC"> 
     <!--读取配置文件配置  -->
     <dataSource type="simple">
     <property name="JDBC.Driver" value="${driver}" />
     <property name="JDBC.ConnectionURL" value="${url}" />
     <property name="JDBC.Username" value="${username}" />
     <property name="JDBC.Password" value="${password}" />
     </dataSource>

    </transactionManager>

    <sqlMap resource="ibatis/user.xml"/>

</sqlMapConfig>

user.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMap namespace="user">
    <select id="queryUserList" resultClass="com.bbs.bean.User">
        select * from user
    </select>

    <insert id="addUser" parameterClass="com.bbs.bean.User">
        insert into user(name,password) value(#name#,#password#)
    </insert>

    <update id="updateUser" parameterClass="com.bbs.bean.User">
      update user set name=#name# where id=#id#
    </update>

 <delete id="deleteUser" parameterClass="java.lang.Integer">
      delete from user where id=#id#
    </delete>

</sqlMap>

LoginServiceTest.java

package com.bbs.service;

import com.bbs.bean.User;

public class LoginServiceTest {

    public static void main(String[] args) {
        LoginService loginService = new LoginService();

        loginService.queryUserList();

        User user = new User();
        user.setName("test5");
        user.setPassword("huawei5");
        loginService.addUser(user);

        User user1 = new User();
        user1.setId(3);
        user1.setName("test2");
        loginService.updateUsr(user1);

        loginService.deleteUser(2);
    }

}

运行结果如下图所示:

这里写图片描述

这里写图片描述

就这样,使用ibatis进行增删改查就实现啦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值