mybatis入門篇(三):Mybatis註解方式的基本用法

@Select註解的基本使用方法mysql

一、mybatis-config.xmlsql

<?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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.forest.owl.entity"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/forest?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.forest.owl.mapper"/>
    </mappers>
</configuration>

二、編寫UserMapper接口apache

import com.forest.owl.entity.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id=#{id}")
    User selectUserById(Long id);
}

三、測試mybatis

@Test
public void UserMapperTest(){
    SqlSession sqlSession = getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.selectUserById((long) 2);
    System.out.println(user.getUserName());
    System.out.println(user.getHeadImg());
    System.out.println(user.getCreateTime());
}

四、關聯查詢app

@Results({
     @Result(property = "id", column = "id"),
     @Result(property = "userName", column = "user_name"),
     @Result(property = "userPassword", column = "user_password"),
     @Result(property = "userPhone", column = "user_phone"),
     @Result(property = "userEmail", column = "user_email"),
     @Result(property = "headImg", column = "head_img"),
     @Result(property = "createTime", column = "create_time"),
     @Result(property = "updateTime", column = "update_time"),
     @Result(property = "role.roleName", column = "role_name")
})
@Select("SELECT u.* ,r.role_name FROM user u INNER JOIN user_role ur on ur.user_id=u.id INNER JOIN role r on r.id=ur.role_id WHERE u.id=#{id}")
List<User> selectUserById(Long id);

關於註解形式的查詢,也能夠經過Provider進行sql的動態生成。如: 新建UserProvider類:ide

import org.apache.ibatis.jdbc.SQL;
public class UserProvider {
    public String selectUserById(Long id){
        return new SQL(){
            {
                SELECT("u.* ,r.role_name");
                FROM("user u");
                LEFT_OUTER_JOIN("user_role ur on ur.user_id=u.id");
                LEFT_OUTER_JOIN("role r on r.id=ur.role_id");
                WHERE("u.id=#{id}");
            }
        }.toString();
    }
}

此時UserMapper能夠這麼寫:測試

public interface UserMapper {
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "userName", column = "user_name"),
        @Result(property = "userPassword", column = "user_password"),
        @Result(property = "userPhone", column = "user_phone"),
        @Result(property = "userEmail", column = "user_email"),
        @Result(property = "headImg", column = "head_img"),
        @Result(property = "createTime", column = "create_time"),
        @Result(property = "updateTime", column = "update_time"),
        @Result(property = "role.roleName", column = "role_name")
    })
    @SelectProvider(type = UserProvider.class, method = "selectUserById")
    List<User> selectUserById(Long id);
}

@insert的基本用法 這裏介紹普通插入和返回主鍵方式的插入url

普通插入數據rest

import com.forest.owl.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    @Insert("INSERT INTO user (user_name, user_password, user_phone, user_email, head_img, create_time, update_time) VALUES (#{userName}, #{userPassword}, #{userPhone}, #{userEmail}, #{headImg}, #{createTime}, #{updateTime})")int insertUser(User user);
}

回寫主鍵方式的插入(注意:哪怕mybatis-config.xml配置中已經配置了useGeneratedKeys,在@Options中仍舊須要再配置一次)code

import com.forest.owl.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
    @Insert("INSERT INTO user (user_name, user_password, user_phone, user_email, head_img, create_time, update_time) VALUES (#{userName}, #{userPassword}, #{userPhone}, #{userEmail}, #{headImg}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(User user);
}
相關文章
相關標籤/搜索