1. 程式人生 > >MyBatis基礎入門《十七》動態SQL

MyBatis基礎入門《十七》動態SQL

MyBatis基礎入門《十七》動態SQL

描述:

  >> 完成多條件查詢等邏輯實現

  >> 用於實現動態SQL的元素主要有:

    > if

    > trim

    > where

    > set

    > choose( when , otherwise )

    > foreach

  動態SQL為Mybatis重要部分,專案也重新新建了一個:mybatis-dynamic-sql

專案結構:

 

 

TblClient.java

 1 package
com.charles.entity; 2 3 import java.io.Serializable; 4 import java.util.Date; 5 6 public class TblClient implements Serializable { 7 8 private static final long serialVersionUID = -5993993584624176849L; 9 10 private Integer cid; 11 private String cname; 12 private String caddress;
13 private Date cbirthday; 14 15 public TblClient() { 16 17 } 18 19 public Integer getCid() { 20 return cid; 21 } 22 23 public void setCid(Integer cid) { 24 this.cid = cid; 25 } 26 27 public String getCname() { 28 return cname; 29 } 30 31
public void setCname(String cname) { 32 this.cname = cname; 33 } 34 35 public String getCaddress() { 36 return caddress; 37 } 38 39 public void setCaddress(String caddress) { 40 this.caddress = caddress; 41 } 42 43 public Date getCbirthday() { 44 return cbirthday; 45 } 46 47 public void setCbirthday(Date cbirthday) { 48 this.cbirthday = cbirthday; 49 } 50 }

 

ClientMapper.java

 1 package com.charles.mapper;
 2 
 3 import java.util.List;
 4 
 5 import com.charles.entity.TblClient;
 6 
 7 public interface ClientMapper {
 8 
 9     /***
10      * 注意這個名字,必須要和ClientMapper.xml檔案中的select標籤id屬性值一樣。
11      * @return List<TblClient> 集合
12      */
13     public List<TblClient> getClientAll();
14     
15 }

 

ClientMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 
 6 <mapper namespace="com.charles.mapper.ClientMapper">
 7  
 8     <resultMap type="com.charles.entity.TblClient" id="tblClientID">
 9         <id property="cid" column="id" />
10         <result property="cname" column="client_name"/>
11         <result property="caddress" column="client_address"/>
12         <result property="cbirthday" column="client_birthday"/>
13     </resultMap>    
14     
15     <select id="getClientAll" resultMap="tblClientID">
16         SELECT 
17                 id ,
18                 client_name ,
19                 client_address ,
20                 client_birthday 
21         FROM tbl_client 
22     </select>
23      
24 </mapper>

 

 MyBatisUtil.java

 1 package com.charles.util;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 
11 public class MyBatisUtil {
12 
13     private static SqlSessionFactory factory = null;
14     
15     /** 在靜態程式碼塊下,factory只會被建立一次 **/
16     static {
17         try {
18             InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
19             factory = new SqlSessionFactoryBuilder().build(inputStream);
20         } catch (IOException e) {
21             e.printStackTrace();
22         }
23     }
24     
25     // 獲取factory
26     public static SqlSessionFactory getSessionFactory() {
27         
28         return factory;
29     }
30     
31     /**
32      * 獲取SQLSession方法
33      * 
34      * @return SQLSession 
35      **/
36     public static SqlSession getSqlSession() {
37         
38         // 開啟事物
39         return factory.openSession(false);
40     }
41     
42     /**
43      * 關閉SQLSession方法
44      * 
45      * @param SQLSession物件
46      */
47     public static void closeSqlSession(SqlSession sqlSession) {
48         
49         if (sqlSession != null) {
50             sqlSession.close();
51         }
52     }
53 }

 

mybatis-config.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 
 6 <configuration>
 7 
 8     <!-- 
 9         注意:
10             這個配置檔案的標籤是有順序的,必須按照這個順序書寫。
11             例如:settings標籤就必須放在properties標籤的後面。
12      -->
13 
14     <!-- 引入database.properties檔案 -->
15     <properties resource="properties/database.properties"></properties>
16 
17     <!-- 配置mybatis的log實現log4j -->
18     <settings>
19         <setting name="logImpl" value="STDOUT_LOGGING" />
20     </settings>
21 
22     <!-- 配置別名 -->
23     <typeAliases>
24         <typeAlias type="com.charles.entity.TblClient" alias="baitang" />
25     </typeAliases>
26 
27     <!-- 配置Mybatis的環境 -->
28     <environments default="development">
29         <environment id="development">
30             <!-- 配置事物管理 -->
31             <transactionManager type="JDBC" />
32             <dataSource type="POOLED">
33                 <property name="driver" value="${jdbc.driver}" />
34                 <property name="url" value="${jdbc.url}" />
35                 <property name="username" value="${jdbc.username}" />
36                 <property name="password" value="${jdbc.password}" />
37             </dataSource>
38         </environment>
39     </environments>
40 
41     <!-- 將Mapper檔案加入到mybatis的配置檔案中 -->
42     <mappers>
43         <mapper resource="com/charles/mapper/ClientMapper.xml" />
44     </mappers>
45 
46 
47 </configuration>

 

database.properties

jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://IP地址:3306/test
jdbc.url=jdbc:mysql://IP地址:3306/test
jdbc.username=charles
jdbc.password=charles

 

lo4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.charles=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

 

JunitSelect.java

 1 package com.charles.junit;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.session.SqlSession;
 6 import org.junit.Test;
 7 
 8 import com.charles.entity.TblClient;
 9 import com.charles.mapper.ClientMapper;
10 import com.charles.util.MyBatisUtil;
11 
12 public class JunitSelect {
13 
14     @Test
15     public void selectif() {
16 
17         /** 1. 獲取SQLSession **/
18         SqlSession session = MyBatisUtil.getSqlSession();
19 
20         /** 2. 排程方法,從資料庫中獲取資料 **/
21         List<TblClient> list = session.getMapper(ClientMapper.class).getClientAll();
22 
23         /** 3. 關閉SQLSession **/
24         MyBatisUtil.closeSqlSession(session);
25 
26         for (TblClient client : list) {
27             System.out.println(client.getCid() + "\t" + client.getCname() + "\t" + client.getCaddress() + "\t"
28                     + client.getCbirthday());
29         }
30     }
31 }

 

pom.xml

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 3     <modelVersion>4.0.0</modelVersion>
 4     <groupId>com.charles.mybatis</groupId>
 5     <artifactId>mybatis-dynamic-sql</artifactId>
 6     <version>0.0.1-SNAPSHOT</version>
 7 
 8     <dependencies>
 9         <dependency>
10             <groupId>junit</groupId>
11             <artifactId>junit</artifactId>
12             <version>4.11</version>
13         </dependency>
14         <dependency>
15             <groupId>log4j</groupId>
16             <artifactId>log4j</artifactId>
17             <version>1.2.17</version>
18         </dependency>
19         <dependency>
20             <groupId>org.mybatis</groupId>
21             <artifactId>mybatis</artifactId>
22             <version>3.4.6</version>
23         </dependency>
24         <dependency>
25             <groupId>mysql</groupId>
26             <artifactId>mysql-connector-java</artifactId>
27             <version>5.1.29</version>
28         </dependency>
29     </dependencies>
30 
31 
32 </project>

 

執行測試程式碼:JunitSelect.java 的測試結果:

 

如有問題,歡迎糾正!!!

如有轉載,請標明源處: https://www.cnblogs.com/Charles-Yuan/p/9902779.html