mybatis使用注解开发

  1. mybatis常用注解

  2. 使用注解方式开发持久层接口

    public interface UserMapper {
    
        /**
         * 查询所有用户
         * @return
         */
        @Select("select * from user")
        List<User> selectAll();
    
        /**
         * 更新用户
         * @param user
         */
        @Update("update user set username=#{username} where id=#{id}")
        void updateUser(User user);
    
        /**
         * 删除用户
         * @param userId
         */
        @Delete("delete from user where id=#{id}")
        void deleteUser(Integer userId);
    
        /**
         * 根据id查询用户
         * @param userId
         * @return
         */
        @Select("select * from user where id=#{id}")
        User findById(Integer userId);
    }
    
    
  3. 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="db.properties"></properties>
        <!--配置别名-->
        <typeAliases>
            <package name="com.test.User"/>
        </typeAliases>
        <!--配置环境-->
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="${jdriver}"></property>
                    <property name="url" value="${url}"></property>
                    <property name="username" value="${username}"></property>
                    <property name="password" value="${password}"></property>
                </dataSource>
            </environment>
        </environments>
        <!--指定带有注解的dao接口所在位置-->
        <mappers>
            <package name="com.test.dao"></package>
        </mappers>
    </configuration>
    
  4. 注解的本质是反射机制

posted @ 2024-05-10 19:59  Hanyta  阅读(6)  评论(0编辑  收藏  举报