基础

首先这次学习mybatis,得先下载idea软件。maven在idea上好操作点,破解方案自行百度。这里暂不详细介绍。
image.png
这是最初的练习,可能注释有问题,但是后面的代码就纠正过来了。
image.png
为了更好的xml分离,就创建了一个文件夹,然后转成编译包,在再下面创建相同的mapper包。
image.png
下面是代码

  1. <dependencies>
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>8.0.28</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mybatis</groupId>
  9. <artifactId>mybatis</artifactId>
  10. <version>3.5.9</version>
  11. </dependency>
  12. </dependencies>

数据库DAO层

  1. package org.lisonglin.entity;
  2. public class Student {
  3. private int id;
  4. private String name;
  5. private int age;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public int getAge() {
  19. return age;
  20. }
  21. public void setAge(int age) {
  22. this.age = age;
  23. }
  24. public Student(int id, String name, int age) {
  25. this.id = id;
  26. this.name = name;
  27. this.age = age;
  28. }
  29. public Student(String name, int age) {
  30. this.name = name;
  31. this.age = age;
  32. }
  33. public Student() {
  34. }
  35. @Override
  36. public String toString() {
  37. return "Student{" +
  38. "id=" + id +
  39. ", name='" + name + '\'' +
  40. ", age=" + age +
  41. '}';
  42. }
  43. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <!-- 对数据库与属性不一致,自动转换 -->
  8. <setting name="mapUnderscoreToCamelCase" value="true"/>
  9. </settings>
  10. <environments default="development">
  11. <environment id="development">
  12. <transactionManager type="JDBC"/>
  13. <dataSource type="POOLED">
  14. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  15. <property name="url" value="jdbc:mysql://localhost:3306/stus?createDatabaseIfNotExist=true&amp;useSSL=false"/>
  16. <property name="username" value="root"/>
  17. <property name="password" value="123"/>
  18. </dataSource>
  19. </environment>
  20. </environments>
  21. <mappers>
  22. <!-- 调用dao层 -->
  23. <mapper resource="org/lisonglin/mapper/StudentMapper.xml"/>
  24. </mappers>
  25. </configuration>
  1. package org.lisonglin.mapper;
  2. import org.apache.ibatis.annotations.Param;
  3. import org.lisonglin.entity.Student;
  4. public interface StudentMapper {
  5. Student get(int id);
  6. void insert(Student stu);
  7. void insertInfo(@Param("name") String name, @Param("age") int age);
  8. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="org.lisonglin.mapper.StudentMapper">
  6. <select id="get" resultType="org.lisonglin.entity.Student">
  7. select * from student where id=#{id}
  8. </select>
  9. <insert id="insert">
  10. insert into student values(null,#{name},#{age})
  11. </insert>
  12. <insert id="insertInfo">
  13. insert into student values(null,#{name},#{age})
  14. </insert>
  15. </mapper>

测试

  1. package org.lisonglin.test;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  6. import org.junit.Test;
  7. import org.lisonglin.entity.Student;
  8. import org.lisonglin.mapper.StudentMapper;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. public class TestMyBatis {
  12. @Test
  13. public void test(){
  14. InputStream is=null;
  15. try {
  16. //获取src下全局配置文件的输入流
  17. is = Resources.getResourceAsStream("mybatis-config.xml");
  18. //获取SqlSessionFactory对象
  19. SqlSessionFactory factory =new SqlSessionFactoryBuilder().build(is);
  20. SqlSession sqlSession = factory.openSession();
  21. StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
  22. // Student student = mapper.get(1);
  23. // System.out.print(student);
  24. // Student s=new Student();
  25. // s.setName("bb");
  26. // s.setAge(12);
  27. // mapper.insert(s);
  28. mapper.insertInfo("cc",13);
  29. //手动提交
  30. sqlSession.commit();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }

image.png
新增成功~

进阶

  1. <dependencies>
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>8.0.28</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mybatis</groupId>
  9. <artifactId>mybatis</artifactId>
  10. <version>3.5.9</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>junit</groupId>
  14. <artifactId>junit</artifactId>
  15. <version>4.13.2</version>
  16. </dependency>
  17. </dependencies>
  1. package org.lisonglin.entity;
  2. public class Student {
  3. private int id;
  4. private String sName;
  5. private int age;
  6. public final static String MYBATIS_CONFIG_FILE="mybatis-config2.xml";
  7. public int getId() {
  8. return id;
  9. }
  10. public void setId(int id) {
  11. this.id = id;
  12. }
  13. public String getsName() {
  14. return sName;
  15. }
  16. public void setsName(String sName) {
  17. this.sName = sName;
  18. }
  19. public int getAge() {
  20. return age;
  21. }
  22. public void setAge(int age) {
  23. this.age = age;
  24. }
  25. @Override
  26. public String toString() {
  27. return "Student{" +
  28. "id=" + id +
  29. ", sName='" + sName + '\'' +
  30. ", age=" + age +
  31. '}';
  32. }
  33. public Student(int id, String sName, int age) {
  34. this.id = id;
  35. this.sName = sName;
  36. this.age = age;
  37. }
  38. public Student() {
  39. }
  40. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!-- 读取配置文件信息 -->
  7. <properties resource="jdbc.properties"></properties>
  8. <settings>
  9. <!--把数据中的下划线改为驼峰命名法-->
  10. <setting name="mapUnderscoreToCamelCase" value="true"/>
  11. </settings>
  12. <typeAliases>
  13. <!-- 别名 -->
  14. <!--<typeAlias type="org.lisonglin.entity.Student" alias="Student"></typeAlias>-->
  15. <!-- 直接导包 -->
  16. <package name="org.lisonglin.entity"></package>
  17. </typeAliases>
  18. <!-- 配置坏境变量,可以配置多个,默认值与id一致 -->
  19. <environments default="development">
  20. <environment id="development">
  21. <transactionManager type="JDBC"></transactionManager><!--事务-->
  22. <dataSource type="POOLED"><!-- 数据源 连接池POOLED -->
  23. <property name="driver" value="${jdbc.driver}"/>
  24. <property name="url" value="${jdbc.url}"/>
  25. <property name="username" value="${jdbc.username}"/>
  26. <property name="password" value="${jdbc.password}"/>
  27. </dataSource>
  28. </environment>
  29. </environments>
  30. <!--配置映射文件-->
  31. <mappers>
  32. <!--基于XML配置文件-->
  33. <!--<mapper resource="org/lisonglin/mapper/StudentMapper.xml"/>-->
  34. <package name="org.lisonglin.mapper"></package>
  35. </mappers>
  36. </configuration>
  1. package org.lisonglin.mapper;
  2. import org.apache.ibatis.annotations.Param;
  3. import org.apache.ibatis.annotations.Select;
  4. import org.lisonglin.entity.Student;
  5. import java.util.List;
  6. public interface StudentMapper {
  7. /**
  8. * XML配置方式
  9. * @param id
  10. * @return
  11. */
  12. Student get(int id);
  13. void insert(Student stu);
  14. void insertInfo(@Param("name") String name, @Param("age") int age);
  15. List<Student> getAll();
  16. int insertStudentCacheId(Student stu);
  17. List<Student> getByName(@Param("key") String key);
  18. List<Student> getByIds(@Param("ids") int ... ids);
  19. List<Student> getStudents(Student stu);
  20. /**
  21. * 注解方式(代码耦合性不高,不推荐)
  22. * @param stu
  23. * @return
  24. */
  25. @Select("insert into stu(id,s_name,age) values(null,#{name},#{age})")
  26. public int add(Student stu);
  27. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="org.lisonglin.mapper.StudentMapper">
  6. <!-- 通用sql -->
  7. <sql id="selectInfo">
  8. select * from stu
  9. </sql>
  10. <select id="getById" resultType="Student" parameterType="int">
  11. <!-- 引入通用sql -->
  12. <include refid="selectInfo"></include>
  13. where id=#{id}
  14. </select>
  15. <select id="getStudents" resultType="Student">
  16. <include refid="selectInfo"></include>
  17. <!-- 条件查询,如果没有符合条件,那么sql中的and会自动去掉 -->
  18. <where>
  19. <!-- 判断中属性是bean中的命名 -->
  20. <if test="sName != null">
  21. and s_name = #{sName}
  22. </if>
  23. <if test="age!=0">
  24. and age = #{age}
  25. </if>
  26. </where>
  27. </select>
  28. <select id="getByIds" resultType="Student">
  29. <include refid="selectInfo"></include>
  30. <where>
  31. <!--<foreach collection="ids" open="id in (" close=")" separator="," item="id">-->
  32. <!--id=#{id}-->
  33. <!--</foreach>-->
  34. <foreach collection="ids" item="id" separator="or">
  35. id=#{id}
  36. </foreach>
  37. </where>
  38. </select>
  39. <select id="get" resultType="Student" parameterType="int">
  40. select * from stu where id=#{id}
  41. </select>
  42. <insert id="insert">
  43. insert into stu values(null,#{name},#{age})
  44. </insert>
  45. <insert id="insertInfo">
  46. insert into stu values(null,#{name},#{age})
  47. </insert>
  48. <select id="getAll" resultType="Student">
  49. select * from stu
  50. </select>
  51. <!-- 查询出增加的主键(方法一) -->
  52. <insert id="insertStudentCacheId" keyColumn="id" keyProperty="id" useGeneratedKeys="true">
  53. insert into stu values(null,#{sName},#{age})
  54. </insert>
  55. <!-- 方法二 -->
  56. <insert id="insertStudentId">
  57. <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
  58. <!-- 查询自增id (方法一) -->
  59. select last_insert_id()
  60. <!--方法二-->
  61. <!--select @@identity-->
  62. </selectKey>
  63. insert into stu values(null,#{sName},#{age})
  64. </insert>
  65. <select id="getByName" resultType="Student">
  66. <!-- ${} 拼接sql #{} 占位符 -->
  67. <!-- 推荐使用这种 -->
  68. <!-- select * from stu where s_name like '%' #{key} '%' -->
  69. <bind name="new_key" value="'%'+key+'%'"></bind>
  70. <include refid="selectInfo"></include>
  71. where s_name like #{new_key}
  72. <!-- select * from stu where s_name like concat('%',#{key},'%') -->
  73. <!-- 这种不建议使用,这种使用statement查询方式,有sql注入风险 -->
  74. <!-- select * from stu where s_name like '%${key}%' -->
  75. </select>
  76. </mapper>
  1. package org.lisonglin.servlet;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  6. import org.lisonglin.entity.Student;
  7. import org.lisonglin.mapper.StudentMapper;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. public class DataUtil {
  11. private static SqlSessionFactory sqlSessionFactory;
  12. public static StudentMapper getStudentMapper(){
  13. InputStream is=null;
  14. try {
  15. is = Resources.getResourceAsStream("mybatis-config.xml");
  16. SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
  17. SqlSession sqlSession = build.openSession();
  18. StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
  19. return mapper;
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. return null;
  24. }
  25. public static SqlSessionFactory getSqlSessionFactory(){
  26. InputStream is=DataUtil.class.getClassLoader().getResourceAsStream(Student.MYBATIS_CONFIG_FILE);
  27. return new SqlSessionFactoryBuilder().build(is);
  28. }
  29. /**
  30. * @param autoCommit
  31. * true:表示创建的SqlSession对象在执行完SQL之后自动提交事务
  32. * false:表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用SqlSession.commit()提交事务
  33. * @return
  34. */
  35. public static SqlSession getSqlSession(boolean autoCommit){
  36. return getSqlSessionFactory().openSession(autoCommit);
  37. }
  38. public static SqlSession getSqlSession(){
  39. return getSqlSessionFactory().openSession();
  40. }
  41. }
  1. package org.lisonglin.test;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  5. import org.junit.Test;
  6. import org.lisonglin.dao.StudentImpl;
  7. import org.lisonglin.entity.Student;
  8. import org.lisonglin.mapper.StudentMapper;
  9. import org.lisonglin.servlet.DataUtil;
  10. import java.io.IOException;
  11. import java.io.Reader;
  12. import java.util.List;
  13. public class MyTest {
  14. private SqlSessionFactory sqlSessionFactory;
  15. @Test
  16. public void getStudentByAgeOrNames(){
  17. StudentMapper studentMapper = DataUtil.getStudentMapper();
  18. Student student=new Student();
  19. student.setAge(20);
  20. System.out.println(student.toString());
  21. List<Student> studentByAgeOrName = studentMapper.getStudents(student);
  22. System.out.println(studentByAgeOrName);
  23. }
  24. @Test
  25. public void getByIdsStudent(){
  26. StudentMapper studentMapper = DataUtil.getStudentMapper();
  27. List<Student> byIds = studentMapper.getByIds(1, 2, 3);
  28. System.out.println(byIds);
  29. }
  30. @Test
  31. public void getByNameStu(){
  32. StudentMapper studentMapper = DataUtil.getStudentMapper();
  33. List<Student> a = studentMapper.getByName("a");
  34. System.out.println(a);
  35. }
  36. @Test
  37. public void getMapperAll(){
  38. StudentMapper sqlSession = DataUtil.getStudentMapper();
  39. List<Student> all = sqlSession.getAll();
  40. System.out.print(all.toString());
  41. }
  42. /**
  43. * mybatis代理模式
  44. */
  45. @Test
  46. public void getMapperMybatis(){
  47. StudentMapper sqlSession = DataUtil.getStudentMapper();
  48. Student student = sqlSession.get(1);
  49. System.out.print(student);
  50. }
  51. @Test
  52. public void insertGetId(){
  53. StudentMapper studentMapper = DataUtil.getStudentMapper();
  54. Student stu=new Student();
  55. stu.setAge(12);
  56. stu.setsName("aaa");
  57. int i = studentMapper.insertStudentCacheId(stu);
  58. System.out.println(i);
  59. System.out.println(stu.getId());
  60. }
  61. /**
  62. * 原生Dao开发
  63. */
  64. @Test
  65. public void getDaoMyBatis(){
  66. String resource = "mybatis-config.xml";
  67. Reader reader = null;
  68. try {
  69. reader = Resources.getResourceAsReader(resource);
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  74. StudentMapper studentMapper=new StudentImpl(sqlSessionFactory);
  75. Student student = studentMapper.get(2);
  76. System.out.print(student);
  77. }
  78. }