前面咱們學會了Mybatis
如何配置數據庫以及建立SqlSession
,那怎麼寫呢?crud怎麼寫?java
代碼直接放在Github倉庫【 https://github.com/Damaer/Myb... 】
須要聲明的是:此Mybatis
學習筆記,是從原始的Mybatis
開始的,而不是整合了其餘框架(好比Spring
)以後,我的認爲,這樣能對它的功能,它能幫咱們作什麼,有更好的理解,後面再慢慢疊加其餘的功能。
項目的目錄以下:
mysql
建立數據庫:初始化數據,SQL語句以下(也就是resource
下的test.sql
)git
#建立數據庫 CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; #建立數據表 CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL , `age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM;
使用maven
管理項目,pom.xml
文件管理依賴jar
包:github
<?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.test</groupId> <artifactId>test</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- junit測試包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 日誌文件管理包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> </dependencies> </project>
與數據庫中相對應的實體類Student
:sql
package bean; 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) { super(); this.name = name; this.age = age; this.score = score; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]"; } }
使用mybatis
的重要一步是配置數據源,要不怎麼知道使用哪個數據庫,有哪些mapper文件,主配置文件 mybatis.xml
:數據庫
<?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_mysql.properties"> </properties> <!-- 別名,對數據對象操做全名太長,須要使用別名 --> <typeAliases> <!--<typeAlias type="bean.Student" alias="Student"/>--> <!--直接使用類名便可,對於整個包的路徑配置(別名),簡單快捷 --> <package name="bean"/> </typeAliases> <!-- 配置運行環境 --> <!-- default 表示默認使用哪個環境,能夠配置多個,好比開發時的測試環境,上線後的正式環境等 --> <environments default="mysqlEM"> <environment id="mysqlEM"> <transactionManager type="JDBC"> </transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 註冊映射文件 --> <mappers> <mapper resource="mapper/mapper.xml"/> </mappers> </configuration>
mybatis.xml
文件裏面抽取出來的數據庫鏈接相關信息jdbc_mysql.properties
文件:apache
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.user=root jdbc.password=123456
日誌系統的配置文件 log4j.properties
:api
log4j.prpp log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n #log4j.appender.R=org.apache.log4j.DailyRollingFileAppender #log4j.appender.R.File=../logs/service.log #log4j.appender.R.layout=org.apache.log4j.PatternLayout #log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n #log4j.logger.com.ibatis = debug #log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug #log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug #log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug #log4j.logger.java.sql.Connection = debug log4j.logger.java.sql.Statement = debug log4j.logger.java.sql.PreparedStatement = debug log4j.logger.java.sql.ResultSet =debug
在主配置文件mybatis.xml
裏咱們配置了去掃描mapper
文件,那咱們要實現的是對Student
的增刪改查等功能,Mapper.xml
:session
<?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="abc"> <!-- parameterType能夠省略不寫 --> <insert id="insertStudent" parameterType="Student"> insert into student(name,age,score) values(#{name},#{age},#{score}) </insert> <insert id="insertStudentCacheId" parameterType="Student"> insert into student(name,age,score) values(#{name},#{age},#{score}) <!-- 指定結果類型resultType,keyProperty是屬性,自動返回到屬性id中,order是次序,after是指獲取id是在於插入後 --> <selectKey resultType="int" keyProperty="id" order="AFTER"> select @@identity </selectKey> </insert> <!-- 刪除 --> <delete id="deleteStudentById" > delete from student where id=#{id} <!-- 這裏的id放什麼均可以,只是一個佔位符,不表示什麼 --> </delete> <update id="updateStudent"> update student set name=#{name},age=#{age},score=#{score} where id=#{id} </update> <!-- 查詢列表 --> <!-- 系統不知道返回封裝爲何類型,因此要註明返回類型 --> <select id="selectAllStudents" resultType="Student"> select id,name,age,score from student <!-- 若是數據庫爲tid,tname,tage,那麼咱們可使用別名 select tid id,tname name,tage age,tscore score from student --> </select> <!-- 經過id來查詢學生 --> <select id="selectStudentById" resultType="Student"> select * from student where id=#{xxx} </select> <!-- 模糊查詢--> <!-- 不能寫成'%#{name}%' --> <!-- 能夠寫成這樣,也就是使函數拼接 select id,name,age,score from student where name like concat('%',#{xxx},'%') --> <!-- 也能夠寫成這樣,‘’引發來的是寫死的,而變量是不能夠引發來的select id,name,age,score from student where name like '%' #{xxx} '%' --> <!-- '%' #{xxx} '%'中間必須有空格,要不就無效了 --> <select id="selectStudentsByName" resultType="Student"> <!--最經常使用的(動態參數) select id,name,age,score from student where name like '%' #{name} '%' --> <!-- 下面的是字符串拼接 ,只能寫value,瞭解便可,容易sql注入,執行效率低,不建議使用--> select id,name,age,score from student where name like '%${value}%' </select> </mapper>
有了mapper.xml
文件還不夠,咱們須要定義接口與sql
語句一一對應,IStudentDao.class
:mybatis
package dao; import bean.Student; import java.util.List; import java.util.Map; public interface IStudentDao { // 增長學生 public void insertStudent(Student student); // 增長新學生並返回id public void insertStudentCacheId(Student student); // 根據id刪除學生 public void deleteStudentById(int id); // 更新學生的信息 public void updateStudent(Student student); // 返回全部學生的信息List public List<Student> selectAllStudents(); // 返回全部學生的信息Map public Map<String, Object> selectAllStudentsMap(); // 根據id查找學生 public Student selectStudentById(int id); // 根據名字查找學生,模糊查詢 public List<Student>selectStudentsByName(String name); }
接口的實現類以下:sqlSession
有不少方法:
insert()
;delete()
;update()
;List
使用SelectList()
方法;Map
使用selectMap()
;selectOne()
便可。package dao; import bean.Student; import org.apache.ibatis.session.SqlSession; import utils.MyBatisUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class StudentDaoImpl implements IStudentDao { private SqlSession sqlSession; public void insertStudent(Student student) { //加載主配置文件 try { sqlSession = MyBatisUtils.getSqlSession(); sqlSession.insert("insertStudent", student); sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } } public void insertStudentCacheId(Student student) { try { sqlSession = MyBatisUtils.getSqlSession(); sqlSession.insert("insertStudentCacheId", student); sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } } public void deleteStudentById(int id) { try { sqlSession = MyBatisUtils.getSqlSession(); sqlSession.delete("deleteStudentById", id); sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } } public void updateStudent(Student student) { try { sqlSession = MyBatisUtils.getSqlSession(); sqlSession.update("updateStudent", student); sqlSession.commit(); } finally { if (sqlSession != null) { sqlSession.close(); } } } public List<Student> selectAllStudents() { List<Student> students ; try { sqlSession = MyBatisUtils.getSqlSession(); students = sqlSession.selectList("selectAllStudents"); //查詢不用修改,因此不用提交事務 } finally { if (sqlSession != null) { sqlSession.close(); } } return students; } public Map<String, Object> selectAllStudentsMap() { Map<String ,Object> map=new HashMap<String, Object>(); /** * 能夠寫成Map<String ,Student> map=new HashMap<String, Student>(); */ try { sqlSession=MyBatisUtils.getSqlSession(); map=sqlSession.selectMap("selectAllStudents", "name"); //查詢不用修改,因此不用提交事務 } finally{ if(sqlSession!=null){ sqlSession.close(); } } return map; } public Student selectStudentById(int id) { Student student=null; try { sqlSession=MyBatisUtils.getSqlSession(); student=sqlSession.selectOne("selectStudentById",id); sqlSession.commit(); } finally{ if(sqlSession!=null){ sqlSession.close(); } } return student; } public List<Student> selectStudentsByName(String name) { List<Student>students=new ArrayList<Student>(); try { sqlSession=MyBatisUtils.getSqlSession(); students=sqlSession.selectList("selectStudentsByName",name); //查詢不用修改,因此不用提交事務 } finally{ if(sqlSession!=null){ sqlSession.close(); } } return students; } }
咱們使用了一個本身定義的工具類,用來獲取Sqlsession
的實例:
package utils; 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 { static private SqlSessionFactory sqlSessionFactory; static public SqlSession getSqlSession() { InputStream is; try { is = Resources.getResourceAsStream("mybatis.xml"); if (sqlSessionFactory == null) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } return sqlSessionFactory.openSession(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
測試代碼MyTest.class
:
import bean.Student; import dao.IStudentDao; import dao.StudentDaoImpl; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Map; public class MyTest { private IStudentDao dao; @Before public void Before(){ dao=new StudentDaoImpl(); } /** * 插入測試 */ @Test public void testInsert(){ /** * 要是沒有select id,這樣是不會自動獲取id的,id會一直爲空 */ Student student=new Student("hello",14,94.6); System.out.println("插入前:student="+student); dao.insertStudent(student); System.out.println("插入後:student="+student); } /** * 測試插入後獲取id */ @Test public void testinsertStudentCacheId(){ Student student=new Student("helloworld",17,85); System.out.println("插入前:student="+student); dao.insertStudentCacheId(student); System.out.println("插入後:student="+student); } /* * 測試刪除 * */ @Test public void testdeleteStudentById(){ dao.deleteStudentById(18); } /* * 測試修改,通常咱們業務裏面不這樣寫,通常是查詢出來student再修改 * */ @Test public void testUpdate(){ Student student=new Student("lallalalla",14,94.6); student.setId(21); dao.updateStudent(student); } /* * 查詢列表 * */ @Test public void testselectList(){ List<Student> students=dao.selectAllStudents(); if(students.size()>0){ for(Student student:students){ System.out.println(student); } } } /* * 查詢列表裝成map * */ @Test public void testselectMap(){ Map<String,Object> students=dao.selectAllStudentsMap(); // 有相同的名字的會直接替換掉以前查出來的,由於是同一個key System.out.println(students.get("helloworld")); System.out.println(students.get("1ADAS")); } /* * 經過id來查詢student * */ @Test public void testselectStudentById(){ Student student=dao.selectStudentById(19); System.out.println(student); } /* * 經過模糊查詢student的名字 * */ @Test public void testselectStudentByName(){ List<Student>students=dao.selectStudentsByName("abc"); if(students.size()>0){ for(Student student:students) System.out.println(student); } } }
至此這個demo就完成了,運行test的時候建議多跑幾回插入再測其餘功能。
從上面的代碼咱們能夠看出Mybatis整體運行的邏輯:
mybatis.xml
文件,而後解析文件,獲取數據庫鏈接信息,存起來。mybatis.xml
裏面配置的mapper.xml
文件。mapper.xml
文件的時候,,將sql
按照namespace
和id
存起來。sqlSessionFactory
工廠,sqlSessionFactory
又能夠獲取到openSession
,至關於獲取到數據庫會話。SqlSession
的insert()
,update()
,delete()
等方法,裏面傳入id
和參數,就能夠查找到剛剛掃描mapper.xml
文件時存起來的sql,去執行sql。
【做者簡介】:
秦懷,公衆號【秦懷雜貨店】做者,技術之路不在一時,山高水長,縱使緩慢,馳而不息。這個世界但願一切都很快,更快,可是我但願本身能走好每一步,寫好每一篇文章,期待和大家一塊兒交流。
此文章僅表明本身(本菜鳥)學習積累記錄,或者學習筆記,若有侵權,請聯繫做者覈實刪除。人無完人,文章也同樣,文筆稚嫩,在下不才,勿噴,若是有錯誤之處,還望指出,感激涕零~