網(wǎng)站開發(fā)z億瑪酷1流量訂制怎么做信息流廣告代理商
文章目錄
- Java后端開發(fā)——Mybatis實驗
- 一、MyBatis入門程序
- 1.創(chuàng)建工程
- 2.引入相關依賴
- 3.數(shù)據(jù)庫準備
- 4.編寫數(shù)據(jù)庫連接信息配置文件
- 5.創(chuàng)建POJO實體
- 6.編寫核心配置文件和映射文件
- 二、MyBatis案例:員工管理系統(tǒng)
- 1.在mybatis數(shù)據(jù)庫中創(chuàng)建employee表
- 2.創(chuàng)建持久化類Employee
- 3.編寫映射文件
- 4.添加映射文件路徑配置。
- 5.編寫MyBatisUtils工具類
- 6.編寫測試類
- 三、動態(tài)SQL測試實驗
- 1.創(chuàng)建映射文件CustomerMapper.xml
- 2.在映射文件CustomerMapper.xml中
- 3.添加使用<where>元素執(zhí)行動態(tài)SQL元素
- 4.添加使用<trim>元素執(zhí)行動態(tài)SQL元素
- 5.添加使用<set>元素執(zhí)行更新操作的動態(tài)SQL
- 四、復雜查詢操作實驗
- 1.添加使用<foreach>元素迭代數(shù)組
- 2.添加使用<foreach>元素迭代List集合執(zhí)行批量查詢操作的動態(tài)SQL
- 3.添加使用<foreach>元素迭代Map集合執(zhí)行批量查詢操作的動態(tài)SQL。
Java后端開發(fā)——Mybatis實驗
一、MyBatis入門程序
1.創(chuàng)建工程
在Eclipse中,創(chuàng)建名稱為mybatis的工程
2.引入相關依賴
3.數(shù)據(jù)庫準備
create database mybatis charset=utf8;
4.編寫數(shù)據(jù)庫連接信息配置文件
在項目的src目錄下創(chuàng)建數(shù)據(jù)庫連接的配置文件,這里將其命名為db.properties,在該文件中配置數(shù)據(jù)庫連接的參數(shù)。
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&
characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root
5.創(chuàng)建POJO實體
在項目的src/main/java目錄下創(chuàng)建com.javaweb.pojo包,在com.javaweb.pojo包下創(chuàng)建User類,該類用于封裝User對象的屬性。
package com.javaweb.pojo;public class Customer {
private Integer id; private String username; // 主鍵ID、客戶名稱
private String jobs; private String phone; // 職業(yè)、電話
// 省略getter/setter@Override
public String toString() {
return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]"; }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 getJobs() {
return jobs;
}public void setJobs(String jobs) {
this.jobs = jobs;
}public String getPhone() {
return phone;
}public void setPhone(String phone) {
this.phone = phone;
}
}
6.編寫核心配置文件和映射文件
在項目的src目錄下創(chuàng)建MyBatis的核心配置文件,該文件主要用于項目的環(huán)境配置,如數(shù)據(jù)庫連接相關配置等。核心配置文件可以隨意命名,但通常將其命名為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 核心根標簽-->
<configuration>
<!--引入數(shù)據(jù)庫連接的配置文件-->
<properties resource="db.properties"/>
<!--environments配置數(shù)據(jù)庫環(huán)境,環(huán)境可以有多個。default屬性指定使用的是哪個-->
<environments default="mysql">
<!--environment配置數(shù)據(jù)庫環(huán)境 id屬性唯一標識-->
<environment id="mysql">
<!-- transactionManager事務管理。 type屬性,采用JDBC默認的事務-->
<transactionManager type="JDBC"></transactionManager>
<!-- dataSource數(shù)據(jù)源信息 type屬性 連接池-->
<dataSource type="POOLED">
<!-- property獲取數(shù)據(jù)庫連接的配置信息 -->
<property name="driver" value="${mysql.driver}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</dataSource>
</environment>
</environments>
<!-- mappers引入映射配置文件 -->
<mappers>
<!-- mapper 引入指定的映射配置文件 resource屬性指定映射配置文件的名稱 -->
<mapper resource="com/javaweb/dao/CustomerMapper.xml"></mapper>
</mappers>
</configuration>
二、MyBatis案例:員工管理系統(tǒng)
1.在mybatis數(shù)據(jù)庫中創(chuàng)建employee表
并在employee表中插入幾條數(shù)據(jù)
use mybatis;
create table user(id int primary key auto_increment,name varchar(20) not null,age int not null
);
insert into user values(null,'張三',20),(null,'李四',18);
2.創(chuàng)建持久化類Employee
并在類中聲明id(編號)、name(姓名)、age(年齡)和position(職位)屬性,以及屬性對應的getter/setter方法
package com.javaweb.bean;
public class Employee {
private Integer id;
private String name;
private Integer age;
private String position;
// 省略getter/setter方法
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + name +
", age=" + age + ", position=" + position +'}';
}
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 Integer getAge() {
return age;
}public void setAge(Integer age) {
this.age = age;
}public String getPosition() {
return position;
}public void setPosition(String position) {
this.position = position;
}
}
3.編寫映射文件
創(chuàng)建映射文件EmployeeMapper.xml,該文件主要用于實現(xiàn)SQL語句和Java對象之間的映射。
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.javaweb.mapper.EmployeeMapper">
<select id="findById" parameterType="Integer" resultType="com.javaweb.pojo.Employee">
select * from employee where id = #{id}
</select>
<insert id="add" parameterType="com.javaweb.pojo.Employee">
insert into employee(id,name,age,position) values (#{id},#{name},#{age},#{position})
</insert>
</mapper>
4.添加映射文件路徑配置。
在mybatis-config.xml映射文件的元素下添加EmployeeMapper.xml映射文件路徑的配置。
<mapper
resource="com/javaweb/mapper/EmployeeMapper.xml">
</mapper>
5.編寫MyBatisUtils工具類
創(chuàng)建MyBatisUtils工具類,該類用于封裝讀取配置文件信息的代碼。
public class MyBatisUtils {private static SqlSessionFactory sqlSessionFactory = null;static { try {// 使用MyBatis提供的Resources類加載MyBatis的配置文件Reader reader = Resources.getResourceAsReader("mybatis-config.xml");// 構建SqlSessionFactory工廠sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);} catch (Exception e) { e.printStackTrace();}}public static SqlSession getSession() {//獲取SqlSession對象的靜態(tài)方法return sqlSessionFactory.openSession();}
}
6.編寫測試類
(1)在項目src/test/java目錄下創(chuàng)建Test包,在Test包下創(chuàng)建MyBatisTest測試類,用于程序測試。在MyBatisTest測試類中添加findByIdTest()方法,用于根據(jù)id查詢員工信息。
(2)在MyBatisTest測試類中添加insertTest()方法,用于插入員工信息。
(3)在MyBatisTest測試類中添加updateTest()方法,用于更新員工信息。
(4)在MyBatisTest測試類中添加deleteTest()方法,用于刪除員工信息。
package com.javaweb.test;import java.util.List;import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;import com.javaweb.pojo.Customer;
import com.javaweb.utils.MybatisUtils;class MyBatisTest {@Testpublic void findCustomerByNameAndJobsTest() {SqlSession session = MybatisUtils.getSession();Customer customer = new Customer();customer.setUsername("jack");customer.setJobs("teacher");List<Customer> customers = session.selectList("com.javaweb.dao.CustomerMapper.findCustomerByNameAndJobs",customer);for (Customer customer2 : customers) {System.out.println(customer2);}session.close();}@Testpublic void findCustomerByNameOrJobsTest() {SqlSession session = MybatisUtils.getSession();Customer customer = new Customer();customer.setUsername("tom");customer.setJobs("teacher");List<Customer> customers = session.selectList("com.javaweb.dao.CustomerMapper.findCustomerByNameOrJobs",customer);for (Customer customer2 : customers) {System.out.println(customer2);}session.close();}@Testpublic void findCustomerByNameAndJobs2Test() {SqlSession session = MybatisUtils.getSession();Customer customer = new Customer();customer.setUsername("jack");customer.setJobs("teacher");List<Customer> customers = session.selectList("com.javaweb.dao.CustomerMapper.findCustomerByNameAndJobs2",customer);for (Customer customer2 : customers) {System.out.println(customer2);}session.close();}@Testpublic void findCustomerByNameAndJobs3Test() {SqlSession session = MybatisUtils.getSession();Customer customer = new Customer();customer.setUsername("jack");customer.setJobs("teacher");List<Customer> customers = session.selectList("com.javaweb.dao.CustomerMapper.findCustomerByNameAndJobs3",customer);for (Customer customer2 : customers) {System.out.println(customer2);}session.close();}@Testpublic void updateCustomerBySetTest() { SqlSession sqlSession = MybatisUtils.getSession();Customer customer = new Customer(); customer.setId(3);customer.setPhone("13311111234");int rows = sqlSession.update("com.javaweb.dao"+ ".CustomerMapper.updateCustomerBySet", customer);if(rows > 0) {System.out.println("您成功修改了"+rows+"條數(shù)據(jù)!");} else { System.out.println("執(zhí)行修改操作失敗!!!");}sqlSession.commit();sqlSession.close();}@Testpublic void findByArrayTest() {SqlSession session = MybatisUtils.getSession(); Integer[] roleIds = {2,3}; // 創(chuàng)建數(shù)組,封裝查詢idList<Customer> customers = session.selectList("com.javaweb.dao.CustomerMapper.findByArray", roleIds); for (Customer customer : customers) {System.out.println(customer);}session.close();}}
三、動態(tài)SQL測試實驗
1.創(chuàng)建映射文件CustomerMapper.xml
在映射文件中,根據(jù)客戶姓名和年齡組合條件查詢客戶信息,使用元素編寫該組合條件的動態(tài)SQL,測試并顯示結果。
<select id="findCustomerByNameOrJobs" parameterType="com.javaweb.pojo.Customer"
resultType="com.javaweb.pojo.Customer">
select * from t_customer where 1=1
<choose>
<!--條件判斷 -->
<when test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</when>
<when test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</when>
<otherwise>
and phone is not null
</otherwise>
</choose>
</select>
2.在映射文件CustomerMapper.xml中
添加使用、、元素執(zhí)行動態(tài)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="com.javaweb.dao.CustomerMapper">
<!-- <if>元素使用 -->
<select id="findCustomerByNameAndJobs" parameterType="com.javaweb.pojo.Customer"
resultType="com.javaweb.pojo.Customer">
select * from t_customer where 1=1
<if test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</if>
</select>
<!--<choose>(<when>、<otherwise>)元素使用 -->
<select id="findCustomerByNameOrJobs" parameterType="com.javaweb.pojo.Customer"
resultType="com.javaweb.pojo.Customer">
select * from t_customer where 1=1
<choose>
<!--條件判斷 -->
<when test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</when>
<when test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</when>
<otherwise>
and phone is not null
</otherwise>
</choose>
</select>
<update id="updateCustomerBySet" parameterType="com.javaweb.pojo.Customer">update t_customer
<set>
<if test="username !=null and username !=''">
username=#{username},</if>
<if test="jobs !=null and jobs !=''"> jobs=#{jobs},</if>
<if test="phone !=null and phone !=''">phone=#{phone},</if>
</set> where id=#{id}
</update>
</mapper>
3.添加使用元素執(zhí)行動態(tài)SQL元素
在映射文件CustomerMapper.xml中,添加使用元素執(zhí)行動態(tài)SQL元素,測試并顯示結果。
<select id="findCustomerByNameAndJobs2" parameterType="com.javaweb.pojo.Customer"resultType="com.javaweb.pojo.Customer">select * from t_customer<where><if test="username !=null and username !=''">and username like concat('%',#{username}, '%')</if><if test="jobs !=null and jobs !=''">and jobs= #{jobs}</if></where></select>
4.添加使用元素執(zhí)行動態(tài)SQL元素
在映射文件CustomerMapper.xml中,添加使用元素執(zhí)行動態(tài)SQL元素,測試并顯示結果。
<select id="findCustomerByNameAndJobs3" parameterType="com.javaweb.pojo.Customer"resultType="com.javaweb.pojo.Customer">select * from t_customer<trim prefix="where" prefixOverrides="and" ><if test="username !=null and username !=''">and username like concat('%',#{username}, '%')</if><if test="jobs !=null and jobs !=''">and jobs= #{jobs}</if></trim>
</select>
5.添加使用元素執(zhí)行更新操作的動態(tài)SQL
在映射文件CustomerMapper.xml中,添加使用元素執(zhí)行更新操作的動態(tài)SQL。
<update id="updateCustomerBySet" parameterType="com.itheima.pojo.Customer">update t_customer <set><if test="username !=null and username !=''">username=#{username},</if><if test="jobs !=null and jobs !=''"> jobs=#{jobs},</if><if test="phone !=null and phone !=''">phone=#{phone},</if></set> where id=#{id}
</update>
四、復雜查詢操作實驗
1.添加使用元素迭代數(shù)組
在映射文件CustomerMapper.xml中,添加使用元素迭代數(shù)組執(zhí)行批量查詢操作的動態(tài)SQL。
<select id="findByList" parameterType="java.util.Arrays"resultType="com.javaweb.pojo.Customer">select * from t_customer where id in<foreach item="id" index="index" collection="list" open="(" separator="," close=")">#{id}</foreach>
</select>
2.添加使用元素迭代List集合執(zhí)行批量查詢操作的動態(tài)SQL
在映射文件CustomerMapper.xml中,添加使用元素迭代List集合執(zhí)行批量查詢操作的動態(tài)SQL。
<select id="findByList" parameterType="java.util.Arrays"resultType="com.javaweb.pojo.Customer">select * from t_customer where id in<foreach item="id" index="index" collection="list" open="(" separator="," close=")">#{id}</foreach>
</select>
3.添加使用元素迭代Map集合執(zhí)行批量查詢操作的動態(tài)SQL。
在映射文件CustomerMapper.xml中,添加使用元素迭代Map集合執(zhí)行批量查詢操作的動態(tài)SQL。
<select id="findByMap" parameterType="java.util.Map"resultType="com.javaweb.pojo.Customer">select * from t_customer where jobs=#{jobs} and id in<foreach item="roleMap" index="index" collection="id" open="(" separator="," close=")"> #{roleMap}</foreach>
</select>