MyBatis學習總結
阿新 • • 發佈:2020-10-11
1 什麼是mybatis?
-
MyBatis 是一款優秀的持久層框架
-
MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集的過程
-
MyBatis 可以使用簡單的 XML 或註解來配置和對映原生資訊,將介面和 Java 的 實體類 【Plain Old Java Objects,普通的 Java物件】對映成資料庫中的記錄。
- Mybatis官方文件 : http://www.mybatis.org/mybatis-3/zh/index.html
2 mybatis的第一個程式
2.1搭建環境
2.1.1 專案結構
2.1.2 pom檔案新增依賴
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> <!--MySQL驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--日誌--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--實體類偷懶--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> </dependencies>
<build> <!--引入配置檔案--> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
2.1.3編寫MyBatis核心配置檔案
2.1.3.1mybatis-config.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="db.properties"> <!-- <property name="username" value="root"/>--> </properties> <settings> <!--標準日誌工廠--> <!-- <setting name="logImpl" value="STDOUT_LOGGING"/>--> <setting name="logImpl" value="LOG4J"/> </settings> <!--實體類起別名--> <typeAliases> <package name="bean"/> <!-- <typeAlias type="com.bean.User" alias="User"></typeAlias>--> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- 使用相對於類路徑的資源引用 --> <mappers> <mapper resource="dao/UserMapper.xml"/> </mappers> </configuration>
2.1.3.2db.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=123456
2.1.3.3 log4j-properties
#將等級為DEBUG的日誌資訊輸出到console和file這兩個目的地,console和file的定義在下面的程式碼
log4j.rootLogger=DEBUG,console,file
#控制檯輸出的相關設定
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#檔案輸出的相關設定
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/log.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日誌輸出級別
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
2.1.4編寫MyBatis工具類 MyBatisUtils.java
package util; 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; /** * @author MoooJL * @data 2020/9/22-20:42 */ public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } }
2.2 編寫程式碼
2.2.1 建立實體類
public class User { private int id; //id private String name; //姓名 private String pwd; //密碼 //構造,有參,無參 //set/get //toString() }
2.2.3 編寫mapper介面類
public interface UserMapper { //查詢全部使用者 List<User> selectUser(); //根據id查詢使用者 User selectUserById(int id); //新增一個使用者 int addUser(User user); //修改一個使用者 int updateUser(User user); //根據id刪除使用者 int deleteUser(int id); }
2.2.4 在UserMapper.xml檔案插入相關SQL語句 附模糊查詢格式
<?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="dao.UserMapper"> <select id="selectUser" resultType="user"> select * from mybatis.user </select> <select id="selectUserById" resultType="user" parameterType="int"> select * from mybatis.user where id=#{id} </select> <insert id="addUser" parameterType="user"> insert into mybatis.user (name,password) values(#{name},#{password}) </insert> <update id="updateUser" parameterType="user"> update mybatis.user set name=#{name} ,password=#{password} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from mybatis.user where id=#{id} </delete> </mapper>
<select id=”selectlike”> select * from user where bar like "%"#{value}"%" </select>
2.2.5 編寫測試程式碼
@Test public void tsetSelectUserById() { SqlSession session = MybatisUtils.getSession(); //獲取SqlSession連線 UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.selectUserById(1); System.out.println(user); session.close(); } @Test public void testAddUser() { SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = new User(5,"王五","zxcvbn"); int i = mapper.addUser(user); System.out.println(i); session.commit(); //提交事務,重點!不寫的話不會提交到資料庫 session.close(); } @Test public void testUpdateUser() { SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.selectUserById(1); user.setPwd("asdfgh"); int i = mapper.updateUser(user); System.out.println(i); session.commit(); //提交事務,重點!不寫的話不會提交到資料庫 session.close(); } @Test public void testDeleteUser() { SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); int i = mapper.deleteUser(5); System.out.println(i); session.commit(); //提交事務,重點!不寫的話不會提交到資料庫 session.close(); }
2.3 總結
-
所有的增刪改操作都需要提交事務!
-
介面所有的普通引數,儘量都寫上@Param引數,尤其是多個引數時,必須寫上!
-
有時候根據業務的需求,可以考慮使用map傳遞引數!
-
為了規範操作,在SQL的配置檔案中,我們儘量將Parameter引數和resultType都寫上!