Mybatis学习(三)

时间:2020-05-19
本文章向大家介绍Mybatis学习(三),主要包括Mybatis学习(三)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Mybatis学习(三)

Mybatis中的连接池以及事务控制

  连接池:
    我们在实际开发中都会使用到连接池
    因为它可以减少我们获取连接所消耗的时间

  mybatis中的连接池:
    mybatis连接池提供了三种方式的配置:
      配置的位置:
        主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式

      type属性的取值:
        POOLED 采用传统的Javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
        UNPOOLED 采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想
        JNDI 采用服务器提供的JNDI技术实现,来获取DataSource对象,不同服务器拿到的DataSource是不一样的
          注意:如果不是web或者maven的war工程,是不能使用的

    mybatis中设置自动提交事务

	sqlSession = factory.openSession(true);

Mybatis基于XML配置的动态SQL语句使用

if标签

映射配置文件

      <select id="findByCondition" resultType="com.itcast.domain.User" parameterType="com.itcast.domain.User">
        select * from user where 1=1
        <if test="username!= null">
            and username = #{username}
        </if>
      </select>-->

测试类

@Test
    public void testFindByCondition(){
        User u = new User();
        u.setUsername("老王");
        u.setSex("男");
        List<User> users = userDao.findByCondition(u);
        for (User user : users) {
            System.out.println(user);
        }
    }

where标签

     <select id="findByCondition" resultType="com.itcast.domain.User" parameterType="com.itcast.domain.User">
        select * from user
        <where>
            <if test="username!= null">
                and username = #{username}
            </if>
            <if test="sex!=null">
                and sex = #{sex}
            </if>
        </where>
    </select>

foreach标签

映射配置文件

<!--根据Queryvo中的id集合实现查询用户列表-->
    <select id="findByIds" resultType="com.itcast.domain.User" parameterType="com.itcast.domain.QueryVo">
        select * from user
        <where>
            <if test="ids != null and ids.size() > 0">
                <foreach collection="ids" open="and id in(" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

测试类

@Test
    public void testFindInIds(){
        QueryVo vo = new QueryVo();
        List<Integer> list = new ArrayList<Integer>();
        list.add(41);
        list.add(42);
        list.add(43);
        vo.setIds(list);

        List<User> users = userDao.findByIds(vo);

        for (User user : users) {
            System.out.println(user);
        }
    }

sql 标签

      <sql id="default">
        select * from user
      </sql>
 <!--查询用户-->
      <select id="findAll" resultType="com.itcast.domain.User">
        <include refid="default"></include>
      </select>

Mybatis中的多表操作

一对一查询(一)

定义账户信息的实体类

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;
  
    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }
}

定义AccountUser实体类

public class AccountUser extends Account {
    private String username;
    private String address;

    public String getUsername() {
        return username;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return super.toString() + "           AccountUser{" +
                "username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}


定义用户的持久层Dao接口

import java.util.List;

public interface AccountDao {
    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAll();

    /**
     * 查询所有账号,并且带有用户名和地址信息
     * @return
     */
    List<AccountUser> findAllAccount();

}

定义AccountDao.xml文件中的查询配置信息

  <!--查询所有并且包含用户名和地址信息-->
    <select id="findAllAccount" resultType="com.itcast.domain.AccountUser">
        select a.*,u.username,u.address from account a,user u where u.id = a.uid;
    </select>

创建AccountTest测试类

    /**
     * 测试查询所有账户,同时包含用户名称和地址
     */
    @Test
    public void testFindAllAccountUser(){
        List<AccountUser> allAccount = accountDao.findAllAccount();
        for (AccountUser accountUser : allAccount) {
            System.out.println(accountUser);
        }
    }

一对一查询(二)

修改Account类

    private User user;

    public User getUser() {
        return user;
    }

修改AccountDao接口中的方法

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAll();

重新定义AccountDao.xml文件

<!-- 定义封装account和user的resultMap -->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!-- 一对一的关系映射:配置封装user的内容-->
        <association property="user" column="uid" javaType="user">
            <id property="id" column="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </association>
    </resultMap>

修改AccountTest测试方法

    /**
     * 测试查询所有
     * @throws Exception
     */
    @Test
    public void testFindAll(){

        //执行查询所有方法
        List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println("--------每个account的信息------------");
            System.out.println(account);
            System.out.println(account.getUser());
        }

    }

一对多查询

定义user类

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;
    private List<Account> accounts;

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

