日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

Mybatis的CRUD之XML方式以及动态SQL

發(fā)布時(shí)間:2024/4/15 asp.net 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Mybatis的CRUD之XML方式以及动态SQL 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

MyBatis 接口代理方式實(shí)現(xiàn) Dao 層

  • 傳統(tǒng)方式實(shí)現(xiàn) Dao 層,我們既要寫接口,還要寫實(shí)現(xiàn)類。而 MyBatis 框架可以幫助我們省略編寫 Dao 層接口實(shí)現(xiàn)類的步驟。程序員只需要編寫接口,由 MyBatis 框架根據(jù)接口的定義來創(chuàng)建該接口的動(dòng)態(tài)代理對象。

實(shí)現(xiàn)規(guī)則

  • 映射配置文件中的名稱空間必須和 Dao 層接口的全類名相同。
  • 映射配置文件中的增刪改查標(biāo)簽的 id 屬性必須和 Dao 層接口的方法名相同。
  • 映射配置文件中的增刪改查標(biāo)簽的 parameterType 屬性必須和 Dao 層接口方法的參數(shù)相同。
  • 映射配置文件中的增刪改查標(biāo)簽的 resultType 屬性必須和 Dao 層接口方法的返回值相同。
  • 獲取動(dòng)態(tài)代理對象
    SqlSession 功能類中的 getMapper() 方法。

    MyBatis 映射配置文件 - 動(dòng)態(tài) SQL

    1.動(dòng)態(tài) SQL 指的就是 SQL 語句可以根據(jù)條件或者參數(shù)的不同進(jìn)行動(dòng)態(tài)的變化。
    <where>:條件標(biāo)簽。
    <if>:條件判斷的標(biāo)簽。
    <foreach>:循環(huán)遍歷的標(biāo)簽。
    2.我們可以將一些重復(fù)性的 SQL 語句進(jìn)行抽取,以達(dá)到復(fù)用的效果。
    <sql>:抽取 SQL 片段的標(biāo)簽。
    <include>:引入 SQL 片段的標(biāo)簽。

    數(shù)據(jù)準(zhǔn)備

    SQL

    創(chuàng)建學(xué)生信息表

    -- 創(chuàng)建學(xué)生表 CREATE TABLE student(sid INT PRIMARY KEY AUTO_INCREMENT,`name` VARCHAR(20),age INT );-- 添加信息 INSERT INTO student VALUES (NULL,'小付',25),(NULL,'小花花',18),(NULL,'李四',24);

    準(zhǔn)備項(xiàng)目

    使用maven創(chuàng)建項(xiàng)目

    pom.xml

    <?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.fs</groupId><artifactId>MyBatis_day02_01</artifactId><version>1.0-SNAPSHOT</version><dependencies> <!-- MyBatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency> <!-- mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency> <!-- log4j日志記錄,可以在控制臺(tái)輸出sql語句方便我們查錯(cuò)--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency> <!-- junit測試--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency> <!-- lombok在實(shí)體類上注解@Data可以自動(dòng)幫我們添加getset方法等--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.20</version></dependency></dependencies> </project>

    dao 接口

    package com.fs.dao;import com.fs.entity.Student;import java.util.List; /* dao模擬*/ public interface StudentMapper {//查詢所有學(xué)生信息List<Student> findAll();//更新學(xué)生信息int updateStudent(Student student);//多條件查詢學(xué)生信息List<Student> selectCondition(Student student);//根據(jù)多個(gè)id查詢學(xué)生信息List<Student> selectByIds(List<Integer> ids);//根據(jù)姓名查詢學(xué)生Student findStudentByName(String name); }

    Student實(shí)體類

    package com.fs.entity;import lombok.Data;@Data //這個(gè)注解是lombok包下的,可以自動(dòng)幫我們添加getset方法等 public class Student {private Integer sid;private String name;private Integer age; }

    service 業(yè)務(wù)層

    package com.fs.service;import com.fs.entity.Student;import java.util.List; /* Service層接口,模擬業(yè)務(wù)層*/ public interface StudentService {//下面的抽象方法與dao一樣List<Student> findAll();int updateStudent(Student student);List<Student> selectCondition(Student student);List<Student> selectByIds(List<Integer> ids);Student findStudentByName(String name); }

    業(yè)務(wù)層實(shí)現(xiàn)類

    package com.fs.service.impl;import com.fs.dao.StudentMapper; import com.fs.entity.Student; import com.fs.service.StudentService; 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.IOException; import java.io.InputStream; import java.util.List;public class StudentServiceImpl implements StudentService {//聲明Dao接口private StudentMapper studentMapper;//構(gòu)造方法通過SqlSession的getMapper(接口的字節(jié)碼)生成studentMapper代理類public StudentServiceImpl() {try {//加載配置文件InputStream rs = Resources.getResourceAsStream("MyBatisConfig.xml");//獲取工廠建造類SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();//獲取工廠對象SqlSessionFactory build = sqlSessionFactoryBuilder.build(rs);//獲取SqlSession對象SqlSession sqlSession = build.openSession(true);//得到代理對象studentMapper = sqlSession.getMapper(StudentMapper.class);} catch (IOException e) {e.printStackTrace();}}/*調(diào)用dao方法實(shí)現(xiàn)功能*/@Overridepublic List<Student> findAll() {return studentMapper.findAll();}@Overridepublic int updateStudent(Student student) {return studentMapper.updateStudent(student);}@Overridepublic List<Student> selectCondition(Student student) {return studentMapper.selectCondition(student);}@Overridepublic List<Student> selectByIds(List<Integer> ids) {return studentMapper.selectByIds(ids);}@Overridepublic Student findStudentByName(String name) {return studentMapper.findStudentByName(name);}}

    配置文件

    數(shù)據(jù)庫連接信息配置文件 jdbc.properties

    driver=com.mysql.jdbc.Driver url=jdbc:mysql://mysql服務(wù)器的ip地址:3306/創(chuàng)建student的庫 username=root password=root

    log4j日志記錄配置文件 log4j.properties

    # Global logging configuration # ERROR WARN INFO DEBUG log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

    MyBatis核心配置文件 MyBatisConfig.xml

    <?xml version="1.0" encoding="UTF-8" ?> <!--MyBatis的DTD約束--> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><!--configuration 核心根標(biāo)簽--> <configuration><!--引入數(shù)據(jù)庫連接的配置文件--><properties resource="jdbc.properties"/><!--配置LOG4J--><settings><setting name="logImpl" value="log4j"/></settings><!--起別名--><typeAliases><!-- 給一個(gè)類起別名--><!-- <typeAlias type="com.fs.entity.Student" alias="student"/>--><!-- 給一個(gè)包下的類起別名,別名為類名的首字母小寫--><package name="com.fs.entity"/></typeAliases><!--environments配置數(shù)據(jù)庫環(huán)境,環(huán)境可以有多個(gè)。default屬性指定使用的是哪個(gè)--><environments default="mysql"><!--environment配置數(shù)據(jù)庫環(huán)境 id屬性唯一標(biāo)識(shí)--><environment id="mysql"><!-- transactionManager事務(wù)管理。 type屬性,采用JDBC默認(rèn)的事務(wù)--><transactionManager type="JDBC"></transactionManager><!-- dataSource數(shù)據(jù)源信息 type屬性 連接池--><dataSource type="POOLED"><!-- property獲取數(shù)據(jù)庫連接的配置信息 --><property name="driver" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${username}" /><property name="password" value="${password}" /></dataSource></environment></environments><!-- mappers引入映射配置文件 --><mappers><!-- mapper 引入指定的映射配置文件 resource屬性指定映射配置文件的名稱 --><mapper resource="StudentMapper.xml"/></mappers> </configuration>

    mapper映射配置文件,詳細(xì)的介紹了動(dòng)態(tài)sql常用的where標(biāo)簽if,foreach標(biāo)簽的使用
    在映射配置文件中,MDL我只寫了update,而insert,delete這兩個(gè)和update沒有任何區(qū)別,甚至標(biāo)簽體都可以混用,我們知道就好,但是實(shí)際開發(fā)還是什么需求用什么標(biāo)簽

    <?xml version="1.0" encoding="UTF-8" ?> <!--MyBatis的DTD約束--> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace:dao接口的全限定名--> <mapper namespace="com.fs.dao.StudentMapper"> <!-- 定義sql語句片段--><sql id="select">select <include refid="fields"></include> from</sql> <!-- 將字段抽取出來,因?yàn)?span id="ozvdkddzhkzd" class="token operator">*會(huì)影響sql查詢的速度--><sql id="fields">sid,name,age</sql><!-- 測試 用include標(biāo)簽來引用sql片段 select sid,name,age from student --><select id="findAll" resultType="student"><include refid="select"></include> student</select><!-- 根據(jù)name查找學(xué)生--><select id="findStudentByName" resultType="student">select * from student where name = #{name}</select><!-- 根據(jù)sid跟新學(xué)生對象--><update id="updateStudent">update student set name = #{name},age = #{age} where sid = #{sid}</update><!-- 動(dòng)態(tài)sql--><select id="selectCondition" resultType="student"> <!-- where 標(biāo)簽的作用就是,自動(dòng)添加where關(guān)鍵字,會(huì)自動(dòng)將多余的and去掉-->select * from student<where><if test="sid != null">sid = #{sid}</if><if test="name != null">and name = #{name}</if><if test="age != null">and age = #{age}</if></where></select> <!-- foreach標(biāo)簽 --><select id="selectByIds" resultType="student" parameterType="list">select * from student<!--Collection:指定遍歷的對象open:遍歷開始拼接的字符串close:遍歷結(jié)束后的字符串拼接separator:每次拼接的分隔符item:遍歷得到的結(jié)果名注意,如果傳入的集合為空,就不會(huì)進(jìn)行任何字符串拼接,包括open close--><where><foreach collection="list" open="sid in(" separator="," close=")" item="sid">#{sid}</foreach></where></select></mapper>

    測試類模擬controller層,控制臺(tái)展示

    package com.fs.dao;import com.fs.entity.Student; import com.fs.service.impl.StudentServiceImpl; import org.junit.Test;import java.util.ArrayList; import java.util.List;public class StudentMapperTest {/*** 測試查詢所有*/@Testpublic void testFindAll() {StudentServiceImpl studentService = new StudentServiceImpl();List<Student> all = studentService.findAll();for (Student student : all) {System.out.println(student);}}/*** 更新學(xué)生信息*/@Testpublic void testUpdate() {StudentServiceImpl studentService = new StudentServiceImpl();Student student1 = new Student();student1.setAge(24);student1.setName("張三");student1.setSid(3);int i = studentService.updateStudent(student1);System.out.println("更新了:"+i+"條學(xué)生信息");}/*** 根據(jù)多條件查詢學(xué)生信息*/@Testpublic void selectCondition() {StudentServiceImpl studentService = new StudentServiceImpl();Student student1 = new Student();student1.setAge(24);student1.setName("李四"); // student1.setSid(3);List<Student> stu = studentService.selectCondition(student1);for (Student student : stu) {System.out.println(student);}}/*** 根據(jù)多個(gè)id查詢*/@Testpublic void selectByIds() {StudentServiceImpl studentService = new StudentServiceImpl();ArrayList<Integer> integers = new ArrayList<>();integers.add(1);integers.add(2);integers.add(3);List<Student> students = studentService.selectByIds(integers);for (Student student : students) {System.out.println(student);}}/*根據(jù)名字查詢學(xué)生信息*/@Testpublic void findStudentByName() {StudentServiceImpl studentService = new StudentServiceImpl();Student xh = studentService.findStudentByName("小花花");System.out.println(xh);} }

    總結(jié)

    以上是生活随笔為你收集整理的Mybatis的CRUD之XML方式以及动态SQL的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。