mybatis大集合
Mybatis
1. Mybatis介紹
MyBatis是支援普通SQL查詢,儲存過程和高階對映的優秀持久層框架。MyBatis消除了幾乎所有的JDBC程式碼和引數的手工設定以及對結果集的檢索封裝。MyBatis可以使用簡單的XML或註解用於配置和原始對映,將介面和Java的POJO(Plain Old Java Objects,普通的Java物件)對映成資料庫中的記錄.
JDBC-àdbutils(自動封裝)-àMyBatis-àHibernate
xml |
2. mybatis快速入門
編寫第一個基於mybaits的測試例子:
2.1.新增jar包
【mybatis】 mybatis-3.1.1.jar 【MYSQL驅動包】 |
2.2.建庫+表
create database mybatis; use mybatis; CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT); INSERT INTO users(NAME, age) VALUES('Tom', 12); INSERT INTO users(NAME, age) VALUES('Jack', 11); |
2.3. 新增Mybatis的配置檔案conf.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> <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/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration> |
2.4. 定義表所對應的實體類
public class User { private int id; private String name; private int age; //get,set方法 } |
2.5. 定義操作users表的sql對映檔案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="com.atguigu.mybatis_test.test1.userMapper"> <select id="getUser" parameterType="int" resultType="com.atguigu.mybatis_test.test1.User"> select * from users where id=#{id} </select> </mapper> |
2.6. 在conf.xml檔案中註冊userMapper.xml檔案
<mappers> <mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/> </mappers> |
2.7. 編寫測試程式碼:執行定義的select語句
public class Test { public static void main(String[] args) throws IOException { String resource = "conf.xml"; //載入mybatis的配置檔案(它也載入關聯的對映檔案) Reader reader = Resources.getResourceAsReader(resource); //構建sqlSession的工廠 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //建立能執行對映檔案中sql的sqlSession SqlSession session = sessionFactory.openSession(); //對映sql的標識字串 String statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser"; //執行查詢返回一個唯一user物件的sql User user = session.selectOne(statement, 1); System.out.println(user); } } |
3. 操作users表的CRUD
3.1. XML的實現
1). 定義sql對映xml檔案:
<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User"> insert into users(name, age) values(#{name}, #{age}); </insert>
<delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete>
<update id="updateUser" parameterType="com.atguigu.ibatis.bean.User"> update users set name=#{name},age=#{age} where id=#{id} </update>
<select id="selectUser" parameterType="int" resultType="com.atguigu.ibatis.bean.User"> select * from users where id=#{id} </select>
<select id="selectAllUsers" resultType="com.atguigu.ibatis.bean.User"> select * from users </select> |
2). 在config.xml中註冊這個對映檔案
<mapper resource=" com/atguigu/ibatis/bean/userMapper.xml"/> |
3). 在dao中呼叫:
public User getUserById(int id) { SqlSession session = sessionFactory.openSession(); User user = session.selectOne(URI+".selectUser", id); return user; } |
3.2. 註解的實現
1). 定義sql對映的介面
public interface UserMapper { @Insert("insert into users(name, age) values(#{name}, #{age})") public int insertUser(User user);
@Delete("delete from users where id=#{id}") public int deleteUserById(int id);
@Update("update users set name=#{name},age=#{age} where id=#{id}") public int updateUser(User user);
@Select("select * from users where id=#{id}") public User getUserById(int id);
@Select("select * from users") public List<User> getAllUser(); }
|
2). 在config中註冊這個對映介面
<mapper class="com.atguigu.ibatis.crud.ano.UserMapper"/> |
3). 在dao類中呼叫
public User getUserById(int id) { SqlSession session = sessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.getUserById(id); return user; } |
4. 幾個可以優化的地方
4.1.連線資料庫的配置單獨放在一個properties檔案中
## db.properties
<properties resource="db.properties"/>
<property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> |
4.2.為實體類定義別名,簡化sql對映xml檔案中的引用
<typeAliases> <typeAlias type="com.atguigu.ibatis.bean.User" alias="_User"/> </typeAliases> |
4.3.可以在src下加入log4j的配置檔案,列印日誌資訊
1. 新增jar: log4j-1.2.16.jar
2.1. log4j.properties(方式一)
log4j.properties, log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
2.2. log4j.xml(方式二)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="debug" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration> |
5. 解決欄位名與實體類屬性名不相同的衝突
5.1.準備表和資料:
CREATE TABLE orders( order_id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(20), order_price FLOAT ); INSERT INTO orders(order_no, order_price) VALUES('aaaa', 23); INSERT INTO orders(order_no, order_price) VALUES('bbbb', 33); INSERT INTO orders(order_no, order_price) VALUES('cccc', 22); |
5.2.定義實體類:
public class Order { private int id; private String orderNo; private float price; } |
5.3.實現getOrderById(id)的查詢:
方式一: 通過在sql語句中定義別名 <select id="selectOrder" parameterType="int" resultType="_Order"> select order_id id, order_no orderNo,order_price price from orders where order_id=#{id} </select>
方式二: 通過<resultMap> <select id="selectOrderResultMap" parameterType="int" resultMap="orderResultMap"> select * from orders where order_id=#{id} </select>
<resultMaptype="_Order" id="orderResultMap"> <id property="id" column="order_id"/> <result property="orderNo" column="order_no"/> <result property="price" column="order_price"/> </resultMap> |
6.實現關聯表查詢
6.1. 一對一關聯
1). 提出需求
根據班級id查詢班級資訊(帶老師的資訊)
2). 建立表和資料
CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) ); CREATE TABLE class( c_id INT PRIMARY KEY AUTO_INCREMENT, c_name VARCHAR(20), teacher_id INT ); ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);
INSERT INTO teacher(t_name) VALUES('LS1'); INSERT INTO teacher(t_name) VALUES('LS2');
INSERT INTO class(c_name, teacher_id) VALUES('bj_a', 1); INSERT INTO class(c_name, teacher_id) VALUES('bj_b', 2); |
3). 定義實體類:
public class Teacher { private int id; private String name; } public class Classes { private int id; private String name; private Teacher teacher; } |
4). 定義sql對映檔案ClassMapper.xml
<!-- 方式一:巢狀結果:使用巢狀結果對映來處理重複的聯合結果的子集 封裝聯表查詢的資料(去除重複的資料) select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1 --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="_Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap>
<!-- 方式二:巢狀查詢:通過執行另外一個SQL對映語句來返回預期的複雜型別 SELECT * FROM class WHERE c_id=1; SELECT * FROM teacher WHERE t_id=1 //1 是上一個查詢得到的teacher_id的值 -->
<select id="getClass2" parameterType="int" resultMap="ClassResultMap2"> select * from class where c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher"> </association> </resultMap>
<select id="getTeacher" parameterType="int" resultType="_Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select> |
5). 測試
@Test public void testOO() { SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass", 1); System.out.println(c); }
@Test public void testOO2() { SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass2", 1); System.out.println(c); } |
6.2. 一對多關聯
1). 提出需求
根據classId查詢對應的班級資訊,包括學生,老師
2). 建立表和資料:
CREATE TABLE student( s_id INT PRIMARY KEY AUTO_INCREMENT, s_name VARCHAR(20), class_id INT ); INSERT INTO student(s_name, class_id) VALUES('xs_A', 1); INSERT INTO student(s_name, class_id) VALUES('xs_B', 1); INSERT INTO student(s_name, class_id) VALUES('xs_C', 1); INSERT INTO student(s_name, class_id) VALUES('xs_D', 2); INSERT INTO student(s_name, class_id) VALUES('xs_E', 2); INSERT INTO student(s_name, class_id) VALUES('xs_F', 2);
|
3). 定義實體類:
public class Student { private int id; private String name; }
public class Classes { private int id; private String name; private Teacher teacher; private List<Student> students; } |
4). 定義sql對映檔案ClassMapper.xml
<!-- 方式一: 巢狀結果: 使用巢狀結果對映來處理重複的聯合結果的子集 SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1 --> <select id="getClass3" parameterType="int" resultMap="ClassResultMap3"> select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap3"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="_Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- ofType指定students集合中的物件型別 --> <collection property="students" ofType="_Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap>
<!-- 方式二:巢狀查詢:通過執行另外一個SQL對映語句來返回預期的複雜型別 SELECT * FROM class WHERE c_id=1; SELECT * FROM teacher WHERE t_id=1 //1 是上一個查詢得到的teacher_id的值 SELECT * FROM student WHERE class_id=1 //1是第一個查詢得到的c_id欄位的值 --> <select id="getClass4" parameterType="int" resultMap="ClassResultMap4"> select * from class where c_id=#{id} </select> <resultMap type="_Classes" id="ClassResultMap4"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher2"></association> <collection property="students" ofType="_Student" column="c_id" select="getStudent"></collection> </resultMap>
<select id="getTeacher2" parameterType="int" resultType="_Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select>
<select id="getStudent" parameterType="int" resultType="_Student"> SELECT s_id id, s_name name FROM student WHERE class_id=#{id} </select> |
5). 測試:
@Test public void testOM() { SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass3", 1); System.out.println(c); }
@Test public void testOM2() { SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass4", 1); System.out.println(c); }
|
7. 動態SQL與模糊查詢
7.1. 提出需求:
實現多條件查詢使用者(姓名模糊匹配, 年齡在指定的最小值到最大值之間)
7.2. 準備資料表和資料:
create table d_user( id int primary key auto_increment, name varchar(10), age int(3) );
insert into d_user(name,age) values('Tom',12); insert into d_user(name,age) values('Bob',13); insert into d_user(name,age) values('Jack',18); |
7.3. ConditionUser(查詢條件實體類)
private String name; private int minAge; private int maxAge; |
7.4. User(表實體類)
private int id; private String name; private int age; |
7.5. 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="com.atguigu.day03_mybatis.test6.userMapper"> <select id="getUser" parameterType="com.atguigu.day03_mybatis.test6.ConditionUser" resultType="com.atguigu.day03_mybatis.test6.User"> select * from d_user where age>=#{minAge} and age<=#{maxAge} <if test='name!="%null%"'>and name like #{name}</if> </select> </mapper> |
7.6. UserTest(測試)
public class UserTest {
public static void main(String[] args) throws IOException {
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sessionFactory.openSession();
String statement = "com.atguigu.day03_mybatis.test6.userMapper.getUser";
List<User> list = sqlSession.selectList(statement, new ConditionUser("%a%", 1, 12));
System.out.println(list); } } |
MyBatis中可用的動態SQL標籤
8.呼叫儲存過程
8.1. 提出需求:
查詢得到男性或女性的數量, 如果傳入的是0就女性否則是男性
8.2. 準備資料庫表和儲存過程:
create table p_user( id int primary key auto_increment, name varchar(10), sex char(2) );
insert into p_user(name,sex) values('A',"男"); insert into p_user(name,sex) values('B',"女"); insert into p_user(name,sex) values('C',"男");
#建立儲存過程(查詢得到男性或女性的數量, 如果傳入的是0就女性否則是男性) DELIMITER $ CREATE PROCEDURE mybatis.ges_user_count(IN sex_id INT, OUT user_count INT) BEGIN IF sex_id=0 THEN SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='女' INTO user_count; ELSE SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='男' INTO user_count; END IF; END $
#呼叫儲存過程 DELIMITER ; SET @user_count = 0; CALL mybatis.ges_user_count(1, @user_count); SELECT @user_count; |
8.3. 建立表的實體類
public class User { private String id; private String name; private String sex; } |
8.4. userMapper.xml
<mapper namespace="com.atguigu.mybatis.test7.userMapper"> <!-- 查詢得到男性或女性的數量, 如果傳入的是0就女性否則是男性 CALL mybatis.get_user_count(1, @user_count); --> <select id="getCount" statementType="CALLABLE" parameterMap="getCountMap"> call mybatis.get_user_count(?,?) </select> <parameterMap type="java.util.Map" id="getCountMap"> <parameter property="sex_id" mode="IN" jdbcType="INTEGER"/> <parameter property="user_count" mode="OUT" jdbcType="INTEGER"/> </parameterMap> </mapper> |
8.5. 測試呼叫:
Map<String, Integer> paramMap = new HashMap<>(); paramMap.put("sex_id", 0);
session.selectOne(statement, paramMap);
Integer userCount = paramMap.get("user_count"); System.out.println(userCount); |
9. Mybatis快取
9.1. 理解MyBatis快取
正如大多數持久層框架一樣,MyBatis 同樣提供了一級快取和二級快取的支援
1. 一級快取: 基於PerpetualCache 的 HashMap本地快取,其儲存作用域為 Session,當 Session flush 或 close 之後,該Session中的所有 Cache 就將清空。 2. 二級快取與一級快取其機制相同,預設也是採用 PerpetualCache,HashMap儲存,不同在於其儲存作用域為 Mapper(Namespace),並且可自定義儲存源,如 Ehcache。 3. 對於快取資料更新機制,當某一個作用域(一級快取Session/二級快取Namespaces)的進行了 C/U/D 操作後,預設該作用域下所有 select 中的快取將被clear。 |
9.2. Mybatis一級快取
1) 提出需求:
根據id查詢對應的使用者記錄物件
2). 準備資料庫表和資料
CREATE TABLE c_user( id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT ); INSERT INTO c_user(NAME, age) VALUES('Tom', 12); INSERT INTO c_user(NAME, age) VALUES('Jack', 11); |
3). 建立表的實體類
public class User implements Serializable{
private int id; private String name; private int age; } |
4). 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="com.atguigu.mybatis.test8.userMapper">
<select id="getUser" parameterType="int" resultType="_CUser"> select * from c_user where id=#{id} </select>
<update id="updateUser" parameterType="_CUser"> update c_user set name=#{name}, age=#{age} where id=#{id} </update> </mapper> |
5). 測試:
/* * 一級快取: 也就Session級的快取(預設開啟) */ @Test public void testCache1() { SqlSession session = MybatisUtils.getSession(); String statement = "com.atguigu.mybatis.test8.userMapper.getUser"; User user = session.selectOne(statement, 1); System.out.println(user);
/* * 一級快取預設就會被使用 */ /* user = session.selectOne(statement, 1); System.out.println(user); */
/* 1. 必須是同一個Session,如果session物件已經close()過了就不可能用了 */ /* session = MybatisUtils.getSession(); user = session.selectOne(statement, 1); System.out.println(user); */
/* 2. 查詢條件是一樣的 */ /* user = session.selectOne(statement, 2); System.out.println(user); */
/* 3. 沒有執行過session.clearCache()清理快取 */ /* session.clearCache(); user = session.selectOne(statement, 2); System.out.println(user); */
/* 4. 沒有執行過增刪改的操作(這些操作都會清理快取) */ /* session.update("com.atguigu.mybatis.test8.userMapper.updateUser", new User(2, "user", 23)); user = session.selectOne(statement, 2); System.out.println(user); */ } |
9.3. Mybatis二級快取
1). 新增一個<cache>在userMapper.xml中
<mapper namespace="com.atguigu.mybatis.test8.userMapper"> <cache/> |
2). 測試
/* * 測試二級快取 */ @Test public void testCache2() { String statement = "com.atguigu.mybatis.test8.userMapper.getUser";
SqlSession session = MybatisUtils.getSession(); User user = session.selectOne(statement, 1); session.commit(); System.out.println("user="+user);
SqlSession session2 = MybatisUtils.getSession(); user = session2.selectOne(statement, 1); session.commit(); System.out.println("user2="+user); } |
3). 補充說明
1. 對映語句檔案中的所有select語句將會被快取。 2. 對映語句檔案中的所有insert,update和delete語句會重新整理快取。 3. 快取會使用Least Recently Used(LRU,最近最少使用的)演算法來收回。 4. 快取會根據指定的時間間隔來重新整理。 5. 快取會儲存1024個物件 |
<cache eviction="FIFO" //回收策略為先進先出 flushInterval="60000" //自動重新整理時間60s size="512" //最多快取512個引用物件 readOnly="true"/> //只讀 |
10. spring整合mybatis
10.1. 新增Jar包
【mybatis】 mybatis-3.2.0.jar mybatis-spring-1.1.1.jar log4j-1.2.17.jar 【spring】 spring-aop-3.2.0.RELEASE.jar spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar spring-jdbc-3.2.0.RELEASE.jar spring-test-3.2.4.RELEASE.jar spring-tx-3.2.0.RELEASE.jar
aopalliance-1.0.jar cglib-nodep-2.2.3.jar commons-logging-1.1.1.jar 【MYSQL驅動包】 mysql-connector-java-5.0.4-bin.jar |
10.2. 資料庫表
user_id INT AUTO_INCREMENT PRIMARY KEY, user_name VARCHAR(30), user_birthday DATE, user_salary DOUBLE ) |
10.3. 實體類: User
public class User {
private int id; private String name; private Date birthday; private double salary;
//set,get方法 } |
10.4. DAO介面: UserMapper (XXXMapper)
public interface UserMapper {
void save(User user); void update(User user); void delete(int id); User findById(int id); List<User> findAll(); } |
10.5. SQL對映檔案: 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="com.atguigu.mybatis.test9.UserMapper"> <resultMap type="User" id="userResult"> <result column="user_id" property="id"/> <result column="user_name" property="name"/> <result column="user_birthday" property="birthday"/> <result column="user_salary" property="salary"/> </resultMap>
<!-- 取得插入資料後的id --> <insert id="save" keyColumn="user_id" keyProperty="id" useGeneratedKeys="true"> insert into s_user(user_name,user_birthday,user_salary) values(#{name},#{birthday},#{salary}) </insert>
<update id="update"> update s_user set user_name = #{name}, user_birthday = #{birthday}, user_salary = #{salary} where user_id = #{id} </update>
<delete id="delete"> delete from s_user where user_id = #{id} </delete>
<select id="findById" resultMap="userResult"> select * from s_user where user_id = #{id} </select>
<select id="findAll" resultMap="userResult"> select * from s_user </select> </mapper> |
10.6. spring的配置檔案: beans.xml
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 1. 資料來源 : DriverManagerDataSource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean>
<!-- 2. mybatis的SqlSession的工廠: SqlSessionFactoryBean dataSource / typeAliasesPackage --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="com.atuigu.spring_mybatis2.domain"/> </bean>
<!-- 3. mybatis自動掃描載入Sql對映檔案 : MapperScannerConfigurer sqlSessionFactory / basePackage --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.atuigu.spring_mybatis2.mapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
<!-- 4. 事務管理 : DataSourceTransactionManager --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
<!-- 5. 使用宣告式事務 --> <tx:annotation-driven transaction-manager="txManager" />
</beans> |
10.7. mybatis的配置檔案:mybatis-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> <!-- Spring整合myBatis後,這個配置檔案基本可以不要了--> <!-- 設定外部配置檔案 --> <!-- 設定類別名 --> <!-- 設定資料庫連線環境 --> <!-- 對映檔案 --> </configuration> |
10.8. 測試
@RunWith(SpringJUnit4ClassRunner.class) //使用Springtest測試框架 @ContextConfiguration("/beans.xml") //載入配置 public class SMTest {
@Autowired //注入 private UserMapper userMapper;
@Test public void save() { User user = new User(); user.setBirthday(new Date()); user.setName("marry"); user.setSalary(300); userMapper.save(user); System.out.println(user.getId()); }
@Test public void update() { User user = userMapper.findById(2); user.setSalary(2000); userMapper.update(user); }
@Test public void delete() { userMapper.delete(3); }
@Test public void findById() { User user = userMapper.findById(1); System.out.println(user); }
@Test public void findAll() { List<User> users = userMapper.findAll(); System.out.println(users); } } |
相關文章
- 網站及工具大集合網站
- hadoop開源工具大集合Hadoop開源工具
- 資源共享|Python 中文書籍大集合!Python
- Kubernetes客戶端和管理介面大集合客戶端
- 從Redis中刪除大集合物件的方法Redis物件
- Spring Boot基礎面試題2020大集合Spring Boot面試題
- Mac新手必看基礎篇,mac快捷鍵大集合Mac
- 大話後端開發的奇淫技巧大集合後端
- MyBatis(二)MyBatis入門程式(MyBatis demo)MyBatis
- 2018最小巧實用的視訊剪輯工具大集合
- Vue 生產專案連結 — 上線專案大集合Vue
- Spring Cloud 終結篇之訊息驅動--stream 大集合SpringCloud
- MyBatis——MyBatis開發流程MyBatis
- 【Mybatis】Mybatis快速入門MyBatis
- MyBatis -01- 初識 MyBatis + MyBatis 環境搭建MyBatis
- 計算機作業系統複習知識點大集合計算機作業系統
- MyBatis系列(一):MyBatis入門MyBatis
- MyBatisMyBatis
- 從零學習flutter(八):Flutter百星開源專案大集合Flutter
- MyBatis-08-Spring的MyBatis InterceptorMyBatisSpring
- 「Mybatis系列」Mybatis高階應用MyBatis
- mybatis plus 啟用 mybatis外掛MyBatis
- Mybatis基礎:Mybatis對映配置檔案,Mybatis核心配置檔案,Mybatis傳統方式開發MyBatis
- 開發者天堂:免費API介面大集合,助你輕鬆打造應用API
- Java 集合詳解 | 一篇文章解決Java 三大集合Java
- mybatis的外掛:mybatis-generator(MBG)MyBatis
- Mybatis20_mybatis的多表操作8MyBatis
- MyBatis-05-MyBatis使用流程簡讀MyBatis
- 「Mybatis系列」Mybatis開發方式和配置MyBatis
- 深入淺出MyBatis:MyBatis的所有配置MyBatis
- MyBatis(十一):MyBatis架構流程淺析MyBatis架構
- mybatis generatorMyBatis
- MyBatis-MyBatis
- MyBatis 配置MyBatis
- 2024.11.1(MyBatis)MyBatis
- 2024.11.2(MyBatis)MyBatis
- Mybatis常用MyBatis
- mybatis教程MyBatis
- Mybatis修改MyBatis