1. 程式人生 > >MyBatis入門實驗(4)之基於註解實現對資料的增刪查改

MyBatis入門實驗(4)之基於註解實現對資料的增刪查改

實驗內容

在上一章中,實現了基於XML檔案的方式對資料庫表進行增刪查改操作。
本次實驗將使用基於註解的方式實現對資料庫表的增刪查改操作。

操作步驟

一、安裝

新增Maven依賴(本文使用版本為3.4.6)

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>x.x.x</version>
</dependency>
<dependency
>
<groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency>

二、建立資料庫及表結構

CREATE TABLE `user` (
  `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `username` varchar(32) NOT NULL
COMMENT '使用者名稱', `password` varchar(64) NOT NULL COMMENT '密碼', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

三、建立 Mybatis 配置檔案

src/main/resources 目錄下建立 mybatis-config.xml 檔案,內容如下

與上一章不同的地方:可以註釋掉對XML檔案的註冊

<configuration>
    <properties resource="jdbc.properties"
>
</properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 載入XML,同時載入介面類 --> <mappers> <mapper class="tutorial.mybatis.mapper.UserMapper"></mapper> <!-- 可以註釋掉,不使用XML檔案,也可以兩者混用 --> <!-- <mapper resource="mybatis/User.xml"></mapper> --> </mappers> </configuration>

src/main/resources 目錄下建立 jdbc.properties 檔案,內容如下

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tutorial_mybatis?characterEncoding=utf-8&useSSL=true
jdbc.username=root
jdbc.password=

四、建立實體類

建立包 tutorial.mybatis.model,並在該包下建立 User 類,內容如下

與上一章不同的地方:可以刪除掉 Mapper.xml 檔案

public class User {

    private Long id;

    private String username;

    private String password;

    // 省略 get / set 方法
}

五、建立介面類

建立包 tutorial.mybatis.mapper,並在該包下建立介面 UserMapper,內容如下

與上一章不同的地方:在介面類中使用註解的方式代替了XML檔案中的SQL語句

public interface UserMapper {

    @Results({
        @Result(id = true, column = "id", property = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
        @Result(column = "username", property = "username", javaType = String.class, jdbcType = JdbcType.VARCHAR),
        @Result(column = "password", property = "password", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @Select("SELECT * FROM `user` WHERE id = #{id}")
    User getUserById(Long id);

    @Results({
        @Result(id = true, column = "id", property = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
        @Result(column = "username", property = "username", javaType = String.class, jdbcType = JdbcType.VARCHAR),
        @Result(column = "password", property = "password", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @Select("SELECT * FROM `user`")
    List<User> listAll();

    @Insert("INSERT INTO `user` VALUES (#{id}, #{username}, #{username})")
    int save(User user);

    @Update("UPDATE `user` SET `username` = #{username}, `password` = #{password} where `id` = #{id}")
    int updateById(User user);

    @Delete("DELETE FROM `user` WHERE id = #{id}")
    int deleteById(Long id);

    @Delete("DELETE FROM `user`")
    int deleteAll();

}

六、構建

準備工作就緒,開始最終章,建立啟動類 MybatisConfig,內容如下:

public class MybatisConfig {

    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public static void main(String[] args) throws IOException {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            init(session);
            testInsert(session);
            User user1 = testGet(session, 1L);
            testUpdate(session, user1);
            User user2 = testGet(session, 2L);
            testDelete(session, user2);
        } finally {
            session.close();
        }
    }

    private static void init(SqlSession session) {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        userMapper.deleteAll();
    }

    public static void testInsert(SqlSession session) {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user1 = new User() {{
            setId(1L);
            setUsername("admin");
            setPassword("admin");
        }};
        User user2 = new User() {{
            setId(2L);
            setUsername("user");
            setPassword("user");
        }};
        userMapper.save(user1);
        userMapper.save(user2);
        System.out.println("------- 資料新增完成,現有資料 --------");
        testList(session);
    }

    public static void testUpdate(SqlSession session, User user) {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        user.setPassword("12345678");
        userMapper.updateById(user);
        System.out.println("------- 修改ID為" + user.getId() + "的使用者密碼為12345678 --------");
        testList(session);
    }

    public static void testDelete(SqlSession session, User user) {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        userMapper.deleteById(user.getId());
        System.out.println("------- 刪除ID為" + user.getId() + "的使用者 --------");
        testList(session);
    }

    public static User testGet(SqlSession session, Long id) {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        return userMapper.getUserById(id);
    }

    private static void testList(SqlSession session) {
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> list = userMapper.listAll();
        if (list != null && !list.isEmpty()) {
            for (User user : list) {
                printUser(user);
            }
        }
    }

    private static void printUser(User user) {
        String userInfo = "ID:" + user.getId() + "名字:" + user.getUsername()+", 密碼:" + user.getPassword();
        System.out.println(userInfo);
    }
}

列印結果為:

------- 資料新增完成,現有資料 --------
ID:1名字:admin, 密碼:admin
ID:2名字:user, 密碼:user
------- 修改ID為1的使用者密碼為12345678 --------
ID:1名字:admin, 密碼:12345678
ID:2名字:user, 密碼:user
------- 刪除ID為2的使用者 --------
ID:1名字:admin, 密碼:12345678