MyBatis基础入门《二》Select查询
MyBatis基础入门《二》Select查询
使用MySQL数据库,创建表:
1 SET NAMES utf8mb4; 2 SET FOREIGN_KEY_CHECKS = 0; 3 4 -- ---------------------------- 5 -- Table structure for tbl_client_copy1 6 -- ---------------------------- 7 DROP TABLE IF EXISTS `tbl_client_copy1`; 8 CREATE TABLE `tbl_client_copy1` ( 9 `id` int(5) NOT NULL AUTO_INCREMENT, 10 `client_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL, 11 `client_address` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL, 12 `client_birthday` datetime NULL DEFAULT NULL, 13 PRIMARY KEY (`id`) USING BTREE 14 ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Compact; 15 16 SET FOREIGN_KEY_CHECKS = 1;
项目工程:
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.dao.ClientMapper"> 7 8 <!-- 查询数据库 --> 9 <select id="getCount" resultType="int"> 10 SELECT COUNT(*) FROM tbl_client 11 </select> 12 13 </mapper>
TblClient.java
1 package com.charles.entity; 2 3 import java.io.Serializable; 4 5 public class TblClient implements Serializable { 6 7 private static final long serialVersionUID = -5993993584624176849L; 8 9 private Integer cid; 10 private String cname; 11 private String caddress; 12 private String cbirthday; 13 14 public TblClient() { 15 } 16 17 public Integer getCid() { 18 return cid; 19 } 20 21 public void setCid(Integer cid) { 22 this.cid = cid; 23 } 24 25 public String getCname() { 26 return cname; 27 } 28 29 public void setCname(String cname) { 30 this.cname = cname; 31 } 32 33 public String getCaddress() { 34 return caddress; 35 } 36 37 public void setCaddress(String caddress) { 38 this.caddress = caddress; 39 } 40 41 public String getCbirthday() { 42 return cbirthday; 43 } 44 45 public void setCbirthday(String cbirthday) { 46 this.cbirthday = cbirthday; 47 } 48 49 }
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 <!-- 引入database.properties文件 --> 9 <properties resource="properties/database.properties"></properties> 10 11 <!-- 配置mybatis的log实现log4j --> 12 <settings> 13 <setting name="logImpl" value="STDOUT_LOGGING" /> 14 </settings> 15 16 <!-- 配置Mybatis的环境 --> 17 <environments default="development"> 18 <environment id="development"> 19 <!-- 配置事物管理 --> 20 <transactionManager type="JDBC" /> 21 <dataSource type="POOLED"> 22 <property name="driver" value="${jdbc.driver}" /> 23 <property name="url" value="${jdbc.url}" /> 24 <property name="username" value="${jdbc.username}" /> 25 <property name="password" value="${jdbc.password}" /> 26 </dataSource> 27 </environment> 28 </environments> 29 30 <!-- 将Mapper文件加入到mybatis的配置文件中 --> 31 <mappers> 32 <mapper resource="com/charles/dao/ClientMapper.xml" /> 33 </mappers> 34 35 36 </configuration>
database.properties
这个是链接数据库的配置,未做改动,不在显示:见《Mybatis基础入门《一》环境搭建》
log4j.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
JunitMybatisConfig.java
1 package com.charles.junit; 2 3 import static org.junit.Assert.fail; 4 5 import java.io.IOException; 6 import java.io.InputStream; 7 8 import org.apache.ibatis.io.Resources; 9 import org.apache.ibatis.session.SqlSession; 10 import org.apache.ibatis.session.SqlSessionFactory; 11 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 12 import org.apache.log4j.Logger; 13 import org.apache.log4j.PropertyConfigurator; 14 import org.junit.Test; 15 16 public class JunitMybatisConfig { 17 18 @Test 19 public void test() { 20 fail("Not yet implemented"); 21 } 22 23 @Test 24 public void testLog4j() { 25 PropertyConfigurator.configure("D:/DISK WORKSPACE/STS MAVEN/mybatis-base/src/main/resources/lo4j.properties"); 26 Logger logger = Logger.getLogger(JunitMybatisConfig.class); 27 logger.debug(" debug "); 28 logger.error(" error "); 29 } 30 31 @Test 32 public void testMybaits() { 33 34 try { 35 /** 1.获取mybatis-config.xml文件 **/ 36 String resource = "mybatis/mybatis-config.xml"; 37 InputStream is = Resources.getResourceAsStream(resource); 38 39 /** 2.创建SQLSessionFactory对象 **/ 40 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); 41 42 /** 3.创建SQLSession **/ 43 SqlSession session = sqlSessionFactory.openSession(); 44 45 /** 4.输出SQLSession对象 **/ 46 System.out.println(session); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } 50 } 51 }
注意:
sqlSessionFactory.openSession(boolean autoCommit); 这里的openSession的方法中有一个boolean类型的参数。
true:关闭事物控制(默认)
false:开启事物控制
JunitMybatisSelect.java
1 package com.charles.junit; 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 import org.junit.Test; 11 12 public class JunitMybatisSelect { 13 14 @Test 15 public void junitSelect() { 16 SqlSession session = null; 17 try { 18 /** 1.获取mybatis-config.xml文件 **/ 19 String resource = "mybatis/mybatis-config.xml"; 20 InputStream is = Resources.getResourceAsStream(resource); 21 22 /** 2.创建SQLSessionFactory对象 **/ 23 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); 24 25 /** 3.创建SQLSession **/ 26 session = sqlSessionFactory.openSession(); 27 28 /** 4.输出SQLSession对象 **/ 29 System.out.println(session); 30 String resoruce = "com.charles.dao.ClientMapper.getCount"; 31 int count = session.selectOne(resoruce); 32 System.out.println(count); 33 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } finally { 37 if(null != session) { 38 session.close(); 39 } 40 } 41 } 42 }
注意:
String resource = "com.charles.dao.ClientMapper.getCount", 这个不是随便写的,这是由:ClientMapper.xml 文件中的namespace + select标签ID的值 组成。
SQLSession的使用方式有两种:
1. 通过SQLSession的实例直接运行映射的SQL语句。
2. 基于Mapper接口方式操作数据。
由于是初步搭建学习MyBatis,这里我使用的是第一种。一步一步的深入,后面会改成第二种方式。
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-base</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.slf4j</groupId> --> 21 <!-- <artifactId>slf4j-api</artifactId> --> 22 <!-- <version>1.7.7</version> --> 23 <!-- </dependency> --> 24 <!-- <dependency> --> 25 <!-- <groupId>org.slf4j</groupId> --> 26 <!-- <artifactId>slf4j-log4j12</artifactId> --> 27 <!-- <version>1.7.7</version> --> 28 <!-- </dependency> --> 29 <dependency> 30 <groupId>org.mybatis</groupId> 31 <artifactId>mybatis</artifactId> 32 <version>3.4.6</version> 33 </dependency> 34 <dependency> 35 <groupId>mysql</groupId> 36 <artifactId>mysql-connector-java</artifactId> 37 <version>5.1.29</version> 38 </dependency> 39 </dependencies> 40 41 </project>
如有问题,欢迎纠正!!!
如有转载,请标明源处:https://www.cnblogs.com/Charles-Yuan/p/9861099.html