07-MyBatis基础

2021-02-09  本文已影响0人  XAbo

一、MyBatis入门

1.1 入门案例

User:

public class User {
    private String id;
    private String userName;
    private String userPass;
  //省略get/set 
    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", userName='" + userName + '\'' +
                ", userPas='" + userPass + '\'' +
                '}';
    }
}

UserMapper:

public interface UserMapper {
    List<User> listAllUsers();
}

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.example.dao.UserMapper">
    <!-- 配置查询所有用户 -->
    <select id="listAllUsers" resultType="com.example.domain.User">
        select * from  [User]
    </select>
</mapper>

Client:

public class Client {
    @Test
    public void testInit() {
        try {
            // 1. 读取配置文件
           //使用绝对路径和相对路径(src/java/main/xxx.xml)都不行。
           //通常使用:
           // 1.使用类加载器:只能读取类路径下的配置文件
           // 2.使用ServletContext对象的getRealPath()。    -- Web项目
            InputStream is = null;
            try {
                is = Resources.getResourceAsStream("mybatis-config.xml");
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 2. 创建 SqlSessionFactory 工厂
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(is);
            // 3. 获取 SqlSession 对象
            SqlSession sqlSession = factory.openSession();
            // 4. 使用 SqlSession 创建 Mapper 的代理对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            // 5. 使用代理对象执行查询
            List<User> users = mapper.listAllUsers();
            users.forEach(System.out::println);
            // 6. 释放资源
            sqlSession.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

mybatis-config.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>

    <!--使用typeAliases配置别名,只能配置domain中类的别名-->
   <typeAliases>
      <!-- <typeAlias type="com.example.User" alias="user"></typeAlias>-->
      <!--指定配置别名的包,配置后类名就是别名,不区分大小写-->
       <package name="com.example.domain"></package>
   </typeAliases>
    <!-- 全局变量 -->
    <!--第一种:resource引用类路径下的配置文件-->
   <properties resource="jdbc.properties"></properties>
   <!--第一种:url引用类路径下的配置文件-->
   <!--<properties url="ftp:///d:/jdbc.properties"></properties>-->
    <!--第二种:直接配置-->
    <!--<properties>
        <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
        <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=TestDB"/>
        <property name="username" value="sa"/>
        <property name="password" value="123"/>
    </properties>-->
    <!--配置环境-->
    <environments default="development">
        <environment id="development">
            <!-- 配置事务类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射文件 -->
    <mappers>
        <!--<mapper resource="com/example/dao/UserMapper.xml"/>-->
        <!--指定 DAO接口所在包,不需要写mapper的resource/class-->
        <package name="com.example.dao"></package>
    </mappers>
</configuration>

二、原理解析

2.1 设计思路

与Jdbc方式相比,Mybatis的相关配置文件已经具备所有数据库操作信息,关键在于如何封装,其代理对象mapper(即dao)应该具备真实dao的功能。mapper对象(容器),核心内容:

key value
com.example.dao.UserMapper.listAllUsers mapper{sql:"select * from [User]",returnType:"com.example.domain.User"}

2.2 模拟Mybatis

https://blog.csdn.net/a1092882580/article/details/104086181

pom.xml:去掉mybatis

<dependencies>
    <!-- 数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.8</version>
        <scope>runtime</scope>
    </dependency>
    <!-- 日志 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- JUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <!-- 解析 xml 的 dom4j -->
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    <!-- dom4j 的依赖包 jaxen -->
    <dependency>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <version>1.1.6</version>
    </dependency>
</dependencies>

编写读取配置文件类 Resources:

public class Resources {
    public static InputStream getResourceAsStream(String filePath) {
        return Resources.class.getClassLoader().getResourceAsStream(filePath);
    }
}

编写 Mapper 类:

public class Mapper {
    // sql语句
    private String queryString;
   // 结果类型的全限定类名
    private String resultType;
  //省略get/set
}

编写自定义 Mybatis 的配置类 Configuration:

public class Configuration {
    private String driver;
    private String url;
    private String username;
    private String password;
    // 必须new一个集合出来,不然下面调用putAll会空指针异常
    private Map<String, Mapper> mappers = new HashMap<String, Mapper>();
    //省略get/set ……
    public Map<String, Mapper> getMappers() {
        return mappers;
    }
    public void setMappers(Map<String, Mapper> mappers) {
        // 这里应该使用put的方式,直接赋值的话会覆盖原本Map集合中的内容
        this.mappers.putAll(mappers);
    }
}

编写构建者类 SqlSessionFactoryBuilder:

public class SqlSessionFactoryBuilder {
    public SqlSessionFactory build(InputStream config) {
        Configuration cfg = XMLConfigBuilder.loadConfiguration(config);
        return new DefaultSqlSessionFactory(cfg);
    }
}

编写 SqlSessionFactory 接口:

public interface SqlSessionFactory {
    SqlSession openSession();
}

编写 DefaultSqlSessionFactory 类:

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private Configuration cfg;
    public DefaultSqlSessionFactory(Configuration cfg) {
        this.cfg = cfg;
    }
    public SqlSession openSession() {
        return new DefaultSqlSession(cfg);
    }
}

编写 SqlSession 接口:

public interface SqlSession {
    <T> T getMapper(Class<T> daoInterfaceClass);
    void close();
}

编写 DefaultSqlSession 类:

public class DefaultSqlSession implements SqlSession {
    private Configuration cfg;
    private Connection conn;
    public DefaultSqlSession(Configuration cfg) {
        this.cfg = cfg;
        conn = DataSourceUtil.getConnection(cfg);
    }
    public <T> T getMapper(Class<T> daoInterfaceClass) {
        return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
                new Class[]{daoInterfaceClass}, new MapperProxy(cfg.getMappers(), conn));
    }
    public void close() {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

编写代理类 MapperProxy:

public class MapperProxy implements InvocationHandler {
    // map的key为全限定类名 + 方法名
    private Map<String, Mapper> mappers;
    private Connection conn;
    public MapperProxy(Map<String, Mapper> mappers, Connection conn) {
        this.mappers = mappers;
        this.conn = conn;
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 获取方法名
        String methodName = method.getName();
        // 获取方法所在的类的名称
        String className = method.getDeclaringClass().getName();
        // 组合key
        String key = className + "." + methodName;
        // 获取Mapper
        Mapper mapper = mappers.get(key);
        // 判断是否有mapper
        if (mapper == null) {
            throw new IllegalArgumentException("传入的参数有误");
        }
        // 调用工具类进行查询
        return new Executor().selectList(mapper, conn);
    }
}

导入提前准备的工具类 XMLConfigBuilder,用于解析 XML 文件:

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 *  用于解析配置文件
 */
public class XMLConfigBuilder {
    /**
     * 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方
     * 使用的技术:
     *      dom4j+xpath
     */
    public static Configuration loadConfiguration(InputStream config){
        try{
            //定义封装连接信息的配置对象(mybatis的配置对象)
            Configuration cfg = new Configuration();

            //1.获取SAXReader对象
            SAXReader reader = new SAXReader();
            //2.根据字节输入流获取Document对象
            Document document = reader.read(config);
            //3.获取根节点
            Element root = document.getRootElement();
            //4.使用xpath中选择指定节点的方式,获取所有property节点
            List<Element> propertyElements = root.selectNodes("//property");
            //5.遍历节点
            for(Element propertyElement : propertyElements){
                //判断节点是连接数据库的哪部分信息
                //取出name属性的值
                String name = propertyElement.attributeValue("name");
                if("driver".equals(name)){
                    //表示驱动
                    //获取property标签value属性的值
                    String driver = propertyElement.attributeValue("value");
                    cfg.setDriver(driver);
                }
                if("url".equals(name)){
                    //表示连接字符串
                    //获取property标签value属性的值
                    String url = propertyElement.attributeValue("value");
                    cfg.setUrl(url);
                }
                if("username".equals(name)){
                    //表示用户名
                    //获取property标签value属性的值
                    String username = propertyElement.attributeValue("value");
                    cfg.setUsername(username);
                }
                if("password".equals(name)){
                    //表示密码
                    //获取property标签value属性的值
                    String password = propertyElement.attributeValue("value");
                    cfg.setPassword(password);
                }
            }
            //取出mappers中的所有mapper标签,判断他们使用了resource还是class属性
            List<Element> mapperElements = root.selectNodes("//mappers/mapper");
            //遍历集合
            for(Element mapperElement : mapperElements){
                //判断mapperElement使用的是哪个属性
                Attribute attribute = mapperElement.attribute("resource");
                if(attribute != null){
                    System.out.println("使用的是XML");
                    //表示有resource属性,用的是XML
                    //取出属性的值
                    String mapperPath = attribute.getValue();//获取属性的值"com/itheima/dao/IUserDao.xml"
                    //把映射配置文件的内容获取出来,封装成一个map
                    Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
                    //给configuration中的mappers赋值
                    cfg.setMappers(mappers);
                }else{
                    System.out.println("使用的是注解");
                    //表示没有resource属性,用的是注解
                    //获取class属性的值
                    String daoClassPath = mapperElement.attributeValue("class");
                    //根据daoClassPath获取封装的必要信息
                    Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
                    //给configuration中的mappers赋值
                    cfg.setMappers(mappers);
                }
            }
            //返回Configuration
            return cfg;
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
            try {
                config.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据传入的参数,解析XML,并且封装到Map中
     * @param mapperPath    映射配置文件的位置
     * @return  map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成)
     *          以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名)
     */
    private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
        InputStream in = null;
        try{
            //定义返回值对象
            Map<String,Mapper> mappers = new HashMap<String,Mapper>();
            //1.根据路径获取字节输入流
            in = Resources.getResourceAsStream(mapperPath);
            //2.根据字节输入流获取Document对象
            SAXReader reader = new SAXReader();
            Document document = reader.read(in);
            //3.获取根节点
            Element root = document.getRootElement();
            //4.获取根节点的namespace属性取值
            String namespace = root.attributeValue("namespace");//是组成map中key的部分
            //5.获取所有的select节点
            List<Element> selectElements = root.selectNodes("//select");
            //6.遍历select节点集合
            for(Element selectElement : selectElements){
                //取出id属性的值      组成map中key的部分
                String id = selectElement.attributeValue("id");
                //取出resultType属性的值  组成map中value的部分
                String resultType = selectElement.attributeValue("resultType");
                //取出文本内容            组成map中value的部分
                String queryString = selectElement.getText();
                //创建Key
                String key = namespace+"."+id;
                //创建Value
                Mapper mapper = new Mapper();
                mapper.setQueryString(queryString);
                mapper.setResultType(resultType);
                //把key和value存入mappers中
                mappers.put(key,mapper);
            }
            return mappers;
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
            in.close();
        }
    }

    /**
     * 根据传入的参数,得到dao中所有被select注解标注的方法。
     * 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息
     * @param daoClassPath
     * @return
     */
    private static Map<String,Mapper> loadMapperAnnotation(String daoClassPath)throws Exception{
        //定义返回值对象
        Map<String,Mapper> mappers = new HashMap<String, Mapper>();

        //1.得到dao接口的字节码对象
        Class daoClass = Class.forName(daoClassPath);
        //2.得到dao接口中的方法数组
        Method[] methods = daoClass.getMethods();
        //3.遍历Method数组
        for(Method method : methods){
            //取出每一个方法,判断是否有select注解
            boolean isAnnotated = method.isAnnotationPresent(Select.class);
            if(isAnnotated){
                //创建Mapper对象
                Mapper mapper = new Mapper();
                //取出注解的value属性值
                Select selectAnno = method.getAnnotation(Select.class);
                String queryString = selectAnno.value();
                mapper.setQueryString(queryString);
                //获取当前方法的返回值,还要求必须带有泛型信息
                Type type = method.getGenericReturnType();//List<User>
                //判断type是不是参数化的类型
                if(type instanceof ParameterizedType){
                    //强转
                    ParameterizedType ptype = (ParameterizedType)type;
                    //得到参数化类型中的实际类型参数
                    Type[] types = ptype.getActualTypeArguments();
                    //取出第一个
                    Class domainClass = (Class)types[0];
                    //获取domainClass的类名
                    String resultType = domainClass.getName();
                    //给Mapper赋值
                    mapper.setResultType(resultType);
                }
                //组装key的信息
                //获取方法的名称
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String key = className+"."+methodName;
                //给map赋值
                mappers.put(key,mapper);
            }
        }
        return mappers;
    }
    
}

编写自定义注解 Select:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select {
    String value();
}

编写数据库工具类 DataSourceUtil:

public class DataSourceUtil {
    public static Connection getConnection(Configuration cfg) {
        try {
            Class.forName(cfg.getDriver());
            return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

导入提前准备好的工具类 Executor ,用于执行jdbc相关操作:

public class Executor {
    public <E> List<E> selectList(Mapper mapper, Connection conn) {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            //1.取出mapper中的数据
            String queryString = mapper.getQueryString();//select * from user
            String resultType = mapper.getResultType();//com.itheima.domain.User
            Class domainClass = Class.forName(resultType);
            //2.获取PreparedStatement对象
            pstm = conn.prepareStatement(queryString);
            //3.执行SQL语句,获取结果集
            rs = pstm.executeQuery();
            //4.封装结果集
            List<E> list = new ArrayList<E>();//定义返回值
            while(rs.next()) {
                //实例化要封装的实体类对象
                E obj = (E)domainClass.newInstance();
                //取出结果集的元信息:ResultSetMetaData
                ResultSetMetaData rsmd = rs.getMetaData();
                //取出总列数
                int columnCount = rsmd.getColumnCount();
                //遍历总列数
                for (int i = 1; i <= columnCount; i++) {
                    //获取每列的名称,列名的序号是从1开始的
                    String columnName = rsmd.getColumnName(i);
                    //根据得到列名,获取每列的值
                    Object columnValue = rs.getObject(columnName);
                    //给obj赋值:使用Java内省机制(借助PropertyDescriptor实现属性的封装)
                    PropertyDescriptor pd = new PropertyDescriptor(columnName,domainClass);//要求:实体类的属性和数据库表的列名保持一种
                    //获取它的写入方法
                    Method writeMethod = pd.getWriteMethod();
                    //把获取的列的值,给对象赋值
                    writeMethod.invoke(obj,columnValue);
                }
                //把赋好值的对象加入到集合中
                list.add(obj);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            release(pstm,rs);
        }
    }
    private void release(PreparedStatement pstm,ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        if(pstm != null){
            try {
                pstm.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

三、使用细节

3.1 模糊查询

<!-- 根据名称模糊查询 -->
    <select id="findByName" parameterType="string" resultMap="userMap">
   <!--第一种:使用的PrepatedStatement的参数占位符,推荐使用。-->
    select * from user where username like #{name}
    <!--第二种:使用的是Statement对象的字符串拼接SQL-->
    <!--select * from user where username like '%${value}%'-->
   </select>

3.2 参数类型

示例:传递pojo包装对象

package com.itheima.domain;
public class QueryVo {
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}
<!-- 根据queryVo的条件查询用户 -->
<select id="findUserByVo" parameterType="com.itheima.domain.QueryVo" resultMap="userMap">
    select * from user where username like #{user.username}
</select>

3.3 结果类型

当数据库字段名和实体类的属性名不一致时候:resultMap

   <!--第二种解决办法:使用resultMap -->
   <!-- 配置查询结果的列名和实体类的属性名的对应关系 -->
    <resultMap id="userMap" type="user">
        <!-- 主键字段的对应 -->
        <id property="userId" column="id"></id>
        <!--非主键字段的对应-->
        <result property="userName" column="username"></result>
        <result property="userAddress" column="address"></result>
        <result property="userSex" column="sex"></result>
        <result property="userBirthday" column="birthday"></result>
    </resultMap>
    <!-- 查询所有 -->
    <select id="findAll" resultMap="userMap">
        <!--第一种解决办法:使用别名-->
        <!--select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user;-->
        select * from user;
    </select>

调用存储过程返回多个结果集:

  <resultMap type="Integer" id="count">  
    <result column="RecordCount"   jdbcType="INTEGER" javaType="Integer" />   
  </resultMap>  
 
  <resultMap type="OrderForm" id="orders">   
    <result column="OrderId" property="id" jdbcType="VARCHAR" javaType="String"/>  
  </resultMap> 
 
  <select id="getOrders" statementType="CALLABLE" parameterType="Map"  resultMap="count,orders" >
   {call Page_Up_Get_OrderState(#{id,mode=IN,jdbcType=VARCHAR})}

3.4 连接池

连接池有很多种,最为熟悉的比如c3p0,DBCP,druid等。mybatis自己又实现了连接池(非c3p0,DBCP,druid)
mybatis支持三种内置的数据源类型:

Spring使用c3p0连接池:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="password"   value="${jdbc.pwd}"></property>
        <property name="user"       value="${jdbc.uid}"></property>
        <property name="jdbcUrl"    value="${jdbc.url}"></property>
</bean>

mybtis的Pooled池:

 <dataSource type="POOLED">
       <property name="driver" value="${driver}"/>
       <property name="url" value="${url}"/>
       <property name="username" value="${username}"/>
       <property name="password" value="${password}"/>
</dataSource>

四、动态SQL

4.1 if标签

<!-- 根据条件查询 -->
<select id="findByCondition" resultMap="userMap">
   select * from user where 1=1
   <if test="username !=  null">
       username = #{username}
  </if>
</select>

4.2 chose标签

<select id="selectSelective" resultMap="xxx" parameterType="xxx">
    select
    <include refid="Base_Column_List"/>
    from xxx   where del_flag=0
    <choose>
        <when test="xxx !=null and xxx != ''">
            and xxx like concat(concat('%', #{xxx}), '%')
        </when>
        <otherwise>
            and xxx like '**%'
        </otherwise>
    </choose>
</select>

4.3 foreach标签

<mapper namespace="cn.zhku.jsj.mybatis.mapper.UserMapper">
    <!-- QueryVo pojo中进行List<Integer>封装 
       通过List<Integer> ids查询用户 select * from user where id in (1,2,3) -->
    <select id="queryUserByIdsQueryVo" parameterType="queryVo"
        resultType="user">
        select * from user
        <where>
            id in
            <foreach collection="ids" item="item" open="(" close=")"
                separator=",">
                #{item}
            </foreach>
        </where>
    </select>
    <!-- List直接进行封装 
         通过List<Integer> ids查询用户 select * from user where id in (1,2,3) -->
    <select id="queryUserByIdsList" parameterType="list" resultType="user">
        select * from user
        <where>
            id in
            <if test="list!=null">
                <foreach collection="list" item="item" open="(" close=")"
                    separator=",">
                    #{item}
                </foreach>
            </if>
        </where>
    </select>
    <!-- Array数组直接进行封装,数组是Integer[] ids:里面都是Integer类型的 
         通过Integer[] ids查询用户 select * from user where id in (1,2,3) -->
    <select id="queryUserByArray" parameterType="Integer[]"
        resultType="user">
        select * from user
        <where>
            id in
            <if test="array!=null">
                <foreach collection="array" item="item" open="(" close=")"
                    separator=",">
                    #{item}
                </foreach>
            </if>
        </where>
    </select>
    <!-- Array数组直接进行封装,数组是Object[] objs:里面都是pojo类型的User 
             通过Object[] objs查询用户select * from user where id in (1,2,3) -->
    <select id="queryUserByPojoArray" parameterType="Object[]"
        resultType="user">
        select * from user
        <where>
            id in
            <if test="array!=null">
                <foreach collection="array" item="item" open="(" close=")"
                    separator=",">
                    #{item.id}
                </foreach>
            </if>
        </where>
    </select>
</mapper>

五、多表操作

5.1 一对多

User:

public class User implements Serializable {
    private Integer id; //省略get/set
    private String username; //省略get/set
    private String address; //省略get/set
    private String sex; //省略get/set
    private Date birthday; //省略get/set
    //一对多关系映射:主表实体应该包含从表实体的集合引用
    private List<Account> accounts;
    public List<Account> getAccounts() {
        return accounts;
    }
    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }
}

Account:

public class Account implements Serializable {
    private Integer id;//省略get/set
    private Integer uid;//省略get/set
    private Double money;//省略get/set
    //从表实体应该包含一个主表实体的对象引用
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

UserDao:

public interface UserDao {
    List<User> findAll();
}

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.example.dao.UserDao">

 <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="accounts"  ofType="com.example.domain.Account">
         <id property="aid" column="aid"></id>  
         <result property="uid" column="uid"></result>
         <result property="money" column="money"></result>
      </collection>
   </resultMap>

    <select id="findAll" resultMap="userAccountMap">
        select * from  [User] u left  join Accout a on u.id = a.uid
    </select>
</mapper>

AccountDao:

public interface AccountDao {
    List<Account> findAll();
}

AccountMapper.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.example.dao.AccountDao">

    <resultMap id ="accountUserMap" type ="account">
     <id property="id" column="aid"></id>
     <result property="uid" column="uid"></result>
     <result property="money" column="money"></result>
    <!--配置一对一-->
      <association property="user" column="uid"  javaType="com.example.domain.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>
      </association>
   </resultMap>

    <select id="findAll" resultMap="accountUserMap">
     select u.*,a.id as aid ,a.uid ,a.money from  [Account] a ,[User] u where u.id = a.uid    
   </select>
</mapper>

5.1 多对多

中间表:

CREATE TABLE `user_role` (
  `UID` int(11) NOT NULL COMMENT '用户编号',
  `RID` int(11) NOT NULL COMMENT '角色编号',
  PRIMARY KEY  (`UID`,`RID`),
  KEY `FK_Reference_10` (`RID`),
  CONSTRAINT `FK_Reference_10` FOREIGN KEY (`RID`) REFERENCES `role` (`ID`),
  CONSTRAINT `FK_Reference_9` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

User:

public class User implements Serializable {
    private Integer id;//省略get/set
    private String username;//省略get/set
    private String address;//省略get/set
    private String sex;//省略get/set
    private Date birthday;//省略get/set
    //多对多的关系映射:一个用户可以具备多个角色
    private List<Role> roles;
    public List<Role> getRoles() {
        return roles;
    }
    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
}

UserDao:

public interface UserDao {
    List<User> findAll();
    User findById(Integer userId);
}

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.example.dao.UserDao">

 <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="com.example.domain.Role">
     <id property="roleId" column="rid"></id>
     <result property="rolename" column="role_name"></result>
     <result property="roleDesc" column="role_desx"></result>
     </collection>
</resultMap>

    <select id="findAll" resultMap="userAccountMap">
        select u.*,r.id as rid,r.role_name,r.role_desc from user u 
        left join user_role ur on r.id=ur.rid
        left join  role r  on r.id= ur.rid
    </select>
</mapper>

Role:

public class Role implements Serializable {
    private Integer roleId;//省略get/set
    private String roleName;//省略get/set
    private String roleDesc;//省略get/set
    //多对多的关系映射:一个角色可以赋予多个用户
    private List<User> users;
    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }
}

RoleDao:

public interface RoleDao {
    List<Role> findAll();
}

RoleMapper.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.example.dao.RoleDao">

 <resultMap id ="RoleMap" type ="role">
     <id property="roleId" column="id"></id>
     <result property="rolename" column="role_name"></result>
     <result property="roleDesc" column="role_desx"></result>
    <!--配置多对多-->
     <collection  property="users"  ofType="com.example.domain.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>
 </resultMap>

    <select id="findAll" resultMap="RoleMap">
        select u.*,r.id as rid,r.role_name,r.role_desc from role r 
        left join user_role ur on r.id=ur.rid
        left join  user  u  on u.id= ur.uid
    </select>
</mapper>
上一篇下一篇

猜你喜欢

热点阅读