1. 程式人生 > 其它 >Mybatis多表查詢

Mybatis多表查詢

作者:季沐測試筆記
原文地址https://www.cnblogs.com/testero/p/15423070.html
部落格主頁https://www.cnblogs.com/testero

1.Mybatis多表查詢

1.1 一對一查詢

1.1.1 一對一查詢的模型MapperScannerConfigurer

使用者表和訂單表的關係為,一個使用者有多個訂單,一個訂單隻從屬於一個使用者

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

1.1.2一對一查詢的語句

對應的sql語句:select * from orders o,user u where o.uid=u.id;

查詢的結果如下:

1.1.3 建立Order和User實體
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表當前訂單從屬於哪一個客戶
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;

}
1.1.4 建立OrderMapper介面
public interface OrderMapper {
    List<Order> findAll();
}
1.1.5 配置OrderMapper.xml
<mapper namespace="com.itheima.mapper.OrderMapper">
    <resultMap id="orderMap" type="com.itheima.domain.Order">
        <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>
    </resultMap>
    <select id="findAll" resultMap="orderMap">
        select * from orders o,user u where o.uid=u.id
    </select>
</mapper>

其中還可以配置如下:

<resultMap id="orderMap" type="com.itheima.domain.Order">
    <result property="id" column="id"></result>
    <result property="ordertime" column="ordertime"></result>
    <result property="total" column="total"></result>
    <association property="user" javaType="com.itheima.domain.User">
        <result column="uid" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
    </association>
</resultMap>
1.1.6 測試結果
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<Order> all = mapper.findAll();
for(Order order : all){
    System.out.println(order);
}

1.2 一對多查詢

1.2.1 一對多查詢的模型

使用者表和訂單表的關係為,一個使用者有多個訂單,一個訂單隻從屬於一個使用者

一對多查詢的需求:查詢一個使用者,與此同時查詢出該使用者具有的訂單

1.2.2 一對多查詢的語句

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

查詢的結果如下:

1.2.3 修改User實體
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表當前訂單從屬於哪一個客戶
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表當前使用者具備哪些訂單
    private List<Order> orderList;
}

1.2.4 建立UserMapper介面
public interface UserMapper {
    List<User> findAll();
}

1.2.5 配置UserMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
    <resultMap id="userMap" type="com.itheima.domain.User">
        <result column="id" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <collection property="orderList" ofType="com.itheima.domain.Order">
            <result column="oid" property="id"></result>
            <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 left join orders o on u.id=o.uid
    </select>
</mapper>
1.2.6 測試結果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
for(User user : all){
    System.out.println(user.getUsername());
    List<Order> orderList = user.getOrderList();
    for(Order order : orderList){
        System.out.println(order);
    }
    System.out.println("----------------------------------");
}

1.3 多對多查詢

1.3.1 多對多查詢的模型

使用者表和角色表的關係為,一個使用者有多個角色,一個角色被多個使用者使用

多對多查詢的需求:查詢使用者同時查詢出該使用者的所有角色

1.3.2 多對多查詢的語句

對應的sql語句:select u.,r.,r.id rid from user u left join user_role ur on u.id=ur.user_id

inner join role r on ur.role_id=r.id;

查詢的結果如下:

1.3.3 建立Role實體,修改User實體
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表當前使用者具備哪些訂單
    private List<Order> orderList;
    //代表當前使用者具備哪些角色
    private List<Role> roleList;
}

public class Role {

    private int id;
    private String rolename;

}

1.3.4 新增UserMapper介面方法
List<User> findAllUserAndRole();
1.3.5 配置UserMapper.xml
<resultMap id="userRoleMap" type="com.itheima.domain.User">
    <result column="id" property="id"></result>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
    <collection property="roleList" ofType="com.itheima.domain.Role">
        <result column="rid" property="id"></result>
        <result column="rolename" property="rolename"></result>
    </collection>
</resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap">
    select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_id
    inner join role r on ur.role_id=r.id
</select>
1.3.6 測試結果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAllUserAndRole();
for(User user : all){
    System.out.println(user.getUsername());
    List<Role> roleList = user.getRoleList();
    for(Role role : roleList){
        System.out.println(role);
    }
    System.out.println("----------------------------------");
}

1.4 知識小結

MyBatis多表配置方式:

一對一配置:使用做配置

一對多配置:使用+做配置

多對多配置:使用+做配置

2.Mybatis的註解開發

2.1 MyBatis的常用註解

這幾年來註解開發越來越流行,Mybatis也可以使用註解開發方式,這樣我們就可以減少編寫Mapper

對映檔案了。我們先圍繞一些基本的CRUD來學習,再學習複雜對映多表操作。

@Insert:實現新增

@Update:實現更新

