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配置文件强大,更多时候还是使用配置文件。

AWS Q Developer image

What is MCP? No, Really!

See MCP in action and explore how MCP decouples agents from servers, allowing for seamless integration with cloud-based resources and remote functionality.

Watch the demo

Top comments (0)

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay