前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mybatis基本配置和搭建

Mybatis基本配置和搭建

作者头像
allsmallpig
发布2021-02-25 10:40:15
2930
发布2021-02-25 10:40:15
举报
文章被收录于专栏:allsmallpi博客

转载自 http://blog.csdn.net/zdtao/article/details/49474557

今天,主要向大家分享下如何从头搭建一个最简单的mybatis项目

下载地址

Mybatis3 最新下载地址:https://github.com/mybatis/mybatis-3/releases

一, 创建配置文件

在新建的project的src目录下,新建mybatis-config.xml

代码语言:html
复制
<configuration>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
    settings>

    <typeAliases>
        <typeAlias type="com.test.entity.Employee" alias="Employee"/>
        <typeAlias type="com.test.entity.Customer" alias="Customer"/>
    typeAliases>

    <environments default="local">
        <environment id="local">
            <transactionManager type="JDBC">transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/orcl"/>
                <property name="username" value="username"/>
                <property name="password" value="password"/>
            dataSource>
        environment>
    environments>


    <mappers>
        <mapper resource="com/test/data/employee-mapper.xml"/>
        <mapper resource="com/test/data/customer-mapper.xml"/>
    mappers>
configuration>

接下来为大家解释下该配置文件中的内容

1. settings 定义mybatis的一些全局设置,这里 配置的两个属性

mapUnderscoreToCamelCase: 在映射database column名字和entity属性名时,自动将带下划线column名转化为常见的java驼峰形式属性名  lazyLoadingEnabled: 延迟加载entity的关联属性

2. typeAlias 定义java类型的别名,比如这里分别将com.yun.entity.Employee和com.yun.entity.Customer设置别名为Employee,Customer。这样在别处配置文件中使用 它们时,就不必再指明带package全名。

3. environments 主要用于配置数据源  可以配置多个environment,以用于不同的产品环境,这里只配置一个用于测试,并定义id为“local”

transactionManager: 有两种类型  1, JDBC : 使用从数据源返回的连接管理commit和rollback  2, MANAGED : 依靠容器来管理transaction dataSource: 有3种类型  1, UNPOOLED :每次请求新打开连接,用完后关闭连接  2, POOLED : 使用连接池管理连接  3, JNDI :使用容器管理datasource时使用

4. mappers 简而言之,mapper文件用于定义sql语句,以及与其对应的entity  以employee-mapper.xml为例,以下是其简单实现:

代码语言:html
复制
<mapper namespace="com.test.data.EmployeeMapper">
    <select id="selectAllEmployee" resultType="Employee">
        select * from employee
    select>

    <select id="selectEmployeeById" parameterType="long" resultType="Employee">
        select * from employee where employee_id=#{id}
    select>

mapper>

这里,我们定义了2句sql statement,分别是

selectAllEmployee: 查找所有employee  selectEmployeeById:根据id查找特定employee

返回结果类型均为Employee(看!这里typeAlias就起到作用了,不需要指明class全名),区别在于前者是个List。

这里大家可能会对selectEmployeeById 中的#{id}感到疑惑,别急,下面会为您介绍。

NOTE:配置文件中的顺序不能乱来,对于例子中的几个配置,要按照顺序来定义:settings -> typeAliases -> environments -> mappers.因为mybatis是按照一个固定顺序来解析这个配置文件的,如果顺序不对,加载时会报错。

二,获得SqlSession

不赘述,直接上代码

代码语言:c#
复制
public class MySqlSession {
    private static String mybatisResource = "mybatis-config.xml";

    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory() {
        try {
            if (sqlSessionFactory == null) {
                InputStream inputStream = Resources.getResourceAsStream(mybatisResource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }

            return sqlSessionFactory;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession newSqlSession() {
        SqlSession session = getSqlSessionFactory().openSession();
        return session;
    }
}

通过调用MySqlSession.newSqlSession()即可获得一个SQLSession对象,这也是mybatis中最核心的类了,负责各种select,update,delete接口等,这里就不详细解释了。

三,DAO

马上就到最后一步啦!  还是直接上代码~

代码语言:c#
复制
public class BatisEmployeeDao {
    public List getAllEmployees() {
        SqlSession session = MySqlSession.newSqlSession();
        try {
            List ret = session.selectList("selectAllEmployee");
            return ret;
        } finally {
            session.close();
        }
    }

    public Employee getEmployeeById(Long id) {
        SqlSession session = MySqlSession.newSqlSession();
        try {
            Employee employee = session.selectOne("selectEmployeeById", id);
            return employee;
        } finally {
            session.close();
        }
    }
}

看到这里,想必各位看官也知道前面#{id}的value是哪里来的了,是的,它就是 getEmployeeById(Long id)中的参数,但两者名字不要求一致哦。

好了,到这里,一个最简单的mybatis配置和实现已经结束了,希望对您有所帮助。  更多细节参看mybatis官方文档:http://mybatis.github.io/mybatis-3/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/02/02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 下载地址
  • 一, 创建配置文件
  • 二,获得SqlSession
  • 三,DAO
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档