## Mybatis ### 舉個小慄子 mybatis配置文件(XML配置文件) ```java ``` user.xml(實現增刪改查的sql語句) ```xml insert into user values (#{userId},#{username},#{password}) delete ...
Mybatis
舉個小慄子
mybatis配置文件(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">
<!--通過這個配置文件,完成mybatis與資料庫的連接 -->
<configuration>
<!--mybatis 在實例化的時候,會自動掃描這個包下的所有類,用於後續 sql 語句的 resultType-->
<typeAliases>
<package name="com.iweb.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="url" value="jdbc:mysql://localhost:3306/iweb?characterEncoding=utf-8"/>
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/user.xml"/>
</mappers>
</configuration>
user.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="com.iweb.entity">
<select id="listUser" resultType="User">select * from user</select>
<!-- parameterType:表示傳入的參數類型,可以是基本數據類型,也可以是引用類型
基本類型中需要註意:如果傳入的參數為整型,參數“_int” 表示 int 類型,參數“int” 表示 Integer 類型-->
<insert id="addUser" parameterType="User">insert into user values (#{userId},#{username},#{password})</insert>
<delete id="deleteUser" parameterType="String">delete from user where userId = #{userId}</delete>
<update id="updateUser" parameterType="User">update user set username = #{username},password = #{password} where userId = #{userId}</update>
<select id="getUser" parameterType="String" resultType="User">select * from user where userId = #{userId}</select>
<!-- 模糊查詢-->
<select id="listUserByNameLike" parameterType="String" resultType="User">select * from user where username like concat('%',#{0},'%')</select>
<!-- 複雜查詢-->
<select id="listUserByIdAndNameLike" parameterType="map" resultType="User">select * from user where userId > #{userId} and username like concat('%',#{username},'%')</select>
</mapper>
使用做sql查詢(Test)
public void test1() throws IOException {
private SqlSession sqlSession;
@Before
public void init() throws IOException {
// 輸入流讀取配置文件信息
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 基於配置文件獲取 mybatis 的一級緩存對象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 基於這個一級緩存,創建一個二級緩存
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void test01(){
// 使用二級緩存實現sql語句調用
List<User> userList = sqlSession.selectList("listUser");
// 遍歷集合
for (User user : userList) {
System.out.println(user);
}
}
@Test
public void test02(){
User user = new User("3","robot01","123456");
sqlSession.insert("addUser",user);
// mybatis 需要手動提交緩存
sqlSession.commit();
test01();
}
@Test
public void test03(){
User user = new User();
user.setUserId("3");
sqlSession.delete("deleteUser",user);
sqlSession.commit();
test01();
}
@Test
public void test04(){
User user = sqlSession.selectOne("getUser","2");
System.out.println(user);
}
@Test
public void test05(){
User user = new User("2","HSS","123456");
sqlSession.update("updateUser",user);
sqlSession.commit();
test01();
}
@Test
public void test06(){
List<User> users = sqlSession.selectList("listUserByNameLike","ss");
System.out.println(users);
}
@Test
public void test07(){
Map<String,Object> params = new HashMap<>();
params.put("userId",2);
params.put("username","ss");
List<User> users = sqlSession.selectList("listUserByIdAndNameLike",params);
System.out.println(users);
}
}
一對多關係查詢
配置文件(⭐註意:每一個配置文件都需要在 mybatis-config.xml 中進行註冊!!!!!!!!!)
<resultMap id="productBean" type="Product">
<id column="productId" property="productId"/>
<result column="productName" property="productName"/>
<result column="price" property="price"/>
<result column="stock" property="stock"/>
<association property="user" javaType="User">
<id column="uId" property="userId"/>
<result column="username" property="username"/>
</association>
</resultMap>
<!-- 多對一關係查詢-->
<select id="listProduct" resultMap="productBean">
select productName,productId,price,stock,u.userId 'uId',username from product left join user u on product.userId = u.userId
</select>
測試類
public class TestMybatis {
private SqlSession sqlSession;
@Before
public void init() throws IOException {
// 輸入流讀取配置文件信息
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 基於配置文件獲取 mybatis 的一級緩存對象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 基於這個一級緩存,創建一個二級緩存
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void test01(){
List<Product> productList = sqlSession.selectList("listProduct");
for (Product product : productList) {
System.out.println(product);
}
}
}
動態sql查詢
配置文件(⭐註意:每一個配置文件都需要在 mybatis-config.xml 中進行註冊!!!!!!!!!)
<select id="listProduct" resultType="product">
select * from product
<if test="productName != null">
where productName like concat('%',#{productName},'%')
</if>
</select>
測試類
@Test
public void test01(){
List<Product> productList = sqlSession.selectList("listProduct");
for (Product product : productList) {
System.out.println(product);
}
}
@Test
public void test02(){
Map<String,String> params = new HashMap<>();
params.put("productName","1");
List<Product> productList = sqlSession.selectList("listProduct",params);
for (Product product : productList) {
System.out.println(product);
}
}
多條件查詢
<!--多條件查詢的矛盾-->
<!-- where 標簽會進行自動判斷,如果所有的 if 條件都不成立,那麼 sql 語句中不會出現 where 關鍵字
只要有一個條件成立,就會自動去除冗餘的 and,並自動添加 where-->
<select id="listProduct" resultType="Product">
select * from product
<where>
<if test="productName != null">
and productName like concat('%',#{productName},'%')
</if>
<if test="price != 0">
and price > #{price}
</if>
</where>
</select>
測試類
@Test
public void test01(){
Map<String,Object> params = new HashMap<>();
params.put("productName","1");
params.put("price",0);
List<Product> productList = sqlSession.selectList("listProduct",params);
for (Product product : productList) {
System.out.println(product);
}
}
動態sql更新
<update id="updateProduct">
update product
<set>
<if test="productName != null">
productName = #{productName},
</if>
<if test="price != null">
price = #{price},
</if>
<if test="stock != null">
stock = #{stock},
</if>
</set>
where productId = #{productId}
</update>
測試類
@Test
public void test01(){
Map<String,Object> params = new HashMap<>();
params.put("productId","1");
params.put("productName","product");
params.put("price","10086");
params.put("stock","10000");
sqlSession.update("updateProduct",params);
sqlSession.commit();
}
when otherwise 標簽
<mapper namespace="com.iweb.entity">
<!-- mybatis 沒有 else 標簽,只能使用 when otherwise 表示 else,如果提供了任何條件,則進行條件鏟鱘,如果沒有提供任何條件參數,則使用 otherwise 作為條件-->
<select id="listProduct" resultType="Product">
select * from product
<where>
<choose>
<when test="productName != null">
and name like concat('%',#{productName},'%')
</when>
<when test="price != null">
and price > #{price}
</when>
<otherwise>
and id > 5
</otherwise>
</choose>
</where>
</select>
</mapper>
使用註解方式實現簡單的sql
mapper介面文件(一定要註冊!!!!!!)
/**
* 通過介面(底層是java的JDK動態代理)實現 mybatis 調用
* 開發人員只需要關心介面,實現類由 mybatis 動態生成
* 1. 註解開發方式: 適用於簡單場景(註解場景下編寫一對多 多對一 或者是動態sql非常麻煩)
* 2. xml配置文件開發方式:適用於所有場景(推薦)
* @author te9uila
* @since 2023/8/5
*/
public interface ProductMapper {
@Insert("insert into product values (#{productId},#{productName},#{price},#{stock},#{userId})")
void add(Product product);
@Delete("delete from product where productId = #{productId}")
void delete(String id);
@Select("select * from product where productId = #{productId}")
Product get(String id);
@Update("update product set productName = #{productName},price = #{price},stock = #{stock} where productId = #{productId}")
int update(Product product);
@Select("select * from product")
List<Product> list();
}
測試類
@Test
public void test01(){
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
List<Product> productList = productMapper.list();
System.out.println(productList);
}