如何使用MyBatis

weixin_33807284發表於2017-11-21

介紹

MyBatis 是一款優秀的持久層框架,它支援定製化 SQL、儲存過程以及高階對映。MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和對映原生資訊,將介面和 Java 的 POJOs(Plain Old Java Objects,普通的 Java物件)對映成資料庫中的記錄。


1864826-c27580fc77abec57.png
MyBatis

下載

mybatis-3.4.5
mysql-jdbc-connector
如果你使用的Maven構建可以直接配置dependency。

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

配置

  • conf.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="db.properties"/><!-- 使用屬性檔案 -->
    <typeAliases><!-- 為User取別名 -->
        <typeAlias type="com.fleming.domain.User" alias="_User"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!-- JDBC配置 -->
            <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="${pass}" />
            </dataSource>
        </environment>
    </environments>
</configuration>
  • 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.fleming.mapping.userMapper">
    <select id="getUser" parameterType="int" resultType="_User">
        select * from users where id=#{id}
    </select>
    <insert id="insertUser" parameterType="_User">
        insert into users(name,age) values(#{name},#{age})
    </insert>
    <delete id="delUser" parameterType="int">
        delete from users where id=#{id}
    </delete>
    <update id="updateUser" parameterType="_User">
        update users set name=#{name},age=#{age} where id=#{id}
    </update>
    <select id="getAllUsers" parameterType="_User">
        select * from users
    </select>
</mapper>
  • 利用註解編寫介面UserMapperI.java
public interface UserMapperI {
    //使用@Insert註解指明add方法要執行的SQL
    @Insert("insert into users(name, age) values(#{name}, #{age})")
    public int add(User user);
    
    //使用@Delete註解指明deleteById方法要執行的SQL
    @Delete("delete from users where id=#{id}")
    public int deleteById(int id);
    
    //使用@Update註解指明update方法要執行的SQL
    @Update("update users set name=#{name},age=#{age} where id=#{id}")
    public int update(User user);
    
    //使用@Select註解指明getById方法要執行的SQL
    @Select("select * from users where id=#{id}")
    public User getById(int id);
    
    //使用@Select註解指明getAll方法要執行的SQL
    @Select("select * from users")
    public List<User> getAll();
}

使用註解可以方便呼叫,然後將mapper檔案配置到conf.xml中

<mappers>
    <mapper resource="com/fleming/mapping/userMapper.xml" />
    <mapper class="com.fleming.mapping.UserMapperI" />
</mappers>

測試

-- ----------------------------
--  Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records 
-- ----------------------------
INSERT INTO `users` VALUES ('1','獨孤求敗','27'), ('2','獨孤求敗','27'), ('3','獨孤求敗','20');
public class MybatisTest {
    @Test
    public void testGetAll(){
        String resource = "conf.xml";
        InputStream is = MybatisTest.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);    
        SqlSession session = sessionFactory.openSession();
        /**
         * 對映sql的標識字串,
         * me.gacl.mapping.userMapper是userMapper.xml檔案中mapper標籤的namespace屬性的值,
         * getAllUsers是select標籤的id屬性值,通過select標籤的id屬性值就可以找到要執行的SQL
         */
        UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
        //執行查詢操作,將查詢結果自動封裝成List<User>返回
        List<User> lstUsers = mapper.getAll();
        //使用SqlSession執行完SQL之後需要關閉SqlSession
        sqlSession.close();
        for(User user: lstUsers) {
            System.out.println(user);
        }
    }   
}

基本入門操作,留作記錄。

相關文章