前提是MyBatis環境部署好了,參考地址:
https://www.cnblogs.com/package-java/p/10316536.html
為了方便演示,我提前在數據庫插入了數據方便查詢
1. 創建新的數據庫`tedu_ums`;
CREATE DATABASE tedu_ums;
2. 在新數據庫中創建數據表`t_user`,表中至少包含id, username, password, age, phone, email這6個屬性;
USE tedu_ums;
CREATE TABLE t_user (
id INT AUTO_INCREMENT,
username VARCHAR(20) UNIQUE NOT NULL,
password VARCHAR(20) NOT NULL,
age INT,
phone VARCHAR(20),
email VARCHAR(50),
PRIMARY KEY(id)
) DEFAULT CHARSET=utf8;
3. 添加不少於10條數據;
INSERT INTO t_user
(username, password, age, phone, email)
VALUES
('root', '1234', 18, '13800138001', 'root@tedu.cn'),
('admin', '4567', 19, '13800138002', 'admin@tedu.cn'),
('jack', '1234', 20, '13800138003', 'jack@tedu.cn'),
('tom', '1234', 22, '13800138010', 'tom@tedu.cn'),
('jerry', '1234', 25, '13800138011', 'jerry@tedu.cn'),
('rose', '1234', 21, '13800138004', 'rose@tedu.cn'),
('mike', '1234', 22, '13800138005', 'mike@tedu.cn'),
('lily', '1234', 23, '13800138006', 'lily@tedu.cn'),
('lucy', '1234', 24, '13800138007', 'lucy@tedu.cn'),
('mary', '1234', 25, '13800138008', 'mary@tedu.cn'),
('alex', '1234', 26, '13800138009', 'alex@tedu.cn');
4. 查詢所有數據;
SELECT id,username,password,age,phone,email FROM t_user;
一、創建實體類
每張數據表都應該有1個對應的實體類,所以,創建`cn.tedu.mybatis.entity.User`類,屬性的數量與類型請參考數據表的設計:
package cn.tedu.mybatis.entity; public class User { private Integer id; private String username; private String password; private Integer age; private String phone; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + ", phone=" + phone + ", email=" + email + "]"; } }
二、創建接口,聲明抽象方法
創建`cn.tedu.mybatis.mapper.UserMapper`接口,並在接口中聲明“插入用戶數據”的抽象方法:
package cn.tedu.mybatis.mapper; import cn.tedu.mybatis.entity.User; public interface UserMapper { Integer addnew(User user);//增 User findById(Integer id);//查 Integer updatenew(User user);//改 Integer deletenew(Integer id);//刪 }
關於抽象方法,在MyBatis中,執行的操作如果是增、刪、改,返回值均使用`Integer`,表示受影響的行數;方法的名稱可以自定義,只要不違反Java的命名規則即可,另外,不允許在接口中使用重載機制;參數也可以自定義,如果執行的是增加操作,參數應該是與數據表對應的實體類的類型。
三、配置接口所在的包並配置配置XML文件的位置與數據源
1、在MyBatis中,通過`MapperScannerConfigurer`類掃描持久層接口的,所以,應該在`spring-dao.xml`文件中進行配置:
2、MyBatis通過`SqlSessionFactoryBean`獲取數據源,並且掃描配置了SQL語句的XML文件,最終由MyBatis框架來執行SQL語句,所以,需要在`spring-dao.xml`中配置`SqlSessionFactoryBean`:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 加載數據庫的配置文件 --> <util:properties id="dbConfig" location="classpath:db.properties"></util:properties> <!-- 配置數據源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="#{dbConfig.url}"></property> <property name="driverClassName" value="#{dbConfig.driver}"></property> <property name="username" value="#{dbConfig.username}"></property> <property name="password" value="#{dbConfig.password}"></property> <property name="initialSize" value="#{dbConfig.initialSize}"></property> <property name="maxActive" value="#{dbConfig.maxActive}"></property> </bean> <!-- 掃描持久層接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 配置接口文件所在的包 --> <property name="basePackage" value="cn.tedu.mybatis.mapper"></property> </bean> <!-- 或取數據源 --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:mappers/*.xml"></property> </bean> </beans>
四、在XML中配置接口方法對應的SQL語句
在`src/main/resources`下創建名為`mappers`文件夾,創建名為UserMapper.xml的文件
根節點必須是`<mapper>`,且根節點的`namespace`表示對應的接口文件,然后,添加子節點,以對應接口中的抽象方法:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <!-- 根節點必須是mapper --> <!-- namespace對應的接口文件 --> <mapper namespace="cn.tedu.mybatis.mapper.UserMapper"> <!-- 根據執行的操作類型選擇節點 --> <!-- id:對應的抽象方法的方法名 --> <!-- 值:#{}括號里面的是User的屬性名 --> <insert id="addnew"> INSERT INTO t_user( username,password,age,phone,email ) value( #{username},#{password},#{age},#{phone},#{email} ) </insert> <select id="findById" resultType="cn.tedu.mybatis.entity.User"> SELECT id,username,password,age,phone,email FROM t_user WHERE id=#{id} </select> <insert id="addnewone"> INSERT INTO t_user( username,password,age,phone,email ) value( #{username},#{password},#{age},#{phone},#{email} ) </insert> <update id="updatenew"> UPDATE t_user SET username=#{username}, password=#{password}, age = #{age}, phone = #{phone}, email=#{email} WHERE id=#{id} </update> <delete id="deletenew"> DELETE FROM t_user WHERE age=#{age} </delete> </mapper>
五、在測試類中測試
package web; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.tedu.mybatis.entity.User; import cn.tedu.mybatis.mapper.UserMapper; public class TestDemo01 { AbstractApplicationContext ac; UserMapper mapper; @Before public void doBefore() { ac = new ClassPathXmlApplicationContext("spring-dao.xml"); mapper = ac.getBean("userMapper",UserMapper.class);//根據id或取對象 } @After public void doafter() { ac.close(); } /* 測試插入*/ @Test public void add() { User user = new User(); user.setUsername("學海無崖"); user.setPassword("12345600"); Integer row = mapper.addnew(user); System.out.println("row:"+row); } /* 測試查詢*/ @Test public void findById() { Integer id=8; User user = mapper.findById(id); System.out.println(user); } /* 測試修改*/ @Test public void updatenew() { User user = new User(); user.setUsername("小珠佩琦"); user.setPassword("5548"); user.setAge(18); user.setEmail("44@qq.com"); user.setPhone("448484"); user.setId(6); Integer num = mapper.updatenew(user); System.out.println("num:"+num); } /* 測試刪除*/ @Test public void deletenew() { Integer age = 60; Integer row = mapper.deletenew(age); System.out.println("row:"+row); } }