IT评测·应用市场-qidao123.com技术社区

标题: Spring Mybatis 根本使用 总结 [打印本页]

作者: 民工心事    时间: 2024-9-23 03:29
标题: Spring Mybatis 根本使用 总结
1. 简介

Mybatis库可以简化数据库的操纵,专注于sql语句。


2.搭建步调

2.1 在pom.xml引入mybatis

  1. <dependency>
  2.     <groupId>org.mybatis</groupId>
  3.     <artifactId>mybatis</artifactId>
  4.     <version>3.5.11</version>
  5. </dependency>
复制代码
2.3 在resources下新建mybatis配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0/EN"
  4.         "https://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6.     <settings>
  7. <!--        <setting name="logImpl" value="STDOUT_LOGGING"/>&lt;!&ndash; 开启mybatis的日志输出 &ndash;&gt;-->
  8.         <setting name="mapUnderscoreToCamelCase" value="true"/><!-- 开启驼峰式自动映射 a_big => aBig -->
  9.     </settings>
  10.     <typeAliases>
  11.         <typeAlias alias="goods" type="com.jojo.pojo.Goods"/><!-- 单独设置别名 -->
  12.         <package name="com.jojo.pojo"/><!-- 批量设置别名, com.jojo.pojo包下的所有类名的别名为类的首字母小写-->
  13.     </typeAliases>
  14.     <environments default="development">
  15.         <environment id="development">
  16.             <transactionManager type="JDBC"/>  <!-- 自动开启事务 -->
  17.             <dataSource type="POOLED"><!-- mybatis维护连接池 -->
  18.                 <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  19.                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/>
  20.                 <property name="username" value="root"/>
  21.                 <property name="password" value="a12345678"/>
  22.             </dataSource>
  23.         </environment>
  24.     </environments>
  25.     <mappers>
  26.         <!-- 指定mapper xml文件的位置 -->
  27.         <mapper resource="mappers/GoodsMapper.xml"/>
  28.     </mappers>
  29. </configuration>