@Delete:實現刪除

@Select:實現查詢

@Result:實現結果集封裝

@Results:可以與@Result 一起使用,封裝多個結果集

@One:實現一對一結果集封裝

@Many:實現一對多結果集封裝

2.2 MyBatis的增刪改查

我們完成簡單的user表的增刪改查的操作

private UserMapper userMapper;

@Before
public void before() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new 
                 SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    userMapper = sqlSession.getMapper(UserMapper.class);
}

@Test
public void testAdd() {
    User user = new User();
    user.setUsername("測試資料");
    user.setPassword("123");
    user.setBirthday(new Date());
    userMapper.add(user);
}
@Test
public void testUpdate() throws IOException {
    User user = new User();
    user.setId(16);
    user.setUsername("測試資料修改");
    user.setPassword("abc");
    user.setBirthday(new Date());
    userMapper.update(user);
}

@Test
public void testDelete() throws IOException {
    userMapper.delete(16);
}
@Test
public void testFindById() throws IOException {
    User user = userMapper.findById(1);
    System.out.println(user);
}
@Test
public void testFindAll() throws IOException {
    List<User> all = userMapper.findAll();
    for(User user : all){
        System.out.println(user);
    }
}

修改MyBatis的核心配置檔案,我們使用了註解替代的對映檔案,所以我們只需要載入使用了註解的Mapper介面即可

<mappers>
    <!--掃描使用註解的類-->
    <mapper class="com.itheima.mapper.UserMapper"></mapper>
</mappers>

或者指定掃描包含對映關係的介面所在的包也可以

<mappers>
    <!--掃描使用註解的類所在的包-->
    <package name="com.itheima.mapper"></package>
</mappers>

2.3 MyBatis的註解實現複雜對映開發

實現複雜關係對映之前我們可以在對映檔案中通過配置來實現,使用註解開發後,我們可以使用@Results註解,@Result註解,@One註解,@Many註解組合完成複雜關係的配置

2.4 一對一查詢

2.4.1 一對一查詢的模型

使用者表和訂單表的關係為,一個使用者有多個訂單,一個訂單隻從屬於一個使用者

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

2.4.2 一對一查詢的語句

對應的sql語句:

select * from orders;

select * from user where id=查詢出訂單的uid;

查詢的結果如下:

2.4.3 建立Order和User實體
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表當前訂單從屬於哪一個客戶
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;

}
2.4.4 建立OrderMapper介面
public interface OrderMapper {
    List<Order> findAll();
}
2.4.5 使用註解配置Mapper
public interface OrderMapper {
    @Select("select * from orders")
    @Results({
            @Result(id=true,property = "id",column = "id"),
            @Result(property = "ordertime",column = "ordertime"),
            @Result(property = "total",column = "total"),
            @Result(property = "user",column = "uid",
                    javaType = User.class,
                    one = @One(select = "com.itheima.mapper.UserMapper.findById"))
    })
    List<Order> findAll();
}
public interface UserMapper {

    @Select("select * from user where id=#{id}")
    User findById(int id);
    
}
2.4.6 測試結果
@Test
public void testSelectOrderAndUser() {
    List<Order> all = orderMapper.findAll();
    for(Order order : all){
        System.out.println(order);
    }
}

2.5 一對多查詢

2.5.1 一對多查詢的模型

使用者表和訂單表的關係為,一個使用者有多個訂單,一個訂單隻從屬於一個使用者

一對多查詢的需求:查詢一個使用者,與此同時查詢出該使用者具有的訂單

2.5.2 一對多查詢的語句

對應的sql語句:

select * from user;

select * from orders where uid=查詢出使用者的id;

查詢的結果如下:

2.5.3 修改User實體
public class Order {

    private int id;
    private Date ordertime;
    private double total;

    //代表當前訂單從屬於哪一個客戶
    private User user;
}

public class User {
    
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表當前使用者具備哪些訂單
    private List<Order> orderList;
}
2.5.4 建立UserMapper介面
List<User> findAllUserAndOrder();
2.5.5 使用註解配置Mapper
public interface UserMapper {
    @Select("select * from user")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "password",column = "password"),
            @Result(property = "birthday",column = "birthday"),
            @Result(property = "orderList",column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.itheima.mapper.OrderMapper.findByUid"))
    })
    List<User> findAllUserAndOrder();
}

public interface OrderMapper {
    @Select("select * from orders where uid=#{uid}")
    List<Order> findByUid(int uid);

}
2.5.6 測試結果
List<User> all = userMapper.findAllUserAndOrder();
for(User user : all){
    System.out.println(user.getUsername());
    List<Order> orderList = user.getOrderList();
    for(Order order : orderList){
        System.out.println(order);
    }
    System.out.println("-----------------------------");
}

