DEV Community

Jihao Deng
Jihao Deng

Posted on

1

MB04 Mybatis Annotation

本篇主要讨论使用Mybatis的注解来进行基本操作

使用Mybatis的注解

  • 在数据库中创建一个Tag表,用于演示注解
DROP TABLE IF EXISTS `h_tag`;

CREATE TABLE `h_tag` (
`id` int(20) NOT NULL,
`tag` varchar(30) DEFAULT NULL,
`rated` int(20) DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `h_tag`(`id`,`tag`,`rated`) values (1,'pure_love',0),(3,'rape',1);
Enter fullscreen mode Exit fullscreen mode
  • 创建Tag实体类、Dao接口
public class Tag {
    private int id;
    private String tag;
    private int rated;
}
Enter fullscreen mode Exit fullscreen mode
public interface TagDao {

    @Select("select * from h_tag")
    List<Tag> findAll();

    @Select("select * from h_tag where tag = #{name}")
    Tag findByTagName(@Param("name") String name);
}
Enter fullscreen mode Exit fullscreen mode

对于@Param注解,基本类型参数或者String,需要加上,而引用类型不需要加

  • 在[mybatis-config.xml]中绑定TagDao接口
<!-- 注册Mapper.xml -->
<mappers>
    <mapper resource="com/dale/dao/UserMapper.xml" />

    <!-- 为了使用注解 绑定接口 -->
    <mapper class="com.dale.dao.TagDao" />
</mappers>
Enter fullscreen mode Exit fullscreen mode
  • JUnit测试代码
@Test
public void testAnnotation() {
    SqlSession ss = MybatisUtil.getSqlSession();

    TagDao tagDao = ss.getMapper(TagDao.class);

    List<Tag> tg = tagDao.findAll();

    for(Tag u:tg) {
        System.out.println(u.getTag());
    }

    Tag tem = tagDao.findByTagName("lolicon");
    System.out.println(tem.getRated());

    ss.close();
}
Enter fullscreen mode Exit fullscreen mode

注解与xml配置文件的对比

使用注解更方便,但是其功能没有xml配置文件强大,更多时候还是使用配置文件。

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more