复制代码
2.3 在resources/mapper下新建mapper的xml配置文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0/EN"
  4.         "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.jojo.mapper.GoodsMapper"><!-- 对应Mapper的全限定符 -->
  6. <!--    这里写sql语句 -->
  7.     <insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
  8.         insert into goods (name) value(#{name})
  9.     </insert>
  10.     <update id="update">
  11.         update goods set name=#{name} where id=#{id}
  12.     </update>
  13.     <delete id="delete">
  14.         delete from goods where id = #{id}
  15.     </delete>
  16.     <select id="selectById" resultType="goods">
  17.         select * from goods where id = #{id}
  18.     </select>
  19.     <select id="selectAll" resultType="goods">
  20.         select * from goods
  21.     </select>
  22. </mapper>
复制代码
2.4 新建pojo类

  1. import lombok.Data;
  2. @Data//lombook插件的@Data标签可以自动生成get和set以及toString方法
  3. public class Goods {
  4.     private Integer id;
  5.     private String name;
  6. }
复制代码
2.5 新建mapper接口

  1. public interface GoodsMapper {
  2.     int insert(Goods goods);
  3.     int update(Goods goods);
  4.     int delete(Integer id);
  5.     Goods selectById(Integer id);
  6.     List<Goods> selectAll();
  7. }
复制代码
2.6 测试

  1. public class MybatisTest {
  2.     @Test
  3.     public void test() throws IOException {
  4.         //1.读取外部配置文件
  5.         InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");
  6.         //2.创建sqlSessionFactory
  7.         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
  8.         //3.根据sqlSessionFactory创建sqlSession
  9.         SqlSession sqlSession = sqlSessionFactory.openSession();
  10.         //4.获取接口的代理对象,调用代理对象的方法就会查找mapper接口的方法
  11.         GoosdMapper mapper = sqlSession.getMapper(GoosdMapper.class);
  12.         Goods goods = mapper.queryById(1);
  13.         System.out.println(goods);
  14.         //5.提交事务和释放资源
  15.         //sqlSession.commit();
  16.         sqlSession.close();
  17.     }
  18. }
复制代码

3.常用mapper语句

3.1 传入值

  1. <!-- #{id} = 使用占位符?,防止sql注入攻击,但不能替代表名表项-->
  2. <!-- ${id} = 不使用占位符?,不能防止sql注入攻击,但可以替代表名表项-->
  3. <select id="queryById" resultType="com.jojo.pojo.Employee">
  4.     select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where emp_id = #{id}
  5. </select>
  6. <delete id="deleteById">
  7.     delete from t_emp where emp_id = #{id} <!-- 传入Integer类型,id可以改写成任意字符串-->
  8. </delete>
  9. <select id="queryBySalary" resultType="com.jojo.pojo.Employee">
  10.     select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{salary} <!-- 传入Double类型,salary可以改写成任意字符串-->
  11. </select>
  12. <insert id="insertEmp">
  13.     insert into t_emp (emp_name, emp_salary) values (#{empName},#{empSalary});<!-- 传入对象时,要写传入对象的属性 -->
  14. </insert>
  15. <select id="queryByNameAndSalary" resultType="com.jojo.pojo.Employee">
  16.     select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{a} and empName = #{b} <!-- 传入两个基本类型,根据接口中的@Param("名称")来指定-->
  17. </select>
  18. <select id="queryByNameAndSalary" resultType="com.jojo.pojo.Employee">
  19.     select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{arg0} and empName = #{arg1} <!-- 法2:传入两个基本类型,可以根据顺序来取arg0...arg1...-->
  20. </select>
  21. <select id="queryByNameAndSalary" resultType="com.jojo.pojo.Employee">
  22.     select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where empSalary = #{param1} and empName = #{param2} <!-- 法3:传入两个基本类型,可以根据顺序来取param1...param2...-->
  23. </select>
  24. <insert id="insertEmpMap">
  25.     insert into t_emp (emp_name, emp_salary) values (#{name},#{salary});<!-- 传入Map时,要写传入Map的key -->
  26. </insert>
复制代码

3.2 返回值

  1. <select id="queryNameById" resultType="string"><!-- resultType指定返回的类型,写类的全限定符或者mybatis提供的别名(在mybatis官网查)-->
  2.     select emp_name from t_emp where emp_id = #{id}
  3. </select>
  4. <select id="queryById" resultType="employee"> <!-- resultType指定返回的为对象时,select的行需要起别名来与类的属性完全一致-->
  5.     select emp_id empId,emp_name empName, emp_salary empSalary from t_emp where emp_id = #{id}
  6. </select>
  7. <select id="queryById" resultType="employee"><!-- resultType指定返回的为对象时,开启驼峰映射(mapUnderscoreToCamelCase)后,select的行不再需要起别名来与类的属性完全一致-->
  8.     select * from t_emp where emp_id = #{id}  
  9. </select>
  10. <select id="selectEmpNameAndMaxSalary" resultType="map"> <!-- resultType返回的值没有未定义类时,可以用map接值,map的每一项的key对应一个列名 -->
  11.     select emp_name 员工姓名, emp_salary 员工工资, (SELECT AVG(emp_salary) from t_emp) 部门平均工资 from t_emp where emp_salary=(select max(emp_salary) from t_emp)
  12. </select>
  13. <select id="queryNamesBySalary" resultType="string"><!--如果返回类型时List<String>,那么指定String即可-->
  14.     select emp_name from t_emp where emp_salary > #{ salary};
  15. </select>
  16. <select id="queryAll" resultType="employee"><!--如果返回类型时List<Employee>,那么指定Employee即可-->
  17.     select * from t_emp;
  18. </select>
  19. <insert id="insertEmp" useGeneratedKeys="true" keyColumn="emp_id" keyProperty="empId"><!-- 主键自增长型:插入时,获取插入的id放在empId中 -->
  20.     insert into t_emp (emp_name, emp_salary) value(#{empName},#{empSalary});
  21. </insert>
  22. <insert id="insertTeacher">
  23.     <selectKey order="BEFORE" resultType="string" keyProperty="tId">
  24.         select replace(UUID(),'-',''); <!-- 插入前由数据库生成uuid并放在tId中-->
  25.     </selectKey>
  26.     insert into teacher (t_id,t_name) value (#{tId},#{tName})
  27. </insert>
复制代码
4.多表查询

4.1 一对一

1对1关系:一个A类中包含一个B类:
  1. public class A {
  2.     private Integer Id;
  3.     private String aName;
  4.     private Integer bId;
  5.     private B b;
  6. }
  7. public class B {
  8.     private Integer bId;
  9.     private String bName;
  10. }
复制代码
使用resultMap来装数据:
  1. <resultMap id="aMap" type="a">
  2.     <!-- a的主键 id标签-->
  3.     <id column="a_id" property="aId"/>
  4.     <!-- order的普通列 custom标签-->
  5.     <result column="a_name" property="aName"/>
  6.     <result column="b_id" property="bId"/>
  7.     <!-- 给第二层对象属性赋值 -->
  8.     <association property="b" javaType="b">
  9.         <id column="b_id" property="bId"/>
  10.         <result column="b_name"  property="bName"></result>
  11.     </association>
  12. </resultMap>
  13. <select id="queryAById" resultMap="aMap">
  14.     SELECT * FROM t_a ta join t_b tb on ta.b_id = tb.b_id where ta.a_id = #{id};
  15. </select>
复制代码
在config文件中参加:
  1. <settings>
  2.         <!-- 开启驼峰式自动映射 a_big => aBig -->
  3.     <setting name="mapUnderscoreToCamelCase" value="true"/>
  4.     <!-- 开启自动映射 a_big => aBig -->
  5.     <setting name="autoMappingBehavior" value="FULL"/>
  6. </settings>
复制代码
后可省略主键以外的映射关系:
  1. <resultMap id="aMap" type="a">
  2.     <!-- a的主键 id标签-->
  3.     <id column="a_id" property="aId"/>
  4.     <!-- 给第二层对象属性赋值 -->
  5.     <association property="b" javaType="b">
  6.         <id column="b_id" property="bId"/>
  7.     </association>
  8. </resultMap>
  9. <select id="queryAById" resultMap="aMap">
  10.     SELECT * FROM t_a ta join t_b tb on ta.b_id = tb.b_id where ta.a_id = #{id};
  11. </select>
复制代码
4.2 一对多

1对多关系:一个A类中包含多个B类(List):
  1. public class A {
  2.     private Integer Id;
  3.     private String aName;
  4.     private Integer bId;
  5.     private List<B> bList;
  6. }
  7. public class B {
  8.     private Integer bId;
  9.     private String bName;
  10. }
复制代码
使用resultMap来装数据:
  1. <resultMap id="aMap" type="a">
  2.     <id column="a_id" property="aId"/>
  3.     <result column="a_name" property="aName"/>
  4.      <result column="b_id" property="bId"/>
  5.     <!--针对List<A>属性使用collection -->
  6.     <collection property="bList" ofType="b">
  7.         <id column="b_id" property="bId"></id>
  8.         <result column="b_name" property="bName"/>
  9.     </collection>
  10. </resultMap>
  11. <select id="queryAList" resultMap="aMap">
  12.     select * from t_a ta join t_b tb on ta.customer_id = tb.customer_id
  13. </select>
复制代码
在config文件中参加:
  1. <settings>
  2.         <!-- 开启驼峰式自动映射 a_big => aBig -->
  3.     <setting name="mapUnderscoreToCamelCase" value="true"/>
  4.     <!-- 开启自动映射 a_big => aBig -->
  5.     <setting name="autoMappingBehavior" value="FULL"/>
  6. </settings>
复制代码
后可省略主键以外的映射关系:
  1. <resultMap id="aMap" type="a">
  2.     <id column="a_id" property="aId"/>
  3.     <!--针对List<A>属性使用collection -->
  4.     <collection property="bList" ofType="b">
  5.         <id column="b_id" property="bId"></id>
  6.     </collection>
  7. </resultMap>
  8. <select id="queryAList" resultMap="aMap">
  9.     select * from t_a ta join t_b tb on ta.customer_id = tb.customer_id
  10. </select>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4