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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

SSM学习(一)Mybatis

發布時間:2025/3/16 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SSM学习(一)Mybatis 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Mybatis Notes

Mybatis First

創建Maven項目

配置依賴

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>RELEASE</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>RELEASE</version></dependency> </dependencies>

log4j配置

src\main\resources\log4j.properties

log4j.rootLogger=DEBUG log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.Target=System.out log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %m%n log4j.logger.test=debug,console

jdbc配置文件

src\main\resources\jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8 jdbc.name=root jdbc.password=123456

主配置文件

src\main\resources\mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!--導入jdbc配置文件--><properties resource="jdbc.properties" /><!--別名--><typeAliases><!--兩種方式--><!--<typeAlias type="com.hex.model.Student" alias="xxx" />--><package name="com.hex.model" /></typeAliases><!--配置數據庫環境--><environments default="mysql_env"><environment id="mysql_env"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.name}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!--導入sql映射文件--><mappers><mapper resource="mapper.xml"/></mappers> </configuration>

mapper映射文件

src\main\resources\mapper.xml

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hex.model.Student"><!--values里面填的是屬性(setget方法名去掉setget首字母小寫)--><insert id="insertStudent" parameterType="Student">insert into student(name,age,score) values (#{name},#{age},#{score})</insert><delete id="deleteStudentById" parameterType="int">DELETE FROM student WHERE id=#{id}</delete><delete id="deleteStudentByName" parameterType="string">DELETE FROM student WHERE NAME=#{name}</delete><select id="searchStudentById" parameterType="int" resultType="Student">SELECT * FROM student WHERE id=#{id}</select><select id="searchStudentByName" parameterType="string" resultType="Student">SELECT * FROM student WHERE NAME=#{name}</select><select id="modifyStudent" parameterType="Student">UPDATE student SET NAME=#{name},age=#{age},score=#{score} where id=#{id}</select><select id="fuzzyQueryByName" parameterType="string" resultType="Student">SELECT * FROM student WHERE NAME LIKE '%${value}%'</select> </mapper>

實體類

com.hex.model.Student

public class Student {private Integer id;private String name;private int age;private double score;public Student() {}public Student(String name, int age, double score) {this.name = name;this.age = age;this.score = score;}/* 省略set、get方法 */ }

dao層

com.hex.dao.StudentDao

package com.hex.dao; import com.hex.model.Student; import com.hex.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import javax.sound.midi.SoundbankResource; import java.util.ArrayList; import java.util.List; public class StudentDao {private SqlSession sqlSession;public void insertStudent(Student student){try{sqlSession = MybatisUtils.sqlSessionFactory();sqlSession.insert("insertStudent",student);sqlSession.commit();}finally {sqlSession.close();}}public void deleteStudentById(int id){try{sqlSession = MybatisUtils.sqlSessionFactory();sqlSession.delete("deleteStudentById",id);sqlSession.commit();}finally {sqlSession.close();}}public void deleteStudentByName(String name){try{sqlSession = MybatisUtils.sqlSessionFactory();sqlSession.delete("deleteStudentByName",name);sqlSession.commit();}finally {sqlSession.close();}}public List<Student> searchStudentById(int id){List<Student> studentList = new ArrayList<Student>();try{sqlSession = MybatisUtils.sqlSessionFactory();studentList = sqlSession.selectList("searchStudentById",id);}finally {sqlSession.close();return studentList;}}public List<Student> searchStudentByName(String name){List<Student> studentList = new ArrayList<Student>();try{sqlSession = MybatisUtils.sqlSessionFactory();studentList = sqlSession.selectList("searchStudentByName",name);}finally {sqlSession.close();return studentList;}}public void modifyStudent(Student student){try{sqlSession = MybatisUtils.sqlSessionFactory();sqlSession.update("modifyStudent",student);sqlSession.commit();}finally {sqlSession.close();}}public List<Student> fuzzyQueryByName(String word){List<Student> studentList = new ArrayList<Student>();try{sqlSession = MybatisUtils.sqlSessionFactory();studentList = sqlSession.selectList("fuzzyQueryByName",word);}finally {sqlSession.close();return studentList;}} }

工具類

com.hex.utils.MybatisUtils

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; public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;/*** 讀取主配置文件,創建SqlSession,如果SqlSession已經存在則直接返回* @return*/public static SqlSession sqlSessionFactory() {try {InputStream is = Resources.getResourceAsStream("mybatis-config.xml");if (sqlSessionFactory == null) {sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);}return sqlSessionFactory.openSession();} catch (IOException e) {e.printStackTrace();}return null;} }

測試類

