欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用mybatis开发原始Dao层

程序员文章站 2022-04-10 15:03:15
本文将介绍使用框架mybatis开发原始Dao层来对一个对数据库进行增删改查的案例。 本次使用的mybatis版本为mybatis-3.2.7,开发工具为eclipse,数据库为mysql,jdk版本jdk1.8.0_151。 1、首先,使用eclipse新建一个java工程,在lib目录下加入my ......

  本文将介绍使用框架mybatis开发原始dao层来对一个对数据库进行增删改查的案例。

  本次使用的mybatis版本为mybatis-3.2.7,开发工具为eclipse,数据库为mysql,jdk版本jdk1.8.0_151。

  1、首先,使用eclipse新建一个java工程,在lib目录下加入mybatis核心包、依赖包、数据驱动包,然后buildpath一下。。

  使用mybatis开发原始Dao层

  2、添加日志文件,在classpath下创建log4j.properties如下:

# global logging configuration
log4j.rootlogger=debug, stdout
# console output...
log4j.appender.stdout=org.apache.log4j.consoleappender
log4j.appender.stdout.layout=org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern=%5p [%t] - %m%n

  3、在classpath下创建config资源文件夹,并在config文件夹下创建sqlmapconfig.xml,如下:

<?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">
        <!-- 使用jdbc事务管理-->
            <transactionmanager type="jdbc" />
        <!-- 数据库连接池-->
            <datasource type="pooled">
                <property name="driver" value="com.mysql.jdbc.driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </datasource>
        </environment>
    </environments>
</configuration>

  sqlmapconfig.xml是mybatis核心配置文件,上边文件的配置内容为数据源、事务管理。

  4、创建数据封装使用的user类

package com.xyfer.po;

import java.util.date;
/**
 * 
 * @author xyfer
 * 数据封装使用的user类
 *
 */
public class user {
    
    private int       id;          //id
    private string    username;    //姓名
    private string    sex;         //性别
    private date      birthday;    // 生日
    private string    address;     // 地址
    public int getid() {
        return id;
    }
    public void setid(int 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;
    }

}

  5、在classpath下的资源文件夹sqlmapper目录下创建sql映射文件user.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="test">
    <!-- 根据id查询用户 -->
    <select id="finduserbyid" parametertype="int" resulttype="com.xyfer.po.user">
        select * from user where id = #{id}
    </select>
    <!-- 添加用户 -->
    <insert id="insertuser" parametertype="com.xyfer.po.user">
    <selectkey keyproperty="id" order="after" resulttype="java.lang.integer">
        select last_insert_id() 
    </selectkey>
      insert into user(username,birthday,sex,address) 
      values(#{username},#{birthday},#{sex},#{address})
    </insert>
    <!-- 修改用户 -->
    <update id="updateuser" parametertype="com.xyfer.po.user">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
        where id=#{id}
    </update>
    <!-- 删除用户 -->
    <delete id="deleteuserbyid" parametertype="int">
        delete from user where id=#{id}
    </delete>
    
</mapper>

 

  6、mybatis框架需要加载映射文件,将users.xml添加在sqlmapconfig.xml,如下:

<mappers>
        <mapper resource="user.xml"/>
</mappers>

  7、dao层接口

package com.xyfer.dao;

import com.xyfer.po.user;

public interface userdao {

    public user getuserbyid(int id);   //根据id值查询一个用户
    public void insertuser(user user); //新增一个用户
    public void updateuser(user user); //修改一个用户
    public void deleteuser(int id);    //删除一个用户
    
}

  dao层接口实现类

package com.xyfer.dao.impl;

import org.apache.ibatis.session.sqlsession;
import org.apache.ibatis.session.sqlsessionfactory;

import com.xyfer.dao.userdao;
import com.xyfer.po.user;

public class userdaoimpl implements userdao {
    //注入sqlsessionfactory
    public userdaoimpl(sqlsessionfactory sqlsessionfactory){
            this.setsqlsessionfactory(sqlsessionfactory);
        }
            
    private sqlsessionfactory sqlsessionfactory;
        
    public sqlsessionfactory getsqlsessionfactory() {
        return sqlsessionfactory;
    }

    public void setsqlsessionfactory(sqlsessionfactory sqlsessionfactory) {
        this.sqlsessionfactory = sqlsessionfactory;
    }

    @override
    public user getuserbyid(int id) {
        sqlsession session = sqlsessionfactory.opensession();
        user user = null;
        try {
            //通过sqlsession调用selectone方法获取一条结果集
            //参数1:指定定义的statement的id,参数2:指定向statement中传递的参数
            user = session.selectone("test.finduserbyid", 1);
            system.out.println(user);
                        
        } finally{
            session.close();
        }
        return user;
    }

    @override
    public void insertuser(user user) {
        sqlsession sqlsession = sqlsessionfactory.opensession();
        try {
            sqlsession.insert("test.insertuser", user);
            sqlsession.commit();
        } finally{
            sqlsession.close();
        }
    }

    @override
    public void updateuser(user user) {
        sqlsession sqlsession = sqlsessionfactory.opensession();
        try {
            sqlsession.update("test.updateuser", user);
            sqlsession.commit();
        } finally{
            sqlsession.close();
        }
    }

    @override
    public void deleteuser(int id) {
        sqlsession sqlsession = sqlsessionfactory.opensession();
        try {
            sqlsession.update("test.deleteuserbyid", id);
            sqlsession.commit();
        } finally{
            sqlsession.close();
        }
    }

}

  8、创建一个junit的测试类,对userdao进行测试。

package com.xyfer.dao.impl;

import static org.junit.assert.*;

import java.io.inputstream;
import java.util.date;

import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.sqlsessionfactory;
import org.apache.ibatis.session.sqlsessionfactorybuilder;
import org.junit.before;
import org.junit.test;

import com.xyfer.dao.userdao;
import com.xyfer.po.user;

public class userdaoimpltest {

    private sqlsessionfactory sqlsessionfactory;
    
    @before
    public void init() throws exception {
        sqlsessionfactorybuilder sessionfactorybuilder = new sqlsessionfactorybuilder();
        inputstream inputstream = resources.getresourceasstream("sqlmapconfig.xml");
        sqlsessionfactory = sessionfactorybuilder.build(inputstream);
    }

    @test
    public void testgetuserbyid() {
        userdao userdao = new userdaoimpl(sqlsessionfactory);
        user user = userdao.getuserbyid(22);
        system.out.println(user);
    }

    @test
    public void testinsertuser() {
        user user = new user();
        user.setusername("小李");
        user.setsex("男");
        user.setbirthday(new date());
        user.setaddress("杭州市");
        userdao userdao = new userdaoimpl(sqlsessionfactory);
        userdao.insertuser(user);
    }

    @test
    public void testupdateuser() {
        user user = new user();
        user.setid(10);
        user.setusername("小威");
        user.setsex("男");
        user.setbirthday(new date());
        user.setaddress("杭州市");
        userdao userdao = new userdaoimpl(sqlsessionfactory);
        userdao.updateuser(user);
    }

    @test
    public void testdeleteuser() {
        userdao userdao = new userdaoimpl(sqlsessionfactory);
        userdao.deleteuser(10);
    }

}

  以上步骤,完成使用mybatis框架开发原始dao层,并对数据库进行增删改查操作。

  需要注意的是,上文提到的config文件夹和sqlmapper文件夹均为资源文件夹(source folder),默认会加载该路径下的文件。