Java Mybatis框架多表操作與註解開發詳解分析

一對一查詢

一對一查詢的模型

用戶表和訂單表的關系為,一個用戶有多個訂單,一個訂單隻從屬於一個用戶。

一對一查詢的需求:查詢一個訂單,與此同時查詢出該訂單所屬的用戶

一對一查詢的語句

對應的sql語句: select * from orders o,user u where o.uid=u.id;查詢的結果如下:

創建Order和User實體

創建OrderMapper接口

public interface OrderMapper {
 
    //查詢全部的方法
    public List<Order> findAll();
}

配置OrderMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.longdi.mapper.OrderMapper">
 
    <resultMap id="orderMap" type="order">
        <!--手動指定字段與實體屬性的映射關系
            column: 數據表的字段名稱
            property:實體的屬性名稱
        -->
        <id column="oid" property="id"></id>
        <result column="ordertime" property="ordertime"></result>
        <result column="total" property="total"></result>
        <!--<result column="uid" property="user.id"></result>
        <result column="username" property="user.username"></result>
        <result column="password" property="user.password"></result>
        <result column="birthday" property="user.birthday"></result>-->
 
        <!--
            property: 當前實體(order)中的屬性名稱(private User user)
            javaType: 當前實體(order)中的屬性的類型(User)
        -->
        <association property="user" javaType="user">
            <id column="uid" property="id"></id>
            <result column="username" property="username"></result>
            <result column="password" property="password"></result>
            <result column="birthday" property="birthday"></result>
        </association>
 
    </resultMap>
 
    <select id="findAll" resultMap="orderMap">
         SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id
    </select>
 
</mapper>

配置UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.longdi.mapper.UserMapper">
 
 
    <resultMap id="userMap" type="user">
        <id column="uid" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <!--配置集合信息
            property:集合名稱
            ofType:當前集合中的數據類型
        -->
        <collection property="orderList" ofType="order">
            <!--封裝order的數據-->
            <id column="oid" property="id"></id>
            <result column="ordertime" property="ordertime"></result>
            <result column="total" property="total"></result>
        </collection>
    </resultMap>
 
    <select id="findAll" resultMap="userMap">
        SELECT *,o.id oid FROM USER u,orders o WHERE u.id=o.uid
    </select>
 
    <!--#############################################################################-->
 
    <resultMap id="userRoleMap" type="user">
        <!--user的信息-->
        <id column="userId" property="id"></id>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <!--user內部的roleList信息-->
        <collection property="roleList" ofType="role">
            <id column="roleId" property="id"></id>
            <result column="roleName" property="roleName"></result>
            <result column="roleDesc" property="roleDesc"></result>
        </collection>
    </resultMap>
 
    <select id="findUserAndRoleAll" resultMap="userRoleMap">
        SELECT * FROM USER u,sys_user_role ur,sys_role r WHERE u.id=ur.userId AND ur.roleId=r.id
    </select>
 
</mapper>

配置sqlMapConfig.xml

<?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>
 
    <!--通過properties標簽加載外部properties文件-->
    <properties resource="jdbc.properties"></properties>
 
    <!--自定義別名-->
    <typeAliases>
        <typeAlias type="com.longdi.domain.User" alias="user"></typeAlias>
        <typeAlias type="com.longdi.domain.Order" alias="order"></typeAlias>
        <typeAlias type="com.longdi.domain.Role" alias="role"></typeAlias>
    </typeAliases>
 
    <!--數據源環境-->
    <environments default="developement">
        <environment id="developement">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    
 
    <!--加載映射文件-->
    <mappers>
        <mapper resource="com/longdi/mapper/UserMapper.xml"></mapper>
        <mapper resource="com/longdi/mapper/OrderMapper.xml"></mapper>
    </mappers>
</configuration>

測試代碼

    @Test
    public void test1() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
 
        OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
        List<Order> orderList = mapper.findAll();
        for (Order order : orderList) {
            System.out.println(order);
        }
        sqlSession.close();
    }

一對多查詢

一對多查詢模型

用戶表和訂單表的關系為,一個用戶有多個訂單,一個訂單隻從屬於一個用戶一對多查詢的需求:查詢一個用戶,與此同時查詢出該用戶具有的訂單