com.hex.test.MyTest

import com.hex.dao.StudentDao; import com.hex.model.Student; import org.junit.Test; import java.io.IOException; public class MyTest {private StudentDao dao = new StudentDao();@Testpublic void test() throws IOException {Student student = new Student("hex",23,98.5);dao.insertStudent(student);}/*省略其他測試方法*/ }

單表的CURD操作

sql語句拼接

<select id="fuzzyQueryByName" parameterType="string" resultType="Student">SELECT * FROM student WHERE NAME like '%' #{word} '%' </select> <select id="fuzzyQueryByName" parameterType="string" resultType="Student">SELECT * FROM student WHERE NAME like concat('%',#{word},'%') </select> <!--第3中方法難以避免sql注入問題--> <select id="fuzzyQueryByName" parameterType="string" resultType="Student">SELECT * FROM student WHERE NAME LIKE '%${value}%' </select>

resultMap

<resultMap id="studentMapper" type="Student"><id column="tid" property="id" /><result column="tname" property="name" /> </resultMap> <select id="searchStudentById" resultMap="studentMapper">SELECT tid,tname,tage,score FROM student WHERE id=#{id} </select>

數據庫字段名和實體類屬性名不一致:將數據庫的tid、tname、tage、score封裝到Student(id,name,age,score)對象中

mapper動態代理

一般流程
dao對象調用dao層接口的實現類 -> sqlSession.insert(映射器id,映射器需要的參數) -> mapper中對應id的sql語句
mapper的動態代理
new sqlSession -> dao = sqlSession.getMapper(dao層接口.class) -> dao調用接口

通常dao層接口的實現類里面定義了sqlSession去指定mapper.xml映射文件中的哪一個映射方法。然后mapper的動態代理要設置mapper的命名空間,sqlSession.getMapper(dao層接口.class)就相當于指定要找該指定命名空間的映射器。可是映射文件里面定義了那么多select、insert等查詢語句,怎么調用我要的呢?這個時候就可以直接用dao對象調用接口,因為接口名和sql語句名是相同的,就可以定位到相應的sql語句。看上去好像是dao直接執行sql語句一樣。

兩個關鍵:mapper的命名空間是接口類的全限定類名。接口的方法名和mapper中定義的查詢語句的id要保持一致。

@Test public void mapperDynamicProxy(){SqlSession sqlSession = MybatisUtils.sqlSessionFactory();StudentDao dao = sqlSession.getMapper(StudentDao.class);Student student = dao.selectStudentById(1);System.out.println(student.getName()); }

多條件查詢

  • 把查詢條件封裝成實體類的對象
  • 把查詢條件封裝成Map
  • 索引
#{}中可以放什么內容: 1.參數對象的屬性 2.隨意內容,此時的#{}是個占位符 3.參數為Map時的key 4.參數為Map時key所對應的value為對象,則可將該對象的屬性放入 5.參數的索引號

動態SQL

原符號<<=>>=&'"
替換符號&lt;&lt;=&gt;&gt;=&amp;&apos;&quot;
  • if

    <select id="selectStudentByCondition" resultType="Student">select * form student<where><if test="name != null and name != ''">and name like '%' #{name} '%'</if><if test="age &gt; 0">and age > #{age}</if></where> </select>
  • choose, when, otherwise

    <select id="selectStudentByCondition" resultType="Student">select * form student<where><choose><when test="name != null and name != ''">and name like '%' #{name} '%'</when><when test="age &gt; 0">and age > #{age}</when><otherwise>1 = 2</otherwise></choose></where> </select>
  • trim, where, set

  • foreach

    <!--遍歷數組--> <select id="selectStudentByCondition" resultType="Student">select * form student<if test="array.length > 0">where id in<foreach collection="array" item="myid" open="(" close=")" separator=",">#{myid}</foreach></if> </select> <!--遍歷list--> <select id="selectStudentByCondition" resultType="Student">select * form student<if test="list.size > 0">where id in<foreach collection="list" item="myid" open="(" close=")" separator=",">#{myid}</foreach></if> </select>
  • bind

sql片段

<sql id="selectColumns">id,name,age,score</sql> <select id="selectStudentByCondition" resultType="Student">select <include refid="selectColumns" /> form student </select>

關聯關系查詢

一對多

創建數據表和實體類

countryminister
結構cid、cnamemid、mname、countryid
關系

mapper映射文件

