做網(wǎng)站的公司都是小公司百度關(guān)鍵詞模擬點擊軟件
文章目錄
- springboot使用mybatis組件
- 1. 添加依賴
- 2. 配置數(shù)據(jù)源
- 3. 創(chuàng)建實體類
- 4. 創(chuàng)建Mapper接口
- 5. 創(chuàng)建Mapper XML文件
- 6. 使用Mapper
- 7. 啟動類配置
- mybtis 動態(tài)SQL
- 1. `@Mapper` 注解
- 2. `@Select` 注解
- 3. `@Insert` 注解
- 4. `@Update` 注解
- 5. `@Delete` 注解
- 6. `@Results` 注解
- 7. `@Param` 注解
- 8. `@CacheNamespace` 注解
- 9. `@Options` 注解
- 10. `@ResultMap` 注解
- 總結(jié)
- mybatis XML標(biāo)簽
- 1. `<mapper>` 標(biāo)簽
- 2. `<select>` 標(biāo)簽
- 3. `<insert>` 標(biāo)簽
- 4. `<update>` 標(biāo)簽
- 5. `<delete>` 標(biāo)簽
- 6. `<resultMap>` 標(biāo)簽
- 7. `<collection>` 標(biāo)簽
- 8. `<include>` 標(biāo)簽
- 9. `<if>` 標(biāo)簽
- 10. `<choose>`、`<when>` 和 `<otherwise>` 標(biāo)簽
- 11. `<foreach>` 標(biāo)簽
- 12. `<trim>` 標(biāo)簽
- 總結(jié)
- 注意
- 參考文獻(xiàn)
springboot使用mybatis組件
在Spring Boot項目中加入MyBatis組件,可以方便地進(jìn)行數(shù)據(jù)庫操作。以下是詳細(xì)的步驟:
1. 添加依賴
首先,在pom.xml
文件中添加MyBatis和數(shù)據(jù)庫驅(qū)動的依賴。例如,如果你使用的是MySQL數(shù)據(jù)庫,可以添加以下依賴:
<dependencies><!-- Spring Boot Starter Data JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- MySQL Connector --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.23</version></dependency><!-- MyBatis Starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency>
</dependencies>
2. 配置數(shù)據(jù)源
在application.properties
或application.yml
文件中配置數(shù)據(jù)源信息。例如,在application.properties
文件中添加以下配置:
# 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# MyBatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
3. 創(chuàng)建實體類
創(chuàng)建與數(shù)據(jù)庫表對應(yīng)的實體類。例如:
package com.example.demo.entity;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax protectedById;@Entity
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private Integer age;// Getters and Setters
}
4. 創(chuàng)建Mapper接口
創(chuàng)建MyBatis的Mapper接口,并使用@Mapper
注解標(biāo)記。例如:
package com.example.demo.mapper;import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;@Mapper
public interface UserMapper {@Select("SELECT * FROM user")List<User> findAll();
}
5. 創(chuàng)建Mapper XML文件
在src/main/resources/mapper
目錄下創(chuàng)建Mapper的XML文件。例如,創(chuàng)建UserMapper.xml
文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.demo.mapper.UserMapper"><select id="findAll" resultType="com.example.demo.entity.User">SELECT * FROM user</select>
</mapper>
6. 使用Mapper
在Service層或Controller層中使用Mapper進(jìn)行數(shù)據(jù)庫操作。例如,在Service層中:
package com.example.demo.service;import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public List<User> getAllUsers() {return userMapper.findAll();}
}
7. 啟動類配置
確保在Spring Boot啟動類上添加@MapperScan
注解,以掃描Mapper接口。例如:
package com.example.demo;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
通過以上步驟,你就可以在Spring Boot項目中成功加入MyBatis組件,并進(jìn)行數(shù)據(jù)庫操作了。
mybtis 動態(tài)SQL
在 MyBatis 中,除了使用 XML 映射文件來定義 SQL 語句之外,還可以使用注解(Annotations)的方式來編寫 SQL 語句。這種方式可以讓 SQL 語句更緊密地與 Java 代碼結(jié)合,使得代碼結(jié)構(gòu)更加清晰。下面是一些常用的 MyBatis 注解及其使用方法。
1. @Mapper
注解
@Mapper
注解用于標(biāo)記一個接口為 MyBatis 的 Mapper 接口。這個接口將包含一系列的 CRUD 方法。
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface UserMapper {// 方法定義
}
2. @Select
注解
@Select
注解用于定義一個 SELECT 語句。
import org.apache.ibatis.annotations.Select;
import com.example.demo.model.User;@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")User getUserById(Long id);
}
3. @Insert
注解
@Insert
注解用于定義一個 INSERT 語句。如果需要獲取自動生成的主鍵值,可以使用 @Options
注解。
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;@Mapper
public interface UserMapper {@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")@Options(useGeneratedKeys = true, keyProperty = "id")void insertUser(User user);
}
4. @Update
注解
@Update
注解用于定義一個 UPDATE 語句。
import org.apache.ibatis.annotations.Update;@Mapper
public interface UserMapper {@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")void updateUser(User user);
}
5. @Delete
注解
@Delete
注解用于定義一個 DELETE 語句。
import org.apache.ibatis.annotations.Delete;@Mapper
public interface UserMapper {@Delete("DELETE FROM user WHERE id=#{id}")void deleteUser(Long id);
}
6. @Results
注解
@Results
注解用于定義結(jié)果映射。它可以幫助處理復(fù)雜的結(jié)果集,比如一對一(One-to-One)或一對多(One-to-Many)的關(guān)系。
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.ResultMap;
import com.example.demo.model.User;
import com.example.demo.model.Address;@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")@Results({@Result(property = "id", column = "id"),@Result(property = "name", column = "name"),@Result(property = "age", column = "age"),@Result(property = "address", column = "address_id",one = @One(select = "com.example.demo.mapper.AddressMapper.getAddressById"))})User getUserById(Long id);
}
7. @Param
注解
@Param
注解用于指定 SQL 語句中的參數(shù)名稱。
import org.apache.ibatis.annotations.Param;@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE name LIKE CONCAT('%', #{name}, '%')")List<User> findUsersByName(@Param("name") String name);
}
8. @CacheNamespace
注解
@CacheNamespace
注解用于定義緩存的命名空間,可以指定緩存的實現(xiàn)類等。
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.cache.decorators.Synchronized;@Mapper
@CacheNamespace(implementation = SynchronizedCache.class)
public interface UserMapper {// 方法定義
}
9. @Options
注解
@Options
注解用于定義 SQL 執(zhí)行后的一些選項,如獲取自動生成的主鍵等。
import org.apache.ibatis.annotations.Options;@Mapper
public interface UserMapper {@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")@Options(useGeneratedKeys = true, keyProperty = "id")void insertUser(User user);
}
10. @ResultMap
注解
@ResultMap
注解用于引用已經(jīng)定義好的結(jié)果映射。
import org.apache.ibatis.annotations.ResultMap;@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")@ResultMap("UserResultMap")User getUserById(Long id);
}
總結(jié)
使用 MyBatis 的注解可以讓你在 Java 代碼中直接定義 SQL 語句,這種方式更加簡潔,特別是在一些簡單的 CRUD 操作中。然而,對于復(fù)雜的 SQL 邏輯或者需要高度定制化的映射關(guān)系,XML 映射文件仍然是一種非常好的選擇。在實際開發(fā)中,可以根據(jù)具體情況選擇最適合的方式來定義 SQL 語句和結(jié)果映射。
mybatis XML標(biāo)簽
MyBatis 是一個優(yōu)秀的持久層框架,它支持定制化的 SQL、存儲過程以及高級映射。在 MyBatis 中,XML 映射文件用于定義 SQL 語句、結(jié)果映射以及其他與數(shù)據(jù)庫交互相關(guān)的配置。下面是 MyBatis 中常用的一些 XML 標(biāo)簽及其用途。
1. <mapper>
標(biāo)簽
<mapper>
標(biāo)簽用于定義一個映射器接口,它包含一系列 SQL 語句和結(jié)果映射。
<mapper namespace="com.example.demo.mapper.UserMapper"><!-- SQL 語句和結(jié)果映射定義 -->
</mapper>
2. <select>
標(biāo)簽
<select>
標(biāo)簽用于定義一個 SELECT 語句。
<select id="getUserById" parameterType="long" resultType="com.example.demo.model.User">SELECT * FROM user WHERE id = #{id}
</select>
3. <insert>
標(biāo)簽
<insert>
標(biāo)簽用于定義一個 INSERT 語句。
<insert id="insertUser" parameterType="com.example.demo.model.User">INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
4. <update>
標(biāo)簽
<update>
標(biāo)簽用于定義一個 UPDATE 語句。
<update id="updateUser" parameterType="com.example.demo.model.User">UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}
</update>
5. <delete>
標(biāo)簽
<delete>
標(biāo)簽用于定義一個 DELETE 語句。
<delete id="deleteUser" parameterType="long">DELETE FROM user WHERE id=#{id}
</delete>
6. <resultMap>
標(biāo)簽
<resultMap>
標(biāo)簽用于定義復(fù)雜的結(jié)果映射關(guān)系,它可以處理一對一(One-to-One)、一對多(One-to-Many)或多對一(Many-to-One)的關(guān)系。
<resultMap id="UserResultMap" type="com.example.demo.model.User"><id property="id" column="id"/><result property="name" column="name"/><result property="age" column="age"/><association property="address" javaType="com.example.demo.model.Address" resultMap="AddressResultMap"/>
</resultMap>
7. <collection>
標(biāo)簽
<collection>
標(biāo)簽用于處理一對多關(guān)系。
<resultMap id="UserResultMap" type="com.example.demo.model.User"><id property="id" column="id"/><result property="name" column="name"/><collection property="orders" ofType="com.example.demo.model.Order" select="getOrdersById"/>
</resultMap>
8. <include>
標(biāo)簽
<include>
標(biāo)簽用于引用外部 SQL 片段。
<sql id="commonColumns">name, age</sql><select id="getAllUsers" resultType="com.example.demo.model.User">SELECT ${commonColumns} FROM user
</select>
9. <if>
標(biāo)簽
<if>
標(biāo)簽用于條件判斷,可以動態(tài)地構(gòu)建 SQL 語句。
<select id="findUsersByName" parameterType="string" resultType="com.example.demo.model.User">SELECT * FROM user WHERE 1=1<if test="name != null">AND name LIKE '%${name}%'</if>
</select>
10. <choose>
、<when>
和 <otherwise>
標(biāo)簽
<choose>
、<when>
和 <otherwise>
標(biāo)簽用于實現(xiàn)多條件判斷。
<select id="findUsers" parameterType="com.example.demo.model.SearchCriteria" resultType="com.example.demo.model.User">SELECT * FROM user WHERE<choose><when test="name != null">name LIKE '%${name}%'</when><when test="age != null">age = ${age}</when><otherwise>1 = 1</otherwise></choose>
</select>
11. <foreach>
標(biāo)簽
<foreach>
標(biāo)簽用于處理集合參數(shù),常用于批量操作。
<insert id="batchInsert" parameterType="java.util.List">INSERT INTO user(name, age) VALUES<foreach item="item" index="index" collection="list" open="(" separator=")," close=")">#{item.name}, #{item.age}</foreach>
</insert>
12. <trim>
標(biāo)簽
<trim>
標(biāo)簽用于動態(tài)拼接 SQL 語句,并提供去除前導(dǎo)或尾隨空白的功能。
<select id="findUsers" parameterType="com.example.demo.model.SearchCriteria" resultType="com.example.demo.model.User">SELECT * FROM user WHERE<trim prefix="WHERE" prefixOverrides="AND|OR"><if test="name != null">AND name LIKE '%${name}%'</if><if test="age != null">OR age = ${age}</if></trim>
</select>
總結(jié)
以上是 MyBatis 中常用的 XML 標(biāo)簽及其用途。通過這些標(biāo)簽,可以靈活地定義 SQL 語句、結(jié)果映射以及其他與數(shù)據(jù)庫交互相關(guān)的配置。掌握這些標(biāo)簽的使用方法,可以幫助你更好地利用 MyBatis 處理復(fù)雜的數(shù)據(jù)庫操作。
注意
- sql的配置有兩種方式:動態(tài)SQL和xml配置
- 推薦使用xml配置,原因如下:
某些場景下,可能需要對遷移到其他類型數(shù)據(jù)庫,使用xml配置:
- 可以不需要改動代碼, 而僅需復(fù)制一份xml, 針對新的類型的數(shù)據(jù)庫進(jìn)行兼容性改造。
- 新舊數(shù)據(jù)庫切換時,在發(fā)生異常時,可以切換回舊的數(shù)據(jù)庫操作,保證業(yè)務(wù)連續(xù)性。
參考文獻(xiàn)
官網(wǎng)中文文檔