    @Override
    public String toString() {
        return "domain{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

在持久层Dao接口中加入查询方法

    /**
     * 查找所有
     * @return
     */
    List<User> findAll();

配置持久层Dao映射配置文件

    <resultMap id="UserAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!--配置user对象中account集合的映射-->
        <collection property="accounts" ofType="account">
            <id column="aid" property="id"></id>
            <result column="uid" property="uid"></result>
            <result column="money" property="money"></result>
        </collection>
    </resultMap>
    <!--查询用户-->
    <select id="findAll" resultMap="UserAccountMap">
        select * from user u left outer join account a on u.id=a.uid;
    </select>

添加测试方法

    /**
     * 测试查询所有
     * @throws Exception
     */
    @Test
    public void testFindAll(){

        //执行查询所有方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
            System.out.println(user.getAccounts());
        }

    }

多对多查询

编写角色实体类

import java.io.Serializable;
import java.util.List;

public class Role implements Serializable {
    private Integer roleId;
    private String roleName;
    private String roleDesc;
    private List<User> users;

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }
}

编写用户实体类

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;
    private List<Role> roles;

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    @Override
    public String toString() {
        return "domain{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}


编写Role持久层接口

import java.util.List;

public interface RoleDao {
    /**
     * 查询所有角色
     * @return
     */
    List<Role> findAll();
}

编写User持久层接口

import java.util.List;

public interface UserDao {
    /**
     * 查找所有
     * @return
     */
    List<User> findAll();
    
}

编写Role映射文件

    <resultMap id="roleMap" type="role">
        <id property="roleId" column="id"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        <collection property="users" ofType="user">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
    </resultMap>

    <!--查询所有-->
    <select id="findAll" resultMap="roleMap">
       select u.*,r.id as rid,r.role_name,r.role_desc from  role r left outer join user_role ur on
        r.id = ur.rid left outer join user u on u.id = ur.uid ;
    </select>

编写User映射文件

     <resultMap id="UserAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
    <collection property="roles" ofType="role">
        <id property="roleId" column="rid"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
    </collection>
    </resultMap>
    <!--查询用户-->
    <select id="findAll" resultMap="UserAccountMap">
        select u.*,r.id as rid,r.role_name,r.role_desc from user u left outer join user_role ur on
        u.id = ur.uid left outer join role r  on r.id = ur.rid;
    </select>

编写Role测试类

public class RoleTest {
    private InputStream in;
    private SqlSession sqlSession;
    private RoleDao roleDao;
    /**
     * 定义初始化方法
     */
    @Before
    public void init() throws Exception{
        //读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获取SqlsessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //获取Sqlsession对象
        sqlSession = factory.openSession();
        //获取dao代理对象
        roleDao= sqlSession.getMapper(RoleDao.class);
    }
    @After
    public void destroy() throws Exception{

        //提交事务
        sqlSession.commit();

        //.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     * @throws Exception
     */
    @Test
    public void testFindAll(){

        List<Role> list = roleDao.findAll();
        for (Role role : list) {
            System.out.println(role);
            System.out.println(role.getUsers());
        }

    }

}

编写User测试类

public class UserTest {
    private InputStream in;
    private SqlSession sqlSession;
    private UserDao userDao;
    /**
     * 定义初始化方法
     */
    @Before
    public void init() throws Exception{
        //读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获取SqlsessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //获取Sqlsession对象
        sqlSession = factory.openSession();
        //获取dao代理对象
        userDao= sqlSession.getMapper(UserDao.class);
    }
    @After
    public void destroy() throws Exception{

        //提交事务
        sqlSession.commit();

        //.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     * @throws Exception
     */
    @Test
    public void testFindAll(){

        //执行查询所有方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
            System.out.println(user.getRoles());
        }

    }

}

原文地址:https://www.cnblogs.com/dankon/p/12915781.html