注解实现Mybaits操作数据库

1,概述:

我们之前讲过了通过XML的方式来注入Sql实现Mybatis操作数据库。但是其实,我们还可以通过注解的方式来实现。不过,在真实的开发中,其实很多人都还是喜欢用xml的方式。

2,注解实现映射器:

1,创建一个Mapper,名字叫做UserAnnMapper

package com.atbleuuu.mybaits.mapper;

import com.atbleuuu.mybaits.po.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * 基于Annotation的User的Mapper
 */
public interface UserAnnMapper {
    @Select("select * from user where id=#{id}")
    User getUserById(int id);
    @Insert("insert  into user value (null,#{name},#{gender},#{age})")
    int addUser(User user);

    @Update(" update user set name =#{name}, gender =#{gender}, age=#{age} where id=#{id}")
    int updateUser(User user);

    @Delete(" delete from user where id=#{id}")
    int deleteUser(int id);
}



 2,把Mapper注入到mybatis-config.xml配置文件中

<!--注入映射器-->
    <mappers>
        <mapper class="com.atbleuuu.mybaits.mapper.UserAnnMapper"/>
    </mappers>

 3,创建一个AnnTest类 实现注解查询

package com.atbleuuu.mybaits.test;

import com.atbleuuu.mybaits.mapper.UserAnnMapper;
import com.atbleuuu.mybaits.po.User;
import com.atbleuuu.mybaits.tool.MybaitsTool;
import org.apache.ibatis.session.SqlSession;


import java.io.IOException;
import java.io.Reader;

public class AnnTest {

        public static void main(String[] args) {

            //加载对应配置文件
            SqlSession sqlSession = null;
            try {
                sqlSession = MybaitsTool.getSqlSession();
                UserAnnMapper userAnnMapper = sqlSession.getMapper(UserAnnMapper.class);
                User user = userAnnMapper.getUserById(1);
                //打印数据
                System.out.println(user);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            //查询对应的数据
        }

        }

Guess you like

Origin blog.csdn.net/Bleuuuu/article/details/120393319