一小时迅速入门Mybatis之Bind与多数据源支持Java API

一、场景

CE985399-DB2E-E19B-3133-0CEF06147D4F.png

数据库表:

DROP TABLE IF EXISTS `person`;
CREATE TABLE `person`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
  `job_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '工作名称',
  `salary` decimal(10, 2) NULL DEFAULT NULL COMMENT '薪资',
  `age` int(11) NULL DEFAULT NULL COMMENT '年龄',
  `gender` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别',
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址',
  `hobby` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '爱好',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- 两个人 一个小月月 一个小强
-- ----------------------------
INSERT INTO `person` VALUES (1, '小强', '学生', 0.00, 16, '男', '北京市海淀区大柳树南站', '爱好学习语文');
INSERT INTO `person` VALUES (2, '小月月', '程序猿', 100000.00, 19, '女', '石家庄市', '爱好女');
DROP TABLE IF EXISTS `mobile`;
CREATE TABLE `mobile`  (
  `p_id` bigint(20) NULL DEFAULT NULL COMMENT 'person表主键',
  `mobile` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号',
  `isp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '网络运营商'
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- 小月月和小强一个人有俩手机 
-- ----------------------------
INSERT INTO `mobile` VALUES (1, '18888888888', '移动');
INSERT INTO `mobile` VALUES (1, '19999999999', '联通');
INSERT INTO `mobile` VALUES (2, '18822222222', '电信');
INSERT INTO `mobile` VALUES (2, '19234566666', '小灵通');

现在有个需求是查询所有的人,并且查出所有手机号,但是有个条件是,如果年龄小于18,那么不对外暴露性别和住址

二、 实现
2.1 创建实体类
package entity;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 * @create 2021-08-30 21:45
 */
public class Person {
    public Person(){}
    public Person(Long id,String name){
        System.out.println("使用了构造函数");
        this.id = id;
        this.name = name;
    }
    private Long id;
    private String name;
    private String jobName;
    private BigDecimal salary;
    private Integer age;
    private String gender;
    private String address;
    private String hobby;
    private List<Mobile> mobiles;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

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

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public List<Mobile> getMobiles() {
        return mobiles;
    }

    public void setMobiles(List<Mobile> mobiles) {
        this.mobiles = mobiles;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", jobName='" + jobName + '\'' +
                ", salary=" + salary +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", address='" + address + '\'' +
                ", hobby='" + hobby + '\'' +
                ", mobiles=" + mobiles +
                '}';
    }
}
package entity;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 * @create 2021-08-30 21:47
 */
public class Mobile {
    private Long pId;
    private String mobile;
    private String isp;

    public Long getpId() {
        return pId;
    }

    public void setpId(Long pId) {
        this.pId = pId;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getIsp() {
        return isp;
    }

    public void setIsp(String isp) {
        this.isp = isp;
    }

    @Override
    public String toString() {
        return "Mobile{" +
                "pId=" + pId +
                ", mobile='" + mobile + '\'' +
                ", isp='" + isp + '\'' +
                '}';
    }
}
2.2 创建 接口
package dao;

import entity.Person;

import java.util.List;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程  分享一个生活在互联网底层做着增删改查的码农的感悟与学习
 * @create 2021-08-30 21:54
 */
public interface PersonMapper {
    List<Person> list();
}
2.3 创建xml

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>
        <package name="entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--扫描-->
    <mappers>
        <mapper resource="PersonMapper.xml"/>
    </mappers>
</configuration>
<?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="dao.PersonMapper">
    
    <resultMap id="personResultMap" type="entity.Person">
        <!--构造函数-->
        <constructor>
            <idArg column="id" jdbcType="BIGINT" javaType="long"/>
            <arg column="name" jdbcType="VARCHAR" javaType="string"/>
        </constructor>
        <!--普通属性-->
        <result property="jobName" column="job_name" jdbcType="VARCHAR" javaType="string"/>
        <result property="salary" column="salary" jdbcType="DECIMAL"  javaType="decimal"/>
        <!--集合-->
        <collection property="mobiles" javaType="java.util.List" ofType="entity.Mobile" >
            <id property="pId" column="p_id" javaType="long" jdbcType="BIGINT"/>
            <result property="mobile" column="mobile" javaType="string" jdbcType="VARCHAR"/>
            <result property="isp" column="isp" javaType="string" jdbcType="VARCHAR"/>
        </collection>
        <!--根据年龄来判断展示什么属性-->
        <discriminator javaType="int" column="age">
            <!--年龄16 值显示爱好-->
            <case value="16"  resultType="entity.Person">
                <result column="hobby" property="hobby" javaType="string" jdbcType="VARCHAR"/>
            </case>
            <!--年龄19 显示年龄 性别 爱好 住址-->
            <case value="19" resultType="entity.Person">
                <result column="age" property="age" javaType="int" jdbcType="INTEGER"/>
                <result column="gender" property="gender" javaType="string" jdbcType="VARCHAR"/>
                <result column="hobby" property="hobby" javaType="string" jdbcType="VARCHAR"/>
                <result column="address" property="address" javaType="string" jdbcType="VARCHAR"/>
            </case>
        </discriminator>
    </resultMap>
    <!--查询-->   
    <select id="list" resultMap="personResultMap">
        select a.*,b.* from person a
        left join mobile b on a.id = b.p_id
    </select>
</mapper>
2.4 测试
import dao.PersonMapper;
import entity.Person;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 */
public class TestMain03 {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper
            PersonMapper mapper = session.getMapper(PersonMapper.class);
            List<Person> list = mapper.list();
            Optional.ofNullable(list).orElse(new ArrayList<>()).forEach(item -> {
                System.out.println(item);
            });
        }
    }
}

输出结果:

3079B1B0-F007-1157-E367-283C0349A86D.png

collection还可以写子查询,下篇写一下子查询的方式

收藏 (0)
评论列表
正在载入评论列表...
我是有底线的
为您推荐
    暂时没有数据