介绍
- 三层架构:视图层、业务逻辑层、持久层
- mybatis框架:
- 执行数据库操作,完成对数据库的增删改查,封装了jdbc
- mapper映射,将表中数据转为一个Java对象,一个表对应一个接口
Mybatis实战
- 使用方式:
- 直接获取SqlSession,根据sql id执行sql
- 自定义dao接口实现类,使用接口实现类对象操作(会有大量重复代码)
- 使用mybatis的代理对象:使用getMapper()获取dao对象,直接执行方法访问数据库。
- mybatis框架使用步骤:
- 定义实体类
- 定义接口
- 定义mapper文件
- 定义主配置文件:1.数据源,2.mapper文件位置
- 使用SqlSessionFactoryBuild创建SqlSessionFactory并传入xml配置文件,通过Factory创建SqlSession,通过SqlSession执行一系列数据库操作
- mybatis传递参数
- dao方法有一个简单类型,直接使用#{任意字符}
- 多个参数:使用@Param("xx")指明xml解析的名字
- 使用Java对象,mapper中使用对象的属性
- #和$的区别
- #是占位符,使用PreparedStatement执行sql,效率高
- 表示列的值,一般放在等号右侧使用
- $是字符串连接,使用Statement,效率低,有sql注入的风险
- $一般是替换表名、列名
- mybatis封装sql的执行结果
- 标签中的resultType,指明封装结果的对象,可以使用别名(需要定义,可以复用)
- 标签中的resultMap,指明数据库列名与Java对象属性的对应关系(需要定义,可以复用),或者使用sql语句的as给列取别名
- like:直接使用#{xxx},传递参数给mapper
- 动态sql
- <where>:里面是if,条件满足加入where,并去除多余的and,or等关键字
- <if>:如果条件满足,加入后面的sql语句
- <foreach>:list或array
- mybatis主配置文件:配置项有顺序
- <properties resource=xxx>配置.properties:,使用${}引用
- <settings>中可以配置日志
- <typeAliases>配置别名:<typeAlias>给某个类型,<package>把一个包中的类作为别名(如果有名称相同的类会有冲突)
- <plugins>配置插件
- <environments>配置<dataSource>
- mapper文件的位置:<mapper resource>单个指定,<package name>指定某个包(要求名称与接口名相同,并在同一个包下)
- PageHelper分页插件
- 加入依赖
- 在执行查询前调用PageHelper的静态方法即可
代码
| <?xml version="1.0" encoding="UTF-8"?> |
| <project xmlns="http://maven.apache.org/POM/4.0.0" |
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
| <modelVersion>4.0.0</modelVersion> |
| |
| <groupId>com.bingmous</groupId> |
| <artifactId>mybatis</artifactId> |
| <version>1.0-SNAPSHOT</version> |
| |
| <properties> |
| <maven.compiler.source>11</maven.compiler.source> |
| <maven.compiler.target>11</maven.compiler.target> |
| </properties> |
| <dependencies> |
| |
| <dependency> |
| <groupId>org.mybatis</groupId> |
| <artifactId>mybatis</artifactId> |
| <version>3.5.1</version> |
| </dependency> |
| |
| <dependency> |
| <groupId>org.postgresql</groupId> |
| <artifactId>postgresql</artifactId> |
| <version>42.2.19</version> |
| </dependency> |
| |
| |
| <dependency> |
| <groupId>com.github.pagehelper</groupId> |
| <artifactId>pagehelper</artifactId> |
| <version>5.2.1</version> |
| </dependency> |
| |
| |
| <dependency> |
| <groupId>org.projectlombok</groupId> |
| <artifactId>lombok</artifactId> |
| <version>1.18.20</version> |
| </dependency> |
| <dependency> |
| <groupId>junit</groupId> |
| <artifactId>junit</artifactId> |
| <version>4.13</version> |
| <scope>test</scope> |
| </dependency> |
| </dependencies> |
| |
| <build> |
| |
| <resources> |
| <resource> |
| <directory>src/main/java</directory> |
| <includes> |
| <include>**/*.properties</include> |
| <include>**/*.xml</include> |
| </includes> |
| <filtering>false</filtering> |
| </resource> |
| </resources> |
| </build> |
| |
| </project> |
| <?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"></properties> |
| |
| |
| <settings> |
| <setting name="logImpl" value="STDOUT_LOGGING"/> |
| </settings> |
| |
| |
| |
| |
| |
| |
| <typeAliases> |
| |
| |
| </typeAliases> |
| |
| <plugins> |
| <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> |
| </plugins> |
| |
| <environments default="development"> |
| <environment id="development"> |
| <transactionManager type="JDBC"/> |
| <dataSource type="POOLED"> |
| <property name="driver" value="${jdbc.drive}"/> |
| <property name="url" |
| value="${jdbc.url}"/> |
| <property name="username" value="${jdbc.username}"/> |
| <property name="password" value="${jdbc.password}"/> |
| </dataSource> |
| </environment> |
| </environments> |
| |
| <mappers> |
| <mapper resource="com/bingmous/dao/StudentDao.xml"/> |
| |
| |
| |
| |
| |
| </mappers> |
| </configuration> |
| jdbc.drive=org.postgresql.Driver |
| jdbc.url=jdbc:postgresql://10.194.227.212:5432/zztest |
| jdbc.username=postgres |
| jdbc.password=hik12345+ |
| |
| |
| |
| |
| public interface StudentDao { |
| |
| List<Student> selectStudents(); |
| |
| |
| Student selectStudentById(Integer id); |
| |
| List<Student> selectStudentByNameAndAge(@Param("name") String name, |
| @Param("age") Integer age); |
| |
| List<Student> selectStudentByNameAndAge2(Student student); |
| |
| List<Student> selectStudentLike(String name); |
| |
| int insertStudent(Student student); |
| |
| |
| |
| |
| List<Student> selectDynamicSQL(@Param("age") Integer age); |
| List<Student> selectDynamicSQL2(ArrayList<Student> list); |
| } |
| <?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="com.bingmous.dao.StudentDao"> |
| |
| |
| |
| <resultMap id="studentMap" type="com.bingmous.beans.Student"> |
| <id column="id" property="id"></id> |
| <result column="name" property="name"></result> |
| <result column="email" property="email"></result> |
| <result column="age" property="age"></result> |
| </resultMap> |
| <select id="selectStudents" resultMap="studentMap"> |
| select id, name, email, age from student order by id |
| </select> |
| |
| <select id="selectStudentById" resultType="com.bingmous.beans.Student"> |
| select id, name, email, age from student where id = #{id} |
| </select> |
| |
| <select id="selectStudentByNameAndAge" resultType="com.bingmous.beans.Student"> |
| select id, name, email, age from student where name = #{name} or age = #{age} |
| </select> |
| |
| <select id="selectStudentByNameAndAge2" resultType="com.bingmous.beans.Student"> |
| select id, name, email, age from student where name = #{name} or age = #{age} |
| </select> |
| <select id="selectStudentLike" resultType="com.bingmous.beans.Student"> |
| <include refid="selectFragment"></include> where name like #{name} |
| </select> |
| |
| <insert id="insertStudent"> |
| insert into student(id, name, email, age) |
| values (#{id}, #{name}, #{email}, #{age}) |
| </insert> |
| |
| |
| <select id="selectDynamicSQL" resultType="com.bingmous.beans.Student"> |
| select id, name, email, age from student |
| <where> |
| |
| |
| |
| <if test="age > 0"> |
| or age > 0 |
| </if> |
| </where> |
| </select> |
| <select id="selectDynamicSQL2" resultType="com.bingmous.beans.Student"> |
| <include refid="selectFragment"></include> where id in |
| <foreach collection="list" item="stu" open="(" close=")" separator=","> |
| #{stu.id} |
| </foreach> |
| </select> |
| |
| <sql id="selectFragment"> |
| select id, name, email, age from student |
| </sql> |
| </mapper> |
| |
| |
| |
| public class MybatisUtils { |
| private static SqlSessionFactory factory = null; |
| static { |
| InputStream is = null; |
| try { |
| is = Resources.getResourceAsStream("mybatis.xml"); |
| factory = new SqlSessionFactoryBuilder().build(is); |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| } |
| |
| |
| public static SqlSession getSqlSession(){ |
| if (factory != null) { |
| return factory.openSession(); |
| } |
| return null; |
| } |
| } |
| |
| |
| |
| @Data |
| @AllArgsConstructor |
| @NoArgsConstructor |
| public class Student { |
| private Integer id; |
| private String name; |
| private String email; |
| private Integer age; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| } |
| |
| |
| |
| public class MainApplication { |
| public static void main(String[] args) throws IOException { |
| |
| |
| |
| |
| |
| |
| |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| |
| List<Student> list = sqlSession.selectList("com.bingmous.dao.StudentDao.selectStudents"); |
| list.forEach(System.out::println); |
| |
| sqlSession.close(); |
| } |
| } |
| |
| |
| |
| |
| public class TestMybatis { |
| |
| |
| |
| @Test |
| public void test06Like(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| StudentDao studentDao = sqlSession.getMapper(StudentDao.class); |
| List<Student> students = studentDao.selectStudentLike("%a%"); |
| students.forEach(System.out::println); |
| } |
| |
| |
| |
| |
| @Test |
| public void test05ParameterType(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| StudentDao studentDao = sqlSession.getMapper(StudentDao.class); |
| List<Student> students = studentDao.selectStudentByNameAndAge("aa", 20); |
| |
| |
| |
| |
| |
| students.forEach(System.out::println); |
| } |
| |
| |
| |
| @Test |
| public void test04ParameterType(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| StudentDao studentDao = sqlSession.getMapper(StudentDao.class); |
| Student student = studentDao.selectStudentById(1001); |
| System.out.println(student); |
| } |
| |
| |
| |
| |
| @Test |
| public void test03Mapper(){ |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| StudentDao studentDao = sqlSession.getMapper(StudentDao.class); |
| List<Student> students = studentDao.selectStudents(); |
| students.forEach(System.out::println); |
| } |
| |
| |
| |
| @Test |
| public void test02DaoImpl() { |
| |
| |
| |
| |
| |
| |
| } |
| |
| |
| @Test |
| public void test01() throws IOException { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| } |
| } |
| |
| |
| |
| public class TestDynamicSQL { |
| |
| |
| |
| |
| |
| |
| @Test |
| public void test01() { |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| StudentDao studentDao = sqlSession.getMapper(StudentDao.class); |
| Student student = new Student(); |
| student.setName(""); |
| |
| |
| |
| |
| var student1 = new Student(); |
| student1.setId(1001); |
| var student2 = new Student(); |
| student2.setId(1002); |
| var list = new ArrayList<Student>(); |
| list.add(student1); |
| list.add(student2); |
| List<Student> students = studentDao.selectDynamicSQL2(list); |
| students.forEach(System.out::println); |
| sqlSession.commit(); |
| sqlSession.close(); |
| } |
| } |
| |
| |
| |
| public class TestPageHelper { |
| @Test |
| public void testPageHelper() { |
| SqlSession sqlSession = MybatisUtils.getSqlSession(); |
| StudentDao studentDao = sqlSession.getMapper(StudentDao.class); |
| |
| PageHelper.startPage(2,2); |
| List<Student> students = studentDao.selectStudents(); |
| students.forEach(System.out::println); |
| |
| PageHelper.startPage(3,2); |
| List<Student> students2 = studentDao.selectStudents(); |
| students2.forEach(System.out::println); |
| |
| sqlSession.commit(); |
| sqlSession.close(); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?