MyBatis_通过映射器(接口)绑定映射语句
一、文件格式
二、数据库
三、代码
1 package mybatis.entity; 2 3 public class Entity { 4 private int id; 5 private String name; 6 private String sex; 7 @Override 8 public String toString() { 9 return "Entity [id=" + id + ", name=" + name + ", sex=" + sex + "]"; 10 } 11 public Entity(int id, String name, String sex) { 12 super(); 13 this.id = id; 14 this.name = name; 15 this.sex = sex; 16 } 17 public Entity() { 18 super(); 19 } 20 public int getId() { 21 return id; 22 } 23 public void setId(int id) { 24 this.id = id; 25 } 26 public String getName() { 27 return name; 28 } 29 public void setName(String name) { 30 this.name = name; 31 } 32 public String getSex() { 33 return sex; 34 } 35 public void setSex(String sex) { 36 this.sex = sex; 37 } 38 39 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 <mapper namespace="mybatis.mapper.PerMapper"> 5 <resultMap id="ResultMap" type="Entity"> 6 <!-- 映射主键 --> 7 <id property="id" column="qid"></id> 8 <!-- 非主键字段 --> 9 <result property="name" column="qname"></result> 10 <result property="sex" column="qsex"></result> 11 </resultMap> 12 <!-- 添加信息 --> 13 <insert id="insert"> 14 INSERT INTO person2 VALUES(4,'d') 15 </insert> 16 <!-- 传参信息 --> 17 <insert id="insertParams" parameterType="Entity"> 18 INSERT INTO person2 19 VALUES(#{id},#{name},#{sex}) 20 </insert> 21 <!-- 固定删除 --> 22 <delete id="delPer"> 23 delete from person2 where id=4 24 </delete> 25 <delete id="delById" parameterType="int"> 26 delete from person2 where id=#{n} 27 </delete> 28 <update id="updById" parameterType="Entity"> 29 update person2 set name=#{name} where id=#{id} 30 </update> 31 <!-- 查询全部 --> 32 <select id="selectPer" resultType="mybatis.entity.Entity"> 33 select * from person2 34 </select> 35 <!-- 按ID查询 --> 36 <select id="selectById" resultType="mybatis.entity.Entity" 37 parameterType="int"> 38 <!-- i:参数变量名 --> 39 select * from person2 where id=2 40 </select> 41 <!-- 查询全部 --> 42 <select id="selectAll" resultType="Entity"> 43 select * from person2 44 </select> 45 <!-- ResultMap ByID查询 ,此时结果集中的字段名称与实体类中的成员变量名称不匹配,导致查询不到结果 --> 46 <select id="selectByResultMapNameNotSame" parameterType="int" 47 resultMap="ResultMap"> 48 SELECT id AS qid,name AS qname,sex as qsex FROM 49 person2 50 WHERE 51 id=#{n} 52 </select> 53 <!-- 模糊查询 --> 54 <select id="selectByLike" resultType="Entity" parameterType="String"> 55 select * from person2 where name like CONCAT('%',#{keyword},'%') 56 </select> 57 <!-- 模糊查询 --> 58 <select id="selectByLikeTwo" parameterType="Entity" resultType="Entity"> 59 SELECT * FROM person2 WHERE name LIKE '%${name}%' 60 </select> 61 </mapper>
1 package mybatis.mapper; 2 3 import java.util.List; 4 5 import mybatis.entity.Entity; 6 7 /** 8 * 定义一个映射器 9 * 1.映射文件(mybatis/entity/EntityMapper.xml)中的namespace的值修改成映射器的完全限定名 10 * 2.映射器中方法的名称与映射文件中的节点的id值一致,参数和返回类型也一致 11 */ 12 public interface PerMapper { 13 /**模糊查询*/ 14 /*<!-- 模糊查询 --> 15 id="selectByLikeTwo" -> 函数名 16 parameterType="Entity" -> 参数类型 17 resultType="Entity" -> 返回值类型 18 /**添加人物*/ 19 public List<Entity> selectByLikeTwo(Entity en); 20 public int insertParams(Entity en); 21 }
1 package mybatis.test; 2 3 import java.util.List; 4 import org.apache.ibatis.session.SqlSession; 5 import org.apache.ibatis.session.SqlSessionFactory; 6 import org.junit.Before; 7 import org.junit.Test; 8 import mybatis.entity.Entity; 9 import mybatis.mapper.PerMapper; 10 import mybatis.util.SqlSessionFactoryUtil; 11 12 public class TestMybatis { 13 public SqlSessionFactory sqlSessionFactory = null; 14 15 @Before 16 public void init() { 17 sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactoryInstance(); 18 } 19 20 @Test 21 public void selectByLikeTwo() { 22 SqlSession session = sqlSessionFactory.openSession(); 23 // 3 24 PerMapper mapper = session.getMapper(PerMapper.class); 25 Entity en = new Entity(); 26 en.setName("孙"); 27 28 List<Entity> list = mapper.selectByLikeTwo(en); 29 for (Entity e : list) { 30 System.out.println(e); 31 } 32 session.close(); 33 } 34 35 // 36 @Test 37 public void insertParams() { 38 SqlSession session = sqlSessionFactory.openSession(); 39 // 3 40 PerMapper mapper = session.getMapper(PerMapper.class); 41 Entity en = new Entity(); 42 en.setId(201); 43 en.setName("克林"); 44 en.setSex("男"); 45 46 int flag = mapper.insertParams(en); 47 System.out.println(flag); 48 session.commit(); 49 session.close(); 50 } 51 }
1 package mybatis.util; 2 3 import java.io.IOException; 4 import java.io.Reader; 5 6 import org.apache.ibatis.io.Resources; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9 10 /** 通过单例模式管理SqlSessionFactory对象 */ 11 public class SqlSessionFactoryUtil { 12 private SqlSessionFactoryUtil() { 13 } 14 15 /* 恶汉式 */ 16 private static SqlSessionFactory sqlSessionFactory; 17 static { 18 Reader reader; 19 try { 20 reader = Resources.getResourceAsReader("mybatisConfig.xml"); 21 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 22 sqlSessionFactory = builder.build(reader); 23 } catch (IOException e) { 24 e.printStackTrace(); 25 } 26 } 27 public static SqlSessionFactory getSqlSessionFactoryInstance() { 28 return sqlSessionFactory; 29 } 30 /* 31 * 懒汉式: 32 * private static SqlSessionFactory sqlSessionFactory = null; 33 * //synchronized 防并发 34 * public synchronized static SqlSessionFactory getSqlSessionFactoryInstance() { 35 * if (sqlSessionFactory != null) { 36 * return sqlSessionFactory; 37 * } else { 38 Reader reader; 39 try { 40 reader = Resources.getResourceAsReader("mybatisConfig.xml"); 41 SqlSessionFactoryBuilder 42 builder = new SqlSessionFactoryBuilder(); 43 sqlSessionFactory = builder.build(reader); 44 } catch (IOException e) { 45 e.printStackTrace(); } 46 return sqlSessionFactory; 47 * } 48 * } 49 */ 50 }
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai username=root password=123456
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置属性 --> <properties resource="config.properties" /> <!-- 设置实体类别名 _ *** --> <typeAliases> <typeAlias alias="Entity" type="mybatis.entity.Entity" /> </typeAliases> <!-- 配置数据库连接环境(支持多个数据库连接) --> <environments default="development"> <!-- 数据库连接 --> <environment id="development"> <!-- 配置事务管理器,JDBC:按照jdbc方式处理事务 --> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息,POOLED:表示以数据库连接池的形式连接数据库 --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 在任意时间可以存在的活动(也就是正在使用)连接数量,默认值:10 --> <property name="poolMaximumActiveConnections" value="300" /> <!-- 任意时间可能存在的空闲连接数 默认是5,最好设置为0,否则可能会崩溃掉 --> <property name="poolMaximumIdleConnections" value="0" /> <!-- 在被强制返回之前,池中连接被检出(checked out)时间,默认值:20000 毫秒(即 20 秒) --> <property name="poolMaximumCheckoutTime" value="20000" /> <!-- 这是一个底层设置,如果获取连接花费的相当长的时间,它会给连接池打印状态日志并重新尝试获取一个连接(避免在误配置的情况下一直安静的失败),默认值:20000 毫秒(即 20 秒)。 --> <property name="poolTimeToWait" value="20000" /> <!-- 是否启用侦测查询。若开启,也必须使用一个可执行的 SQL 语句设置 poolPingQuery 属性(最好是一个非常快的 SQL),默认值:false。 --> <property name="poolPingEnabled" value="true" /> <!-- 配置 poolPingQuery 的使用频度。这可以被设置成匹配具体的数据库连接超时时间,来避免不必要的侦测,默认值:0(即所有连接每一时刻都被侦测 — 当然仅当 poolPingEnabled 为 true 时适用) --> <property name="poolPingConnectionsNotUsedFor" value="3600000" /> <!-- 发送到数据库的侦测查询,用来检验连接是否处在正常工作秩序中并准备接受请求。默认是“NO PING QUERY SET”,这会导致多数数据库驱动失败时带有一个恰当的错误消息。 --> <property name="poolPingQuery" value="select 1" /> </dataSource> </environment> </environments> <!-- 加载映射文件 --> <mappers> <mapper resource="mybatis/entity/EntityMapper.xml" /> </mappers> </configuration>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mybatis</groupId> <artifactId>Test</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.0.4</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project>