MyBatis中文官網:
http://www.mybatis.cn/java
我使用的工具是idea,jdk是1.8mysql
1.建立一個maven項目 mbs_mavensql
2.引入mybatis的jar包數據庫
1 <dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 <version>5.1.46</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.mybatis</groupId> 9 <artifactId>mybatis</artifactId> 10 <version>3.5.1</version> 11 </dependency>
3.引入log的jar包,mybatis是須要依賴log ,引入junit測試和lobok代碼簡化工具apache
1 <dependency> 2 <groupId>org.projectlombok</groupId> 3 <artifactId>lombok</artifactId> 4 <version>1.18.10</version> 5 </dependency> 6 7 <!-- log start --> 8 <dependency> 9 <groupId>org.slf4j</groupId> 10 <artifactId>slf4j-api</artifactId> 11 <version>${slf4j-api.version}</version> 12 </dependency> 13 <dependency> 14 <groupId>ch.qos.logback</groupId> 15 <artifactId>logback-core</artifactId> 16 <version>${logback.version}</version> 17 </dependency> 18 <dependency> 19 <groupId>ch.qos.logback</groupId> 20 <artifactId>logback-access</artifactId> 21 <version>${logback.version}</version> 22 </dependency> 23 <dependency> 24 <groupId>ch.qos.logback</groupId> 25 <artifactId>logback-classic</artifactId> 26 <version>${logback.version}</version> 27 </dependency> 28 <!-- log end --> 29 30 <dependency> 31 <groupId>junit</groupId> 32 <artifactId>junit</artifactId> 33 <version>4.12</version> 34 </dependency>
1 <properties> 2 <slf4j-api.version>1.7.25</slf4j-api.version> 3 <logback.version>1.1.7</logback.version> 4 </properties>
4.建立logback.xmlapi
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoder 默認配置爲PatternLayoutEncoder --> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <logger name="dao" level="DEBUG"/> <!--本身的dao層--> <logger name="cm.mbs.dao" level="INFO"/> <root level="INFO"> <appender-ref ref="STDOUT"/> </root> </configuration>
5.建立mybatis-config.xmlsession
<?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> <!--使用logback的配置--> <settings> <setting name="logPrefix" value="dao." /> </settings> <!--<settings>--> <!--<!– 指定使用LOG4J輸出日誌 –>--> <!--<setting name="logImpl" value="LOG4J"/>--> <!--</settings>--> <typeAliases> <!-- 配置包的別名,一般在使用類時須要使用類的全限定名稱,使用該配置後只要直接使用類名便可 --> <package name="cm.mbs.entity"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <!-- 在src/main/resources目錄下建立mapper目錄 --> <mapper resource="mapper/UserMapper.xml" /> </mappers> </configuration>
6.建立數據庫表mybatis
/* Navicat Premium Data Transfer Source Server : localhost_3306 Source Server Type : MySQL Source Server Version : 50726 Source Host : localhost:3306 Source Schema : test Target Server Type : MySQL Target Server Version : 50726 File Encoding : 65001 Date: 25/10/2019 09:50:24 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `Id` bigint(20) NOT NULL AUTO_INCREMENT, `UserName` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `Password` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, PRIMARY KEY (`Id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES (1, '張三', '123456'); INSERT INTO `t_user` VALUES (2, '李四', '123456'); SET FOREIGN_KEY_CHECKS = 1;
7.建立實體類app
@Data //這個是lombok的註解,爲每個私有屬性建立get set方法 @NoArgsConstructor //lombok 無參構造器 public class User { private Long id; private String userName; private String password; }
8.建立daomaven
public interface UserMapper { List<User> selectAll(); Integer addUser(User user); Integer updateUser(User user); Integer delUser(Integer id); }
9.建立UserMapper.xml
<?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="cm.mbs.dao.UserMapper"> <select id="selectAll" resultType="User"> select Id,UserName,Password from t_user </select> <insert id="addUser" parameterType="cm.mbs.entity.User" > INSERT INTO t_user (UserName,Password) VALUES ( #{userName}, #{password}) </insert> <update id="updateUser" parameterType="cm.mbs.entity.User"> update t_user set UserName = #{userName} ,Password = #{password} where id = #{id} </update> <delete id="delUser" parameterType="int"> delete from t_user where Id = #{id} </delete> </mapper>
10.編寫測試類
package cm.mbs.dao; import cm.mbs.entity.User; 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 org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Description: example * Created by SMO992079 on 2019/10/22 9:53 */ public class UserMapperTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void init() { InputStream is = null; try { String resource = "mybatis-config.xml"; is = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } @Test public void testSelectAll() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { // List<User> list = sqlSession.selectList("selectAll"); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.selectAll(); for (User user : users) { System.out.println(user.getUserName() + " " + user.getPassword()); } } } @Test public void testAddUser(){ User user = new User("張三","123123213"); try (SqlSession sqlSession = sqlSessionFactory.openSession()) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); Integer integer = mapper.addUser(user); System.out.println(integer); } } @Test public void testUpdateUser(){ User user = new User(1,"張三","123123213"); try (SqlSession sqlSession = sqlSessionFactory.openSession()) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); Integer integer = mapper.updateUser(user); System.out.println(integer); } } @Test public void testDelUser(){ try (SqlSession sqlSession = sqlSessionFactory.openSession()) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); Integer integer = mapper.delUser(1); System.out.println(integer); } } }
11.mybatis的啓動理解
1. 構建sqlSessionFactory (UserMapperTest.java)
// 指定全局配置文件 String resource = "mybatis-config.xml"; // 讀取配置文件 InputStream is = Resources.getResourceAsStream(resource); // 構建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
2. 打開sqlSession對話,並執行sql (UserMapperTest.java)
// 獲取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 操做CRUD,指定statement,規則:命名空間+「.」+statementId List<User> list = sqlSession.selectList("selectAll"); // 這個地方也能夠使用 getMapper來獲取mapper對象例如 UserMapper mapper = sqlSession.getMapper(UserMapper.class); // 執行查詢方法 List<User> users = mapper.selectAll();