在上一個demo【(四)關於Mybatis別名定義】中,咱們實現了基本的插入功能,並解釋了mybatis一些基本的規範。在這裏咱們須要實現單表的增刪改查功能。代碼託管於GitHub上,https://github.com/Damaer/Mybatis-Learning 下面的mybatis-05-CRUD這個項目中,能夠直接跑(前提是Maven環境以及sql環境配好)
首先,項目的目錄以下:
首先,咱們的數據庫mysql,SQL語句以下(也就是resource下的test.sql)html
#建立數據庫 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包:java
4.0.0com.testtest1.0-SNAPSHOTorg.mybatismybatis3.3.0mysqlmysql-connector-java5.1.29junitjunit4.11testlog4jlog4j1.2.17org.slf4jslf4j-api1.7.12org.slf4jslf4j-log4j121.7.12
既然數據庫中有實體類,那咱們也須要實體類Student:mysql
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:git
<?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>
jdbc_mysql.properties文件:github
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.user=root jdbc.password=123456
日誌系統的配置文件 log4j.properties:sql
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
在主配置文件裏咱們配置了去掃描mapper文件,那咱們要實現的是對Student的增刪改查等功能,Mapper.xml:數據庫
insert into student(name,age,score) values(#{name},#{age},#{score}) insert into student(name,age,score) values(#{name},#{age},#{score}) select @@identitydelete from student where id=#{id} update student set name=#{name},age=#{age},score=#{score} where id=#{id} select id,name,age,score from student select * from student where id=#{xxx} select id,name,age,score from student where name like '%${value}%'
有了mapper文件還不夠,咱們須要定義接口與sql語句一一對應,IStudentDao.class:apache
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 ListselectAllStudents(); // 返回全部學生的信息Map public MapselectAllStudentsMap(); // 根據id查找學生 public Student selectStudentById(int id); // 根據名字查找學生,模糊查詢 public ListselectStudentsByName(String name); }
接口的實現類以下:
sqlSession有不少方法,若是是插入一條數據須要使用insert();刪除一條數據使用delete();更新一條數據使用update();若是查詢返回數據的List使用SelectList()方法;若是返回查詢多條數據的Map使用selectMap();若是查詢一條數據,那麼只須要使用selectOne()便可。api
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>(); /** * 能夠寫成Mapmap=new HashMap(); */ 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的實例:session
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的時候建議多跑幾回插入再測試其餘功能。
此文章僅表明本身(本菜鳥)學習積累記錄,或者學習筆記,若有侵權,請聯繫做者刪除。人無完人,文章也同樣,文筆稚嫩,在下不才,勿噴,若是有錯誤之處,還望指出,感激涕零~
技術之路不在一時,山高水長,縱使緩慢,馳而不息。
公衆號:秦懷雜貨店