對應的sql語句: select *,o.id oid from user u left join orders o on u.id=o.uid;查詢的結果如下:

SELECT *,o.id oid FROM USER u, orders o WHERE u.id=o.uid

修改User實體

創建UserMapper接口

配置UserMapper.xml
測試結果

多對多查詢

多對多查詢的模型
用戶表和角色表的關系為,一個用戶有多個角色,一個角色被多個用戶使用多對多查詢的需求:查詢用戶同時查詢出該用戶的所有角色

多對多查詢的語句

對應的sql語句: select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_idinner join role r on ur.role_id=r.id;
查詢的結果如下:

創建Role實體,修改User實體

添加UserMapper接口方法

配置UserMapper.xml(上面)
測試代碼

總結:

MyBatis多表配置方式:

一對一配置:使用<resultMap>做配置
一對多配置:使用<resultMap>+<collection>做配置

多對多配置:使用<resultMap>+<collection>做配置

Mybatis的註解開發

Mybatis的常用註解

這幾年來註解開發越來越流行,Mybatis也可以使用註解開發方式,這樣我們就可以減少編寫Mapper映射文件瞭。我們先圍繞一些基本的CRUD來學習,再學習復雜映射多表操作。
@Insert:實現新增
@Update:實現更新@Delete:實現刪除@Select:實現查詢
@Result:實現結果集封裝
@Results:可以與@Result一起使用,封裝多個結果集@One:實現一對一結果集封裝
@Many:實現一對多結果集封裝

Mybatis的增刪查改

    private UserMapper mapper;
 
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
    }
   @Test
    public void testSave(){
        User user = new User();
        user.setUsername("tom");
        user.setPassword("abc");
        mapper.save(user);
    }
 
    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(18);
        user.setUsername("lucy");
        user.setPassword("123");
        mapper.update(user);
    }
 
    @Test
    public void testDelete(){
        mapper.delete(18);
    }
 
    @Test
    public void testFindById(){
        User user = mapper.findById(2);
        System.out.println(user);
    }
 
    @Test
    public void testFindAll(){
        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }
    }

修改MyBatis的核心配置文件,我們使用瞭註解替代的映射文件,所以我們隻需要加載使用瞭註解的Mapper接口即可

    <!--加載映射關系-->
    <mappers>
        <!--掃描使用註解的類-->
        <package name="com.longdi.mapper.UserMapper"></package>
    </mappers>

或者指定掃描包含映射關系的接口所在的包也可以

    <!--加載映射關系-->
    <mappers>
        <!--指定接口所在的包-->
        <package name="com.longdi.mapper"></package>
    </mappers>

UserMapper:

public interface UserMapper {
 
    @Insert("insert into user values(#{id},#{username},#{password},#{birthday})")
    public void save(User user);
 
    @Update("update user set username=#{username},password=#{password} where id=#{id}")
    public void update(User user);
 
    @Delete("delete from user where id=#{id}")
    public void delete(int id);
 
    @Select("select * from user where id=#{id}")
    public User findById(int id);
 
    @Select("select * from user")
    public List<User> findAll();
 
    @Select("select * from user")
    @Results({
            @Result(id=true ,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "password",property = "password"),
            @Result(
                    property = "orderList",
                    column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.longdi.mapper.OrderMapper.findByUid")
            )
    })
    public List<User> findUserAndOrderAll();
 
 
    @Select("SELECT * FROM USER")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "password",property = "password"),
            @Result(
                    property = "roleList",
                    column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.longdi.mapper.RoleMapper.findByUid")
            )
    })
    public List<User> findUserAndRoleAll();
 
 
}

MyBatis的註解實現復雜映射開發

實現復雜關系映射之前我們可以在映射文件中通過配置<resultMap>來實現,使用註解開發後,我們可以使用@Results註解,@Result註解,@One註解,@Many註解組合完成復雜關系的配置

一對一查詢(使用註解配置Mapper)

測試代碼:

一對多查詢(使用註解配置Mapper)

測試代碼;

多對多查詢(使用註解配置mapper)

測試代碼:

到此這篇關於Java Mybatis框架多表操作與註解開發詳解分析的文章就介紹到這瞭,更多相關Java Mybatis內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: