Mybatis 代理模式創建

  • mybatis代理模式與非代理模式的區別:

    1. mapper類只需要定義接口,mapper映射文件的namespace的值必須爲mapper接口的全類名

    2. 書寫的SQL的ID 必須與mapper接口中的相對應的方法名相同

    配置文件mybatisConfig.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 resource="jdbc.properties"/>
    <typeAliases>
        <package name="mybatis.domian"/>
        <package name="mybatis.vo"/>
    </typeAliases>
    <environments default="mybatis_1">
        <environment id="mybatis_1">
            <transactionManager type="JDBC"/>
            <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>
        <package name="mybatis.mapper"></package>
    </mappers>
</configuration>

實體類User

package mybatis.domian;

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

public class User implements Serializable{
    private Integer id;
    private String name;
    private  String password;
    private Float salary;
    private Date birthday;
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Float getSalary() {
        return salary;
    }
    public void setSalary(Float salary) {
        this.salary = salary;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(id, user.id) &&
                Objects.equals(name, user.name) &&
                Objects.equals(salary, user.salary) &&
                Objects.equals(birthday, user.birthday);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id, name, salary, birthday);
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}

實體類Department

package mybatis.domian;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Department implements Serializable {
    private Integer id;
    private String name;
    private  String location;
   private Set<User> set = new HashSet<>();

    public Set<User> getSet() {
        return set;
    }

    public void setSet(Set<User> set) {
        this.set = set;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", location='" + location + '\'' +
                '}';
    }
}

mapper接口 UserMapper

package mybatis.mapper;

import mybatis.domian.Department;
import mybatis.domian.User;
import mybatis.vo.UserQueryVo;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    void save(User user);
    void delete(User user);
    void update(User user);
    User findById(Integer id);
    List<User> findAll();
    List<User> findByMap(Map<String,Object> map);
    List<User> findQueryVo(UserQueryVo userQueryVo);
    Department findDepaetmentByUserName(String name);
    Department findDepaetmentByUserName1(String name);
    User findUserByName(String name);

}

Service接口

package mybatis.service;

import mybatis.domian.Department;
import mybatis.domian.User;

import java.util.List;

public interface UserService {
    void addUser(User user);
    List<User> findAllUserList();
    User checkLogin(String name,String password);

    /**
     * 查詢某人所在部門
     * @param name
     * @return
     */
    Department findDepaetmentByUserName(String name);
    Department findDepaetmentByUserName1(String name);
    Department findDepaetmentByUserName2(String name);
}
package mybatis.service;

import mybatis.domian.User;

import java.util.List;

public interface DepartmentService {
    List<User> findUserListByDepartmenyName(String name);
    List<User> findUserListByDepartmenyName1(String name);
}

Service接口實現類

package mybatis.service.impl;

