SSM学习(一)Mybatis
Mybatis Notes
Mybatis First
創(chuàng)建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,consolejdbc配置文件
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><!--配置數(shù)據(jù)庫環(huán)境--><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;/*** 讀取主配置文件,創(chuàng)建SqlSession,如果SqlSession已經(jīng)存在則直接返回* @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>數(shù)據(jù)庫字段名和實體類屬性名不一致:將數(shù)據(jù)庫的tid、tname、tage、score封裝到Student(id,name,age,score)對象中
mapper動態(tài)代理
一般流程
dao對象調(diào)用dao層接口的實現(xiàn)類 -> sqlSession.insert(映射器id,映射器需要的參數(shù)) -> mapper中對應(yīng)id的sql語句
mapper的動態(tài)代理
new sqlSession -> dao = sqlSession.getMapper(dao層接口.class) -> dao調(diào)用接口
通常dao層接口的實現(xiàn)類里面定義了sqlSession去指定mapper.xml映射文件中的哪一個映射方法。然后mapper的動態(tài)代理要設(shè)置mapper的命名空間,sqlSession.getMapper(dao層接口.class)就相當于指定要找該指定命名空間的映射器??墒怯成湮募锩娑x了那么多select、insert等查詢語句,怎么調(diào)用我要的呢?這個時候就可以直接用dao對象調(diào)用接口,因為接口名和sql語句名是相同的,就可以定位到相應(yīng)的sql語句。看上去好像是dao直接執(zhí)行sql語句一樣。
兩個關(guān)鍵: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
- 索引
動態(tài)SQL
| 替換符號 | < | <= | > | >= | & | ' | " |
if
<select id="selectStudentByCondition" resultType="Student">select * form student<where><if test="name != null and name != ''">and name like '%' #{name} '%'</if><if test="age > 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 > 0">and age > #{age}</when><otherwise>1 = 2</otherwise></choose></where> </select>trim, where, set
foreach
<!--遍歷數(shù)組--> <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>關(guān)聯(lián)關(guān)系查詢
一對多
創(chuàng)建數(shù)據(jù)表和實體類
| 結(jié)構(gòu) | cid、cname | mid、mname、countryid |
| 關(guān)系 | 一 | 多 |
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語句的結(jié)果得到的
<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>多對一
創(chuàng)建數(shù)據(jù)表和實體類
| 結(jié)構(gòu) | cid、cname | mid、mname、country |
| 關(guān)系 | 多 | 一 |
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還可以這樣寫,一個關(guān)聯(lián)的值是從另外一個select語句的結(jié)果得到的
<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>自關(guān)聯(lián)
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注解式開發(fā)(dao層接口)
- @Insert(value="")
- @Delete(value="")
- @Update(value="")
- @Select(value="")
轉(zhuǎn)載于:https://www.cnblogs.com/hextech/p/10657533.html
總結(jié)
以上是生活随笔為你收集整理的SSM学习(一)Mybatis的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第二次学习笔记(linux/unix操作
- 下一篇: Oracle 表的创建 及相关參数