关于java:MyBatis起始

7次阅读

共计 4982 个字符,预计需要花费 13 分钟才能阅读完成。

Mybatis:

一种简化 sql 操作的长久层框架, 开发只须要关注具体的 sql 语句即可

传统的 JDBC: 1. 操作 sql 2. 操作 Connection、Statment(向数据库发送 sql 的一个对象)、ResultSet 等

ORM 框架: 对象关系匹配, 把关系数据库中的数据转换成面向对象程序中的对象

hibernate(全自动 sql)和 mybatis(自定义 sql)

1.pom 中引入依赖

mybais 只有这一个依赖就实现了
<dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.4.6</version>
</dependency>
    
然而须要操作数据库, 因而引入连贯数据库驱动
<dependency>
         <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.26</version>
</dependency>
 
再加一个测试类的依赖用于测试
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
</dependency>

2.mybatis.xml

编写 myBatis 外围配置文件(放在 resource 目录下)

<?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 core file-->
<configuration>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/hualian?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 将 Mapper.xml 注册到 Mybatis 的外围配置文件中 重要!!-->
    <mappers>
        <mapper resource="com/gxa/hualian/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

3.pom 中引入 mapper.xml

为了可能加载到 java 文件夹下的 mapper 的 xml 文件
<build>
   <resources>
      <resource>
         <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
</build>

4. 写 java 代码

pojo/mapper/test

User

public class User implements Serializable {

    private Long id;
    private String name;
    private Integer points;
    private String phone;
    private Timestamp regTime;

    public User(Long id, String name, Integer points, String phone, Timestamp regTime) {
        this.id = id;
        this.name = name;
        this.points = points;
        this.phone = phone;
        this.regTime = regTime;
    }

    public User() {}
}

UserMapper

public interface UserMapper {void   add(User user);

    void deleteById(Long id);

    void  update(User user);

    List<Map> selectAll();}

UserMapper.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.gxa.hualian.mapper.UserMapper">
    <!-- 增删改查 sql-->
    <insert id="add" parameterType="com.gxa.hualian.pojo.User">
        insert into `user` (`name`,`phone`,`regTime`) values (#{name},#{phone},#{regTime})
    </insert>

    <delete id="deleteById" parameterType="long">
        delete from `user` where id=#{id}
    </delete>

    <update id="update" parameterType="com.gxa.hualian.pojo.User">
        update `user` set `name`=#{name},`phone`=#{phone},`regTime`=#{regTime}
    </update>

    <select id="selectAll" resultType="java.util.Map">
        select * from `user`
    </select>

Test

public class TestUser {

    UserMapper mapper=null;
    SqlSession sqlSession = null;
    @Before
    // 为了获取 sqlSession
    public void init() throws IOException {
        //Resources:mybatis 提供的一个文件流读取工具
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
        // 实例化一个构建器
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 通过 builder 失去一个工厂对象
        SqlSessionFactory factory = builder.build(resourceAsStream);
        // 通过 openSession 失去会话对象,默认为手动提交事务
        //SqlSession 提供了在数据库执行 SQL 命令所需的所有办法
        sqlSession= factory.openSession();

        // 取得 mapper 接口的代理对象
        mapper= sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void add(){Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = new User("测试",0,"7898",timestamp);

        // 取得代理对象再调办法
        mapper.add(user);

        //sqlSession 自带的办法, 同样有增删改查,statement 参数 (第一个参数) 要与接口中的办法名统一
        sqlSession.insert("add", user);

        sqlSession.commit();}

    @Test
    public void deleteById(){mapper.deleteById(37L);
        sqlSession.commit();}

    @Test
    public void update(){Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
        User user1 = new User(44L,"测试 4",0,"+65+6565+",timestamp1);
        sqlSession.update("update", user1);
        sqlSession.commit();}


    @Test
    public void selectAll(){List<Map> maps = mapper.selectAll();
        System.out.println(maps.size());
        for (Map map : maps) {System.out.println(map);
        }
    }

}

遇到的坑:

1. 没有 spring 治理的时候, 想要 mapper 对象须要本人创立 sqlSession

2. 没有在 pom 中引入 xml 文件, 报找不到 UserMapper.xml 的错

标签配置解析:

mappers: 映射器 , UserMapper.xml 文件中配置 映射到具体的 Mapper.xml 文件

 <!-- 将 Mapper.xml 注册到 Mybatis 的外围配置文件中 -->
    <mappers>
        <mapper resource="com/gxa/hualian/mapper/UserMapper.xml"/>
    </mappers>

namespace: 用于绑定 Dao 接口

<mapper namespace="com.xxx.hualian.mapper.UserMapper">
    ...
</mappe>

environments: 环境配置汇合 能够配置多种数据库

environment: 环境配置 具体的实现

连接池: 服务器端一次性向数据库创立多个连贯, 并将多个连贯保留在一个连接池对象当中, 下次有申请操作数据库时, 间接从连接池取得一个连贯, 应用完后不敞开而是持续放回连接池当中 , 可节俭创立连贯 / 开释连贯的资源

//default: development 开发模式 work 工作模式
<environments default="development">
 //id: 指定以后环境的惟一标识
        <environment id="development">
//transactionManager: 事务管理器 type: JDBC- 应用 JDBC 原生的事务管理形式, 提交和回滚都须要手动
            <transactionManager type="JDBC"/>
//datasource: 数据源 type: POOLED- 应用连接池
            <dataSource type="POOLED">
//property: 属性, 连贯四大件 连贯驱动,url, 用户名, 明码
                <property name="driver" value="com.mysql.jdbc.Driver"/>
//useSSL:SSL 协定用于保障数据安全和正确, 默认 true
                <property name="url" value="jdbc:mysql://localhost:3306/hualian?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

正文完
 0