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

一个简单的MyBatis项目

程序员文章站 2022-04-14 21:49:41
1、log4j.properties,我们把它设为debug级别,以便于调试。生产环境可以设为INFO,本项目放在src下面: 2、Role.java,一个pojo(plain ordinary java object),用于映射: 3、用XML方式构建映射器,它包含一个接口和一个XML。其中,Ro ......

1、log4j.properties,我们把它设为debug级别,以便于调试。生产环境可以设为info,本项目放在src下面:

# 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

2、role.java,一个pojo(plain ordinary java object),用于映射:

package com.ssm.pojo;

/**
 * created by czz on 2019/7/23.
 */
public class role {
    private long id;
    private string rolename;
    private string note;

    public long getid() {
        return id;
    }

    public void setid(long id) {
        this.id = id;
    }

    public string getrolename() {
        return rolename;
    }

    public void setrolename(string rolename) {
        this.rolename = rolename;
    }

    public string getnote() {
        return note;
    }

    public void setnote(string note) {
        this.note = note;
    }

    @override
    public string tostring() {
        return "role{" +
                "id=" + id +
                ", rolename='" + rolename + '\'' +
                ", note='" + note + '\'' +
                '}';
    }
}

3、用xml方式构建映射器,它包含一个接口和一个xml。其中,rolemapper.java:

package com.ssm.mapper;

import com.ssm.pojo.role;

import java.util.list;

/**
 * created by czz on 2019/7/23.
 */
public interface rolemapper {
    int insertrole(role role);
    int deleterole(long id);
    int updaterole(role role);
    role getrole(long id);
    list<role> findroles(string rolename);
}

4、xml构建中的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.ssm.mapper.rolemapper">

    <insert id="insertrole" parametertype="role">
        insert into t_role(role_name,note) values (#{role_name},#{note})
    </insert>

    <delete id="deleterole" parametertype="long">
        delete from t_role where id = #{id}
    </delete>

    <update id="updaterole" parametertype="role">
        update t_role set role_name = #{rolename},note = #{note} where id = #{id}
    </update>

    <select id="getrole" parametertype="long" resulttype="role">
        select id ,role_name rolename,note from t_role where id = #{id}
    </select>

    <select id="findroles" parametertype="long" resulttype="com.ssm.pojo.role">
        select id ,role_name rolename,note from t_role where role_name like concat('%',#{rolename},'%')
    </select>
</mapper>

5、mybatis-config.xml用于构建sqlsessionfactory,代码清单如下:

<?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>
    <!-- 全局setting配置,根据需要添加 -->

    <!-- 配置别名 -->
    <typealiases>
        <typealias type="com.ssm.pojo.role" alias="role"/>
    </typealiases>
    <!-- 配置数据库环境 -->
    <environments default="development">
        <environment id="development">
            <transactionmanager type="jdbc"></transactionmanager>
            <datasource type="pooled">
                <property name="driver" value="com.mysql.jdbc.driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm?useunicode=true&amp;characterencoding=utf8&amp;servertimezone=utc"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </datasource>
        </environment>
    </environments>
    <mappers>
        <package name="com.ssm.mapper"/>
    </mappers>
</configuration>

6、由于sqlsessionfactory应该采用单例模式,所以这里采用单例模式,利用sqlsessionfactorybuilder来构建它:

package com.ssm.utils;

import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.sqlsessionfactory;
import org.apache.ibatis.session.sqlsessionfactorybuilder;

import java.io.ioexception;
import java.io.inputstream;

/**
 * created by czz on 2019/7/24.
 */
public class sqlsessionfactoryutils {
    private final static class<sqlsessionfactoryutils> lock = sqlsessionfactoryutils.class;
    private static sqlsessionfactory sqlsessionfactory = null;
    //防止其他代码通过new的方式创建它
    private sqlsessionfactoryutils(){

    }

    public static sqlsessionfactory getsqlsessionfactory(){
        // 加锁是为了防止多线程中多次实例化,以保证其唯一性
        synchronized (lock){
            if (sqlsessionfactory != null){
                return sqlsessionfactory;
            }
            string resource = "mybatis-config.xml";
            inputstream inputstream;
            try {
                inputstream = resources.getresourceasstream(resource);
                sqlsessionfactory = new sqlsessionfactorybuilder().build(inputstream);
            }catch (ioexception e){
                e.printstacktrace();
                return null;
            }
            return sqlsessionfactory;
        }
    }
}

7、运行代码:

package com.ssm.chapter3.main;

import com.ssm.mapper.rolemapper;
import com.ssm.pojo.role;
import com.ssm.utils.sqlsessionfactoryutils;
import org.apache.ibatis.session.sqlsession;
import org.apache.log4j.logger;

/**
 * created by czz on 2019/7/24.
 */
public class chapter3main {
    public static void main(string[] args) {
        logger log = logger.getlogger(chapter3main.class);
        sqlsession sqlsession = null;
        try {
            sqlsession = sqlsessionfactoryutils.getsqlsessionfactory().opensession();
            rolemapper rolemapper = sqlsession.getmapper(rolemapper.class);
            role role = rolemapper.getrole(1l);
            log.info(role.getrolename());
        }finally {
            if (sqlsession!=null){
                sqlsession.close();
            }
        }
    }
}

8、jar包下载:
(1)mybatis 3.5.2(当前最新版)
官网
百度云 :提取码:xnjz
(2)数据库驱动包(mysql):
百度云 :提取码:c963

大家有兴趣也可以关注我的公众号查看文章。

一个简单的MyBatis项目