pdf文档 MYBATIS Dynamic SQL

69.51 KB 5 页 0 评论
语言 格式 评分
英语
.pdf
3
摘要
http://www.tutorialspoint.com/mybatis/mybatis_dynamic_sql.htm Copyright © tutorialspoint.com MYBATIS - DYNAMIC SQL MYBATIS - DYNAMIC SQL Dynamic SQL is a very powerful feature of MyBatis. It enables programmers to build queries based on the scenario dynamically. For example, if you want to search the Student data base, based on the name of the student in MyBatis, you have to write the query using the dynamic SQL. MyBatis uses a powerful Dynamic SQL language that can be used within any mapped SQL statemen
AI总结
《MyBatis Dynamic SQL》 MyBatis 的动态 SQL 是一种强大的功能,允许开发人员根据实际场景动态构建查询语句。以下是 MyBatis 提供的基于 OGNL 的动态 SQL 表达式: * `if`:用于条件ally包含 WHERE 子句的一部分。 例如: ```xml ``` 如果 `name` 不为 `null`,则添加 `WHERE` 条件。 * `choose, when, otherwise`:类似于 Java 的 `switch` 语句,用于在多个选项中选择一个。 例如: ```xml ``` 根据条件选择不同的查询字段。 * `where`:自动处理 `WHERE` 子句,当包含的标签无内容时,不会生成 `WHERE`。 如果内容以 `AND` 或 `OR` 开头,则会自动去除。 例如: ```xml ``` * `foreach`:用于遍历集合,生成 `IN` 条件。 例如: ```xml ``` ### 示例 #### 数据库表 ```sql CREATE TABLE student ( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL ) ``` #### Student.xml ```xml ``` #### GetRecordByName.java ```java public class GetRecordByName { public static void main(String args[]) throws IOException { String req_name = "Mohammad"; Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); Student stud = new Student(); stud.setName(req_name); stud.setId(1); List student = session.selectList("getRecByName_Id", stud); for (Student st : student) { System.out.println("++++++++++++++ details of the student named Mohammad are ++++++++++++++++++++"); System.out.println("Id: " + st.getId()); System.out.println("Name: " + st.getName()); System.out.println("Branch: " + st.getBranch()); System.out.println("Percentage: " + st.getPercentage()); System.out.println("Email: " + st.getEmail()); System.out.println("Phone: " + st.getPhone()); } System.out.println("Records Read Successfully"); session.commit(); session.close(); } } ``` ### 编译和运行 1. 创建 Student.xml、Student.java 和 GetRecordByName.java 文件。 2. 确保已正确设置 PATH 和 CLASSPATH。 3. 编译并执行 GetRecordByName 类,将从 Student 表中读取记录。 ### 输出结果 ``` ++++++++++++++ details of the student named Mohammad are ++++++++++++++++++++ Id: 1 Name: Mohammad Branch: It Percentage: 80 Email: mohamad123@yahoo.com Phone: 90000000 Records Read Successfully ```
P1
P2
P3
P4
P5
下载文档到本地,方便使用
文档评分
请文明评论,理性发言.