其他分享
首页 > 其他分享> > MyBatis

MyBatis

作者:互联网

MyBatis

持久层

框架

初次使用Mybatis

​ 略

​ 配置pom文件,添加依赖

MyBits-config中的配置:

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
<!--                数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///db3?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        加载sql的映射文件 编写了sql映射文件以后写入地址-->  
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

这里需要根据sql的映射文件来加入

<?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">

<!--namespace:名称空间
 id:在使用的时候的唯一标签
 resultType:返回的结果集对象
-->
<mapper namespace="test">
    <select id="selectAll" resultType="com.qiu.pojo.User">
        select * from tb_user;
    </select>
</mapper>
//1.加载mybatis的核心配置文件,获取sqlsessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

//2.获取sqlSession对象 并用它执行sql语句
SqlSession sqlSession = sqlSessionFactory.openSession();

//执行sql语句
List<User> users = sqlSession.selectList("test.selectAll");

System.out.println(users);
// 释放资源
sqlSession.close();

至此完成一个Demo项目 测试结果如下所示:

image

解决sql映射文件的警告提示

image

用Mapper代理开发

image

  1. 设置SQL映射文件的namespace属性为Mapper接口全限定名
<mapper namespace="com.qiu.Mapper.UserMapper">  
    <select id="selectAll" resultType="com.qiu.pojo.User">
        select * from tb_user;
    </select>
</mapper>
  1. 在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
public interface UserMapper {
    List<User> selectAll();
} //因为这里是查询所有数据返回的是多个user对象 这里用list接受

同时记得修改MyBatis-config里面的Mapper路径:

<!--        加载sql的映射文件-->
      <!--   <mapper resource="com/qiu/Mapper/UserMapper.xml"/> -->
<!--        mapper代理的方式-->
        <package name="com.qiu.Mapper"/>    
    </mappers>
</configuration>

编码:

//3.1 获取对应的UserMapper的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectAll();

测试结果如下image

MyBatisX插件

image

可以在Mapper配置文件和对应接口之间来回跳动

案例

<mapper namespace="com.qiu.Mapper.BrandMapper">
    <resultMap id="brandResultMap" type="brand">
<!--        id:唯一标识
type 映射类型-->
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
<!--        id:完成主健字段的映射
result 完成其他字段的映射-->
    </resultMap>

<!--数据库表的字段名称和实体类的属性名称不一样,则不能自动封装-->
    <select id="selectAll" resultMap="brandResultMap">
        select * from  tb_brand ;
    </select>
</mapper>

这里需要注意 因为数据库的字段名和brand实体类中的变量名不同 不能自动封装 ,需要使用 resultMap标签来进行映射 具体看上面的代码

  //MyBatis运用mapper代理 查找所有数据
    public void selectAll() throws IOException {
        //1.加载mybatis的核心配置文件,获取sqlsessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.获取sqlSession对象 并用它执行sql语句
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //执行sql语句
        //3.1 获取对应的BrandMapper的代理对象

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();

        System.out.println(brands);
        sqlSession.close();
    }
}

测试结果如下所示:

image

参数占位符和参数类型

sql语句设置多个参数的三个方法:

List<Brand> selectByCondition(@Param("status") int status, @Param("brandName") String brandName, @Param("companyName")String companyName);

//参数设置

 int status=0;
        String brandName="只";
        String companyName="只";
        brandName="%"+brandName+"%";
        companyName="%"+companyName+"%";

//执行语句
List<Brand> brands = mapper.selectByCondition(status, brandName, companyName);
ist<Brand> selectByCondition(Brand brand);


//参数设置
int status=0;
        String brandName="只";
        String companyName="只";
        brandName="%"+brandName+"%";
        companyName="%"+companyName+"%";
        Brand brand=new Brand();
        brand.setStatus(status);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);

//执行语句
List<Brand> brands = mapper.selectByCondition(brand);
List<Brand> selectByCondition(Map map);


//参数设置
Map map =new HashMap();
        map.put("status",status);
        map.put("brandName",brandName);
        map.put("companyName",companyName);
        
//执行语句
List<Brand> brands = mapper.selectByCondition(map);

动态sql

if标签:

# 动态sql
    <where>
            <if test="status!=null">
                status=#{status}
            </if>
            <if test="brandName!=null and brandName!=''">
                and brand_name like #{brandName}
            </if>
            <if test="companyName!=null and companyName!=''">
                and company_name like #{companyName};
            </if>
        </where>

choose when标签

 <choose>    <!-- 相当于switch-->
               <when test="status!=null">
#                                       相当于case
                   status=#{status};
               </when>
               <when test="brandName!=null">
                   brand_name like #{brandName};
               </when>
               <when test="companyName!=null">
                   company_name like #{companyName};
               </when>
                <otherwise>
                    1=1;
                </otherwise>
           </choose>

foreach标签

<foreach collection="ids" item="id" separator=","  open="(" close=")">
    #{id}
</foreach>

标签:status,companyName,brand,sqlSession,brandName,sql,MyBatis
来源: https://www.cnblogs.com/xiaoqiuStu/p/16125521.html