MyBatis 동적 SQL 알아보기
sql tutorialSQL의 강력한 기능 소개 MyBatis SQL
권장(무료): sql tutorial
Dynamic SQL
MyBatis의 강력한 기능 중 하나는 동적 SQL입니다. JDBC 또는 기타 유사한 프레임워크를 사용해 본 경험이 있다면 다양한 조건에 따라 SQL 문을 연결하는 데 따른 어려움을 이해하게 될 것입니다. 예를 들어, 스플라이스할 때 필요한 공백을 추가하는 것을 잊지 않도록 주의하고, 목록의 마지막 열 이름에서 쉼표를 제거하도록 주의하십시오. 이러한 어려움을 완전히 없애려면 동적 SQL 기능을 활용하십시오.
과거에는 동적 SQL을 사용하는 것이 쉽지 않았지만 마이바티스는 어떤 SQL 매핑 문에서도 사용할 수 있는 강력한 동적 SQL 언어를 제공하여 이러한 상황을 개선했습니다.
동적 SQL 요소는 JSTL 또는 XML 기반 텍스트 프로세서와 유사합니다. 이전 버전의 MyBatis에서는 이해하는 데 시간이 걸리는 요소가 많았습니다. MyBatis 3에서는 요소 유형이 크게 단순화되었습니다. 이제 원래 요소의 절반만 배우면 됩니다. MyBatis는 강력한 OGNL 기반 표현식을 사용하여 대부분의 다른 요소를 제거합니다.
준비
먼저 User 엔터티 클래스를 생성합니다
public class User { private Integer id; private String username; private String userEmail; private String userCity; private Integer age;}
사용자 테이블을 생성합니다
CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(255) DEFAULT NULL, user_email varchar(255) DEFAULT NULL, user_city varchar(255) DEFAULT NULL, age int(11) DEFAULT NULL, PRIMARY KEY (id))
if
인터페이스 메소드 정의
public List<User> findByUser(User user);
해당 Mapper.xml 인터페이스 정의는 다음과 같습니다
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user where <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if></select>
if 태그 테스트가 true이면 if 태그의 SQL 문이 연결됩니다.
username, userEmail, userCity가 비어 있지 않으면 아래와 같이 SQL이 splicing됩니다
select id, username, user_email userEmail, user_city userCity, age from user where username = ? and user_email = ? and user_city = ?
username만 비어 있지 않으면 SQL이 다음과 같이 splicing됩니다
select id, username, user_email userEmail, user_city userCity, age from user where username = ?
하지만 이 방법의 문제 단점, 현재 사용자 이름이 비어 있다고 가정하면 userEmail과 userCity 모두 비어 있지 않습니다.
동적 SQL 코드를 분석해 보겠습니다. username에 할당된 값이 없습니다. 즉, username==null이므로 "username=#{username}" 코드는 SQL 문에 추가되지 않습니다. 동적 SQL은 다음과 같습니다:
select id, username, user_email userEmail, user_city userCity, age from user where and user_email = ? and user_city = ?
where 바로 뒤에 and가 옵니다. 이는 명백한 문법 오류입니다. 이때 where
바로 뒤에는 and
가 있어야 합니다. 삭제되었습니다. 이 문제를 해결하려면 where
태그를 사용하면 됩니다. where
后面的and
删掉。为了解决这个问题,可以使用where
标签。
where
将上面的SQL改成如下所示
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user <where> <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if> </where> </select>
如果where
标签里面的if
标签有满足条件的,那么where
标签就会被拼接成where语句,若if
标签拼接的SQL最前面有and语句,那么这个and将会被删除。使用这种方法, 会自动删除SQL中不需要的关键字,所以一般 if 标签和 where 标签会组合起来使用。
trim
trim
标签中的 prefix
和 suffix
属性会被用于生成实际的 SQL 语句,会和标签内部的语句拼接。
如果语句的前面或后面遇到 prefixOverrides
或 suffixOverrides
属性中指定的值,MyBatis 会自动将它们删除。在指定多个值的时候,别忘了每个值后面都要有一个空格,保证不会和后面的 SQL 连接在一起。
prefix:给拼接的SQL语句加一个前缀
suffix:给拼接的SQL语句加一个后缀
prefixOverrides:拼接的SQL语句前面遇到 prefixOverrides
,MyBatis 会自动将它们删除
suffixOverrides:拼接的SQL语句后面遇到 suffixOverrides
,MyBatis 会自动将它们删除
下面使用trim
标签来实现where
标签的功能
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user <trim prefix="where" prefixOverrides="and"> <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if> </trim> </select>
如果username为空,userEmail和userCity不为空,那么if
标签拼接的SQL语句如下所示
and user_email = #{userEmail} and user_city = #{userCity}
因为trim
标签设置了prefixOverrides=”and”,而上面的SQL前面有and语句,所以需要将上面的and语句删掉,又因为trim
标签设置了prefix=”where”,所以需要在拼接的SQL语句前面加一个where语句
最后trim
where
위의 SQL을 다음과 같이 변경합니다.where user_email = #{userEmail} and user_city = #{userCity}
where
태그의 if
태그가 조건을 충족하면 where 태그는 where 문으로 연결됩니다. <code>if
태그와 연결된 SQL의 앞에 and 문이 있으면 and가 삭제됩니다. 이 방법을 사용하면 SQL에서 불필요한 키워드가 자동으로 삭제되므로 일반적으로 태그와 where 태그를 조합하여 사용하는 경우가 많습니다. trim
trim
태그의 prefix
및 suffix
속성은 실제 SQL 문을 생성하는 데 사용됩니다. 태그 문장 접합 내부와 결합됩니다.
prefixOverrides
또는 suffixOverrides
속성에 지정된 값이 명령문 전후에 발견되면 MyBatis는 자동으로 해당 값을 삭제합니다. 여러 값을 지정할 때 후속 SQL과 연결되지 않도록 각 값 뒤에 공백을 두는 것을 잊지 마십시오.
접두사: 연결된 SQL 문에 접두사 추가 접미사: 연결된 SQL 문에 접미사 추가
prefixOverrides Strong>: 스플라이스 SQL 문 이전에prefixOverrides
가 발견되면 MyBatis는 자동으로 이를 삭제합니다
suffixOverrides: 스플라이스 이후에 suffixOverrides
가 발견되면 SQL 문, MyBatis가 자동으로 삭제합니다아래 trim
태그를 사용하여 where
태그의 기능을 구현하세요
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user <where> <choose> <when test="username != null and username != ''"> username = #{username} </when> <when test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </when> <when test="userCity != null and userCity != ''"> and user_city = #{userCity} </when> </choose> </where> </select>
태그 접합을 위한 SQL 문이 다음과 같습니다🎜<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">public int updateUser(User user);</pre><div class="contentsignin">로그인 후 복사</div></div>🎜<code>trim
태그가 prefixOverrides="and"로 설정되어 있고 위의 SQL에 and 문이 있으므로 앞에 있으므로 위와 문을 삭제해야 하며 trim
태그가 prefix="where"로 설정되어 있으므로 접합된 문 앞에 where 문을 추가해야 합니다. SQL 문🎜🎜마지막으로 trim
태그의 SQL 문이 아래와 같이 이어집니다🎜<update id="updateUser" parameterType="com.example.mybatis.entity.User"> update user <set> <if test="username != null and username != ''"> username=#{username}, </if> <if test="userEmail != null and userEmail != ''"> user_email=#{userEmail}, </if> <if test="userCity != null and userCity != ''"> user_city=#{userCity}, </if> <if test="age != null"> age=#{age} </if> </set> where id=#{id} </update>
public List<User> getUsersByIds(List<Integer> ids);
<!-- collection: 指定要遍历的集合 默认情况下 如果为Collection类型的,key为collection; 如果为List类型的,key为list 如果是数组类型,key为array 可以通过@Param("ids")来指定key item: 将当前遍历的元素赋值给指定的变量 open: 给遍历的结果添加一个开始字符 close: 给遍历的结果添加一个结束字符 separator: 每个元素之间的分隔符 --><select id="getUsersByIds" resultType="com.example.mybatis.entity.User"> select * from user where id in <foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach></select>
接口定义如下所示
public List<User> getUsersByIds(List<Integer> ids);
接口对应的 Mapper.xml 定义如下所示
<!-- collection: 指定要遍历的集合 默认情况下 如果为Collection类型的,key为collection; 如果为List类型的,key为list 如果是数组类型,key为array 可以通过@Param("ids")来指定key item: 将当前遍历的元素赋值给指定的变量 open: 给遍历的结果添加一个开始字符 close: 给遍历的结果添加一个结束字符 separator: 每个元素之间的分隔符 --><select id="getUsersByIds" resultType="com.example.mybatis.entity.User"> select * from user where id in <foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach></select>
用于批量插入
接口定义如下所示
public int addUserList(List<User> users);
接口对应的 Mapper.xml 定义如下所示
<insert id="addUserList" parameterType="com.example.mybatis.entity.User"> insert into user (username, user_email, user_city, age) values <foreach item="user" collection="list" separator=","> (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--返回自增主键--><insert id="addUserList" parameterType="com.example.mybatis.entity.User" useGeneratedKeys="true" keyProperty="id"> insert into user (username, user_email, user_city, age) values <foreach item="user" collection="list" separator=","> (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--还可以这样写--><!-- 这种方式需要数据库连接属性设置allowMultiQueries=true 这种分号分隔多个SQL还可以用于其他的批量操作,如修改、删除 --><insert id="addUserList" parameterType="com.example.mybatis.entity.User"> <foreach item="user" collection="list" separator=";"> insert into user (username, user_email, user_city, age) values (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--如果是Oracle数据库,则需要这样写--><insert id="addUserList" parameterType="com.example.mybatis.entity.User"> <foreach item="user" open="begin" close="end;" collection="list"> insert into user (username, user_email, user_city, age) values (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}); </foreach></insert>
위 내용은 MyBatis 동적 SQL 알아보기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









HQL과 SQL은 Hibernate 프레임워크에서 비교됩니다. HQL(1. 객체 지향 구문, 2. 데이터베이스 독립적 쿼리, 3. 유형 안전성), SQL은 데이터베이스를 직접 운영합니다(1. 데이터베이스 독립적 표준, 2. 복잡한 실행 파일) 쿼리 및 데이터 조작).

"OracleSQL의 나눗셈 연산 사용법" OracleSQL에서 나눗셈 연산은 일반적인 수학 연산 중 하나입니다. 데이터 쿼리 및 처리 중에 나누기 작업은 필드 간의 비율을 계산하거나 특정 값 간의 논리적 관계를 도출하는 데 도움이 될 수 있습니다. 이 문서에서는 OracleSQL의 나누기 작업 사용법을 소개하고 구체적인 코드 예제를 제공합니다. 1. OracleSQL의 두 가지 분할 연산 방식 OracleSQL에서는 두 가지 방식으로 분할 연산을 수행할 수 있습니다.

Oracle과 DB2는 일반적으로 사용되는 관계형 데이터베이스 관리 시스템으로, 각각 고유한 SQL 구문과 특성을 가지고 있습니다. 이 기사에서는 Oracle과 DB2의 SQL 구문을 비교 및 차이점을 설명하고 구체적인 코드 예제를 제공합니다. 데이터베이스 연결 Oracle에서는 다음 문을 사용하여 데이터베이스에 연결합니다. CONNECTusername/password@database DB2에서 데이터베이스에 연결하는 문은 다음과 같습니다. CONNECTTOdataba

MyBatis 동적 SQL 태그 해석: Set 태그 사용법에 대한 자세한 설명 MyBatis는 풍부한 동적 SQL 태그를 제공하고 데이터베이스 작업 명령문을 유연하게 구성할 수 있는 탁월한 지속성 계층 프레임워크입니다. 그 중 Set 태그는 업데이트 작업에서 매우 일반적으로 사용되는 UPDATE 문에서 SET 절을 생성하는 데 사용됩니다. 이 기사에서는 MyBatis에서 Set 태그의 사용법을 자세히 설명하고 특정 코드 예제를 통해 해당 기능을 보여줍니다. Set 태그란 무엇입니까? Set 태그는 MyBati에서 사용됩니다.

해결 방법: 1. 로그인한 사용자에게 데이터베이스에 액세스하거나 운영할 수 있는 충분한 권한이 있는지 확인하고 해당 사용자에게 올바른 권한이 있는지 확인하십시오. 2. SQL Server 서비스 계정에 지정된 파일에 액세스할 수 있는 권한이 있는지 확인하십시오. 3. 지정된 데이터베이스 파일이 다른 프로세스에 의해 열렸거나 잠겼는지 확인하고 파일을 닫거나 해제한 후 쿼리를 다시 실행하십시오. .관리자로 Management Studio를 실행해 보세요.

데이터베이스 기술 경쟁: Oracle과 SQL의 차이점은 무엇입니까? 데이터베이스 분야에서 Oracle과 SQL Server는 매우 존경받는 관계형 데이터베이스 관리 시스템입니다. 둘 다 관계형 데이터베이스 범주에 속하지만 둘 사이에는 많은 차이점이 있습니다. 이 기사에서는 Oracle과 SQL Server의 차이점과 실제 애플리케이션에서의 기능 및 장점을 자세히 살펴보겠습니다. 우선, Oracle과 SQL Server 사이에는 구문에 차이가 있습니다.

MyBatisGenerator는 MyBatis에서 공식적으로 제공하는 코드 생성 도구로, 개발자가 데이터베이스 테이블 구조에 맞는 JavaBeans, Mapper 인터페이스 및 XML 매핑 파일을 빠르게 생성할 수 있도록 도와줍니다. 코드 생성을 위해 MyBatisGenerator를 사용하는 과정에서 구성 매개변수 설정이 중요합니다. 이 글은 구성 매개변수의 관점에서 시작하여 MyBatisGenerator의 기능을 깊이 탐구할 것입니다.

MyBatis 캐싱 메커니즘 분석: 1단계 캐시와 2단계 캐시의 차이점 및 적용 MyBatis 프레임워크에서 캐싱은 데이터베이스 작업 성능을 효과적으로 향상시킬 수 있는 매우 중요한 기능입니다. 그중 1단계 캐시와 2단계 캐시는 MyBatis에서 일반적으로 사용되는 두 가지 캐싱 메커니즘입니다. 이 기사에서는 1차 수준 캐시와 2차 수준 캐시의 차이점과 적용을 자세히 분석하고 설명할 구체적인 코드 예제를 제공합니다. 1. 레벨 1 캐시 레벨 1 캐시는 로컬 캐시라고도 하며 기본적으로 활성화되어 있으며 끌 수 없습니다. 첫 번째 수준 캐시는 SqlSes입니다.