import mybatis.domian.Department;
import mybatis.domian.User;
import mybatis.mapper.UserMapper;
import mybatis.service.UserService;
import mybatis.util.MybatisUtils;
import mybatis.vo.UserQueryVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class UerServiceImpl implements UserService{
    @Override
    public void addUser(User user) {
        SqlSession sqlSession = null;
        if (user == null) {
            throw new IllegalArgumentException("");
        }
        try{
            sqlSession = MybatisUtils.getSqlSession();
        /*
           如何mapper文件使用不是代理模式 則此處需要寫成
           namespace+方法名
           使用的爲代理模式時,則可以直接使用方法名
         */
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.save(user);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.clolseSqlSession();
        }

    }

    @Override
    public List<User> findAllUserList() {
        SqlSession sqlSession = null;
        List<User> userList = Collections.emptyList(); // 避免空指針異常

        try{
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            userList = mapper.findAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.clolseSqlSession();
        }
            return  userList;
    }

    /**
     * 登陸方法
     * @param name
     * @param password
     * @return
     */
    @Override
    public User checkLogin(String name ,String password) {
        SqlSession sqlSession = null;
        UserQueryVo userQueryVo = null;
        User user = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            userQueryVo = new UserQueryVo();
            userQueryVo.setName(name);
            userQueryVo.setPassword(password);
           List<User> users = mapper.findQueryVo(userQueryVo);
           if (CollectionUtils.isNotEmpty(users)){
               user = users.get(0);
           }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MybatisUtils.clolseSqlSession();
        }
        return user;
    }

    @Override
    public Department findDepaetmentByUserName(String name) {
        SqlSession sqlSession = null;
        UserQueryVo userQueryVo = null;
        Department department = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            department = new Department();
            department = mapper.findDepaetmentByUserName(name);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MybatisUtils.clolseSqlSession();
        }
        return department;
    }

    @Override
    public Department findDepaetmentByUserName1(String name) {
        SqlSession sqlSession = null;
        UserQueryVo userQueryVo = null;
        Department department = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            department = new Department();
            department = mapper.findDepaetmentByUserName1(name);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MybatisUtils.clolseSqlSession();
        }
        return department;
    }
    @Override
    public Department findDepaetmentByUserName2(String name){
        SqlSession sqlSession = null;
        UserQueryVo userQueryVo = null;
        User user = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            user = new User();
            user = mapper.findUserByName(name);
            System.out.println(user);
            if (user != null){
                return user.getDepartment();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MybatisUtils.clolseSqlSession();
        }
        return null;
    }
}
package mybatis.service.impl;

import mybatis.domian.Department;
import mybatis.domian.User;
import mybatis.mapper.DepartmentMapper;
import mybatis.service.DepartmentService;
import mybatis.util.MybatisUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class DepartmentServiceImpl implements DepartmentService {
    @Override
    public List<User> findUserListByDepartmenyName(String name) {
        List<User> userList = Collections.emptyList();
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
            userList = mapper.findUserListByDepartmenyName(name);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.clolseSqlSession();
        }
        return userList;
    }
    @Override
    public List<User> findUserListByDepartmenyName1(String name) {
        List<User> userList = new ArrayList<>();
        Department department = null;
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
            department = mapper.findByName(name);
            if (department != null){
                Set<User> userSet = department.getSet();
                // 將 userSet中的數據 全部加入到userList
                CollectionUtils.addAll(userList, userSet.iterator());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.clolseSqlSession();
        }
        return userList;
    }
}

UserQueryVo


