Mybatis 使用注解的基本配置

8 篇文章 0 订阅
本文档展示了如何在Java项目中配置MyBatis连接MySQL数据库,包括引入依赖、配置数据库连接信息、创建MyBatis配置文件、定义Mapper接口及其实现。示例代码详细解释了查询所有记录和按条件获取单条记录的方法。
摘要由CSDN通过智能技术生成

导入依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

在resources目录下创建mysql.properties,写入:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/javatest?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
name=root
password=root1234

在resources目录下创建mybatis-config.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>
    <properties resource="mysql.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${name}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.mine.dao.MyuserDao"></mapper>
    </mappers>
</configuration>

创建 com.mine.dao.MyuserDao 接口写入:

public interface MyuserDao {

    @Select("select * from myuser ${order}")
    List<Map<String,Object>> getAll(String order);

    @Select("select * from myuser where id = #{id}")
    Map<String,Object> getOne(Integer id);

}

调用

public class MyMain {
    public static void main(String[] args) {

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        InputStream inputStream =
                Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = builder.build(inputStream);
        SqlSession sqlSession = factory.openSession(true);//开启事务
        MyuserDao myUserMapper = sqlSession.getMapper(MyuserDao.class);
        Map<String, Object> one = myUserMapper.getOne(2);
        System.out.println(one);
        System.out.println("-----------------------");
        List<Map<String, Object>> all = myUserMapper.getAll("order by 1 desc");
        System.out.println(all);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值