2.6 多對多查詢

2.6.1 多對多查詢的模型

使用者表和角色表的關係為,一個使用者有多個角色,一個角色被多個使用者使用

多對多查詢的需求:查詢使用者同時查詢出該使用者的所有角色

2.6.2 多對多查詢的語句

對應的sql語句:

select * from user;

select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=使用者的id

查詢的結果如下:

2.6.3 建立Role實體,修改User實體
public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    //代表當前使用者具備哪些訂單
    private List<Order> orderList;
    //代表當前使用者具備哪些角色
    private List<Role> roleList;
}

public class Role {

    private int id;
    private String rolename;

}
2.6.4 新增UserMapper介面方法
List<User> findAllUserAndRole();
2.6.5 使用註解配置Mapper
public interface UserMapper {
    @Select("select * from user")
    @Results({
        @Result(id = true,property = "id",column = "id"),
        @Result(property = "username",column = "username"),
        @Result(property = "password",column = "password"),
        @Result(property = "birthday",column = "birthday"),
        @Result(property = "roleList",column = "id",
                javaType = List.class,
                many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid"))
})
List<User> findAllUserAndRole();}



public interface RoleMapper {
    @Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}")
    List<Role> findByUid(int uid);
}

2.6.6 測試結果
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAllUserAndRole();
for(User user : all){
    System.out.println(user.getUsername());
    List<Role> roleList = user.getRoleList();
    for(Role role : roleList){
        System.out.println(role);
    }
    System.out.println("----------------------------------");
}

SSM框架整合

1.1 原始方式整合

1.準備工作
2.建立Maven工程
3.匯入Maven座標

參考:素材/配置檔案/pom.xml檔案

4.編寫實體類
public class Account {
    private int id;
    private String name;
    private double money;
    //省略getter和setter方法
}
5.編寫Mapper介面
public interface AccountMapper {
    //儲存賬戶資料
    void save(Account account);
    //查詢賬戶資料
    List<Account> findAll();
}
6.編寫Service介面
public interface AccountService {
    void save(Account account); //儲存賬戶資料
    List<Account> findAll(); //查詢賬戶資料
}
7.編寫Service介面實現
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    public void save(Account account) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
        accountMapper.save(account);
        sqlSession.commit();
        sqlSession.close();
    }
    public List<Account> findAll() {
        SqlSession sqlSession = MyBatisUtils.openSession();
        AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
        return accountMapper.findAll();
    }
}
8.編寫Controller
@Controller
public class AccountController {
    @Autowired
    private AccountService accountService;
    @RequestMapping("/save")
    @ResponseBody
    public String save(Account account){
        accountService.save(account);
        return "save success";
    }
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("accountList");
        modelAndView.addObject("accountList",accountService.findAll());
        return modelAndView;
    }
}
9.編寫新增頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>儲存賬戶資訊表單</h1>
    <form action="${pageContext.request.contextPath}/save.action" method="post">
        使用者名稱稱<input type="text" name="name"><br/>
        賬戶金額<input type="text" name="money"><br/>
        <input type="submit" value="儲存"><br/>
    </form>
</body>
</html>
10.編寫列表頁面
<table border="1">
    <tr>
        <th>賬戶id</th>
        <th>賬戶名稱</th>
        <th>賬戶金額</th>
    </tr>
    <c:forEach items="${accountList}" var="account">
        <tr>
            <td>${account.id}</td>
            <td>${account.name}</td>
            <td>${account.money}</td>
        </tr>
    </c:forEach>
</table>
11.編寫相應配置檔案(檔案參考目錄:素材/配置檔案)

•Spring配置檔案:applicationContext.xml

•SprngMVC配置檔案:spring-mvc.xml

•MyBatis對映檔案:AccountMapper.xml

•MyBatis核心檔案:sqlMapConfig.xml

•資料庫連線資訊檔案:jdbc.properties

•Web.xml檔案:web.xml

•日誌檔案:[log4j.xml](

12.測試新增賬戶
13.測試賬戶列表

1.2 Spring整合MyBatis

1.整合思路
2.將SqlSessionFactory配置到Spring容器中
<!--載入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置資料來源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>
<!--配置MyBatis的SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
3.掃描Mapper,讓Spring容器產生Mapper實現類
<!--配置Mapper掃描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.itheima.mapper"/>
</bean>
4.配置宣告式事務控制
<!--配置宣告式事務控制-->
<bean id="transacionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transacionManager">
    <tx:attributes>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:pointcut id="txPointcut" expression="execution(* com.itheima.service.impl.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
5.修改Service實現類程式碼
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    public void save(Account account) {
        accountMapper.save(account);
    }
    public List<Account> findAll() {
        return accountMapper.findAll();
    }
}