public class UserQueryVo extends User {
}

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="mybatis.mapper.UserMapper">

    <insert id="save" parameterType="User">
        INSERT  INTO
             mybatis_user(user_name,user_password,user_salary,user_birthday)
         VALUE
               (#{name},#{password},#{salary},#{birthday})

    </insert>
    <select id="findAll" resultType="User">
        SELECT
            user_id id ,
            user_name name,
            user_password password ,
            user_salary salary ,
            user_birthday birthday
        FROM
            mybatis_user
    </select>
    <!--
    parameterType:參數類型
    resultType:結果類型
    模糊查詢:可在代碼中傳遞參數時使用 % 或者在SQL中使用%
    -->
    <select id="findQueryVo" resultType="User" parameterType="UserQueryVo">
        SELECT
                user_id id ,
                user_name name,
                user_password password ,
                user_salary salary ,
                user_birthday birthday
        FROM
                mybatis_user
        WHERE
            1=1
        <if test="name != null and name != '' ">
            AND user_name LIKE  "%" #{name} "%"
        </if>
        <if test="password != null and password != ''">
             AND user_password LIKE "%" #{password}"%"
        </if>
        <if test="salary != null and salary != '' ">
            AND user_salary LIKE  "%" #{salary} "%"
        </if>
        <if test="birthday != null and birthday != ''">
            AND user_birthday LIKE "%" #{birthday} "%"
        </if>
    </select>
    <select id="findDepaetmentByUserName" parameterType="java.lang.String" resultType="Department">
          SELECT
                d.department_id id,
                d.department_name name,
                d.department_location location
          FROM
                mybatis_user u
          LEFT JOIN
                mybatis_department d
          ON
                u.department_id = d.department_id
          WHERE
                u.user_name = #{name}
    </select>
    <resultMap id="DepartmentRM" type="Department">
          <id property="id" column="department_id"/>
          <result property="name" column="department_name"/>
          <result property="location" column="department_location"/>
    </resultMap>
    <select id="findDepaetmentByUserName1" parameterType="java.lang.String" resultMap="DepartmentRM">
          SELECT
                d.department_id ,
                d.department_name ,
                d.department_location
          FROM
                mybatis_user u
          LEFT JOIN
                mybatis_department d
          ON
                u.department_id = d.department_id
          WHERE
                u.user_name = #{name}
    </select>

    <!--多對一-->
    <resultMap id="UserRM" type="User">
        <id property="id" column="user_id"/>
        <result property="name" column="user_name"/>
        <result property="password" column="user_password"/>
        <result property="salary" column="user_salary"/>
        <result property="birthday" column="birthday"/>
        <association property="department" column="depaetment_id" javaType="Department">
            <id property="id" column="department_id"/>
            <result property="name" column="department_name"/>
            <result property="location" column="department_location"/>
        </association>
    </resultMap>
    <select id="findUserByName" parameterType="java.lang.String" resultMap="UserRM">
            SELECT
                u.user_id,
                u.user_name,
                u.user_salary,
                u.user_password,
                u.user_birthday,
                d.department_id ,
                d.department_name ,
                d.department_location
          FROM
                mybatis_user u
          INNER JOIN
                mybatis_department d
          ON
                u.department_id = d.department_id
          WHERE
                u.user_name = #{name}
    </select>
</mapper>

Department.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="mybatis.mapper.DepartmentMapper">

    <select id="findUserListByDepartmenyName" parameterType="java.lang.String" resultType="User">
        SELECT
                u.user_id id ,
                u.user_name name,
                u.user_salary salary ,
                u.user_password password ,
                u.user_birthday birthday
          FROM
                mybatis_user u
                INNER JOIN
                    mybatis_department d
                     ON
                         u.department_id = d.department_id
          WHERE
                d.department_name = #{name}
    </select>
    <resultMap id="DepartmentRM" type="Department">
        <id property="id" column="department_id"/>
        <result property="name" column="department_name"/>
        <result property="location" column="department_location"/>
        <collection property="set" column="depaetment_id" ofType="User">
            <id property="id" column="user_id"/>
            <result property="name" column="user_name"/>
            <result property="password" column="user_password"/>
            <result property="salary" column="user_salary"/>
            <result property="birthday" column="user_birthday"/>
        </collection>
    </resultMap>
    <select id="findByName" resultMap="DepartmentRM">
        SELECT
                u.user_id,
                u.user_name,
                u.user_salary,
                u.user_password,
                u.user_birthday,
                d.department_id ,
                d.department_name ,
                d.department_location
          FROM
                mybatis_user u
          INNER JOIN
                mybatis_department d
          ON
                u.department_id = d.department_id
          WHERE
                d.department_name = #{name}
    </select>
</mapper>

重點內容


collection: 集合 表示多的一方,比如一個部門中有多 個員工,其中property表示所映射的屬性名,column該屬性在數據庫中的列名,ofType該屬性的類型名稱

association: 有一個 比如:一個員工對應一個部門propertycolumn與collection中屬性相同,javaType屬性的類型名稱

resultType: 表示結果類型,當數據庫字段名與實體字段名相同時可直接使用實體類名

resultMap: 當數據庫字段與實體字段不同,且SQL 對查詢字段並未起表明時, 需要對結果進行映射


方法思想,在做條件查詢時,創建了UserQueryVo實體類 ,通過集成實體類,得到實體的屬性,實現對查詢條件的封裝

PS: 僅日常筆記整理,有錯誤請指出,噴子繞路

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章