<mapper namespace="com.one2many.dao.CountryDao"><resultMap id="countryMapper" type="Country"><id column="cid" property="cid" /><result column="cname" property="cname"/><collection property="ministers" ofType="Minister"><id column="mid" property="mid"/><result column="mname" property="mname" /></collection></resultMap><select id="selectCountryById" resultMap="countryMapper" parameterType="int">SELECT cid,cname,mid,mname FROM country,minister WHERE cid = countryid and cid = #{id}</select> </mapper>

測試類

@Test public void test01(){SqlSession sqlSession = MybatisUtils.sqlSessionFactory();CountryDao dao = sqlSession.getMapper(CountryDao.class);Country country = dao.selectCountryById(1);System.out.println(country.toString()); }

mapper還可以這樣寫,一個集合的值是從另外一個select語句的結果得到的

<mapper namespace="com.one2many.dao.CountryDao"><select id="selectMinisterByCountry" resultType="Minister">select mid,mname from minister where countryid = #{xxx}</select><resultMap id="countryMapper" type="Country"><id column="cid" property="cid" /><result column="cname" property="cname"/><collection property="ministers"ofType="Minister"select="selectMinisterByCountry"column="cid"/></resultMap><select id="selectCountryById" resultMap="countryMapper" parameterType="int">SELECT cid,cname,mid,mname FROM country,minister WHERE cid = countryid and cid = #{id}</select> </mapper>

多對一

創建數據表和實體類

countryminister
結構cid、cnamemid、mname、country
關系

mapper映射文件

<mapper namespace="com.many2one.dao.MinisterDao"><resultMap id="ministerMapper" type="Minister"><id column="mid" property="mid" /><result column="mname" property="mname" /><association property="country" javaType="Country"><!--property映射成javaType--><id column="cid" property="cid" /><result column="cname" property="cname" /></association></resultMap><select id="selectMinisterById" resultMap="ministerMapper">SELECT MID,mname,cid,cname FROM minister,countryWHERE countryid = cid AND MID = #{xxx}</select> </mapper>

測試類

@Test public void test01(){SqlSession sqlSession = MybatisUtils.sqlSessionFactory();MinisterDao dao = sqlSession.getMapper(MinisterDao.class);Minister minister = dao.selectMinisterById(2);System.out.println(minister.toString()); }

mapper還可以這樣寫,一個關聯的值是從另外一個select語句的結果得到的

<mapper namespace="com.many2one.dao.MinisterDao"><select id="selectCountryById" resultType="Country">select cid,cname FROM country where cid=#{xxx}</select><resultMap id="ministerMapper" type="Minister"><id column="mid" property="mid" /><result column="mname" property="mname" /><association property="country"javaType="Country"select="selectCountryById" column="countryid"></association></resultMap><select id="selectMinisterById" resultMap="ministerMapper">SELECT MID,mname,countryid FROM minister WHERE MID = #{xxx}</select> </mapper>

自關聯

NewsLabel模型

public class NewsLabel {private int id;private String name;private Set<NewsLabel> children;/*省略set、get、toString方法*/ } <mapper namespace="com.hex.dao.NewsLabelDao"><resultMap id="newslabelMapper" type="NewsLabel"><id column="id" property="id" /><result column="name" property="name"/><collection property="children"ofType="NewsLabel"select="selectChildrenByParent"column="id" /></resultMap><select id="selectChildrenByParent" resultMap="newslabelMapper">select id,name FROM newslabel where pid=#{xxx}</select> </mapper> @Test public void test01(){SqlSession sqlSession = MybatisUtils.sqlSessionFactory();NewsLabelDao dao = sqlSession.getMapper(NewsLabelDao.class);List<NewsLabel> list = dao.selectChildrenByParent(2);for (NewsLabel li:list) {System.out.println(li.toString());} }

多對多

延遲加載

<settings><setting name="lazyLoadingEnable" value="false" /><setting name="aggressiveLazyLoading" value="false" /> </settings>

查詢緩存

一級緩存、二級緩存

ehcache

  • 導包

    <dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId><version>2.8.3</version> </dependency> <dependency><groupId>org.mybatis</groupId><artifactId>mybatis-ehcache</artifactId><version>1.0.0</version> </dependency>
  • 引入ehcache類
    xml <mapper> <cache type="org.mybatis.caches.ehcache.EhcacheCache" /> </mapper>

  • 導入配置文件

    把ehcache-core里面的配置文件導入項目

Mybatis注解式開發(dao層接口)

  • @Insert(value="")
  • @Delete(value="")
  • @Update(value="")
  • @Select(value="")
<mapper><!--映射文件所在的包--><package name="com.hex.dao" /> </mapper>

轉載于:https://www.cnblogs.com/hextech/p/10657533.html

總結

以上是生活随笔為你收集整理的SSM学习(一)Mybatis的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。