MyBatis使用注解方式查询

1,导入MyBatis的依赖

<dependencies>

            
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>3.4.6version>
            dependency>

            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>5.1.46version>
                <scope>runtimescope>
            dependency>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
        dependencies>

2,需要映射的实体类,User.class

public class User {
     
    private  int id;
    private String username;
    private String password;
    private String email;
    private String gender;
    private int flag;
    private int role;
    private String code;

    private List<Order> orders;


    public List<Order> getOrders() {
     
        return orders;
    }

    public void setOrders(List<Order> orders) {
     
        this.orders = orders;
    }

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

    public String getUsername() {
     
        return username;
    }

    public void setUsername(String username) {
     
        this.username = username;
    }

    public String getPassword() {
     
        return password;
    }

    public void setPassword(String password) {
     
        this.password = password;
    }

    public String getEmail() {
     
        return email;
    }

    public void setEmail(String email) {
     
        this.email = email;
    }

    public String getGender() {
     
        return gender;
    }

    public void setGender(String gender) {
     
        this.gender = gender;
    }

    public int getFlag() {
     
        return flag;
    }

    public void setFlag(int flag) {
     
        this.flag = flag;
    }

    public int getRole() {
     
        return role;
    }

    public void setRole(int role) {
     
        this.role = role;
    }

    public String getCode() {
     
        return code;
    }

    public void setCode(String code) {
     
        this.code = code;
    }


    @Override
    public String toString() {
     
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", gender='" + gender + '\'' +
                ", flag=" + flag +
                ", role=" + role +
                ", code='" + code + '\'' +
                ", orders=" + orders +
                '}';
    }
}

3,MyBatis的接口mapper类UserMapper.class这里使用了注解而非xml方式

/**
 * Created by davidshion 2/9/20/6:27 PM
 * 相当于以前的dao接口
 *
 * @Author davidshi
 */
public interface UserMapper {
     
     @Select("select * from tb_user where username =#{username} and password =#{password}")
    User findUserByNameAndPassword(@Param("username") String username, @Param("password") String password);

    @Select("select id uid ,username, password  from tb_user where username =#{username} and password =#{password}")
    @ResultMap("basemap")
    User findUserByNameAndPassword1(@Param("username") String username, @Param("password") String password);

    @Select("select id uid ,username name , password  pwd from tb_user where username =#{username} and password =#{password}")
    @Results({
     @Result(id = true,column = "uid",property = "id"),
            @Result(column = "name",property = "username"),
            @Result(column = "pwd" ,property = "password")})
    User findUserByNameAndPassword2(@Param("username") String username, @Param("password") String password);



    @SelectProvider(type = SqlUtil.class,method = "findUserByUserNameAndEmailSql")
    List<User> findUserByNameAndPassword3(@Param("username") String username, @Param("email") String email);

4,sql的查询工具类

public class SqlUtil {
     
    public String findUserByUserNameAndEmailSql(Map<String,Object> params){
     
        String username = (String) params.get("username");
        String email = (String) params.get("email");
        BEGIN();//开始
        SELECT("id ,username, password");
        FROM("tb_user");
        if (username != null) {
     
            WHERE("username =#{username}");
        }
        if (email != null) {
     
            WHERE("email =#{email}");
        }

        return  SQL();
    }
}

5,MyBatis的配置类SqlMapConfig.xml



<configuration>

    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING" />
    settings>
   
    
    <environments default="abc">

        <environment id="abc">
            
            <transactionManager type="JDBC">transactionManager>

            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///db_shopping?useUnicode=true&characterEncoding=UTF8"/>
                <property name="username" value="root"/>
                <property name="password" value="qishimeiyoumima"/>
            dataSource>
        environment>

    environments>

 <mappers>

     
     
        
     
        <package name="person.david.mybatis.mapper"/>

 mappers>

configuration>

6,测试类TestMain.class

public class TestMain {
     
    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void before() throws IOException {
     
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    }

    @Test
    public void test12() {
     
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u = mapper.findUserByNameAndPassword1("admin", "e10adc3949ba59abbe56e057f20f883e");
        System.out.println(u);
    }

    @Test
    public void test13() {
     
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper1 mapper = sqlSession.getMapper(UserMapper1.class);
        User u = mapper.findUserByNameAndPassword("lee", "e10adc3949ba59abbe56e057f20f883e");
        sqlSession.close();
        System.out.println(u);
    }

    @Test
    public void test14() {
     
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper1 mapper = sqlSession.getMapper(UserMapper1.class);
        User u = mapper.findUserByNameAndPassword2("lee", "e10adc3949ba59abbe56e057f20f883e");
        sqlSession.close();
        System.out.println(u);
    }

    @Test
    public void test15() {
     
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u = mapper.findUserById(10);
        sqlSession.close();//二级缓存必须要关闭链接才可以生效,因为访问的是同一个数据,会产生多线程的安全问题,所以它要求必须关闭才可以
        //享元模式

        SqlSession sqlSession1 = sqlSessionFactory.openSession();
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User u1 = mapper1.findUserById(10);
        sqlSession1.close();

        System.out.println(u);
        System.out.println(u1);
    }

你可能感兴趣的:(MyBatis,mybatis,mybatis注解方式查询)