具体操作
项目结构
![RZT5[0XG]Z}XRL{3YL9NI_U](https://img-hello-world.oss-cn-beijing.aliyuncs.com/imgs/437d7ed2c28ec2fafac0a4ba2313bdff.png)
引入项目依赖 pom.xml
1<?xml version="1.0" encoding="UTF-8"?> 2<project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.imooc</groupId> 8 <artifactId>mybatis</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <properties> 12 <maven.compiler.source>8</maven.compiler.source> 13 <maven.compiler.target>8</maven.compiler.target> 14 </properties> 15 16 <repositories> 17 <repository> 18 <id>aliyun</id> 19 <name>aliyun</name> 20 <url>https://maven.aliyun.com/repository/public</url> 21 </repository> 22 </repositories> 23 24 <!--引入MyBaties依赖--> 25 <dependencies> 26 <dependency> 27 <groupId>org.mybatis</groupId> 28 <artifactId>mybatis</artifactId> 29 <version>3.5.7</version> 30 </dependency> 31 <!--导入MySQL JDBC驱动--> 32 <dependency> 33 <groupId>mysql</groupId> 34 <artifactId>mysql-connector-java</artifactId> 35 <version>8.0.25</version> 36 </dependency> 37 38 <dependency> 39 <groupId>junit</groupId> 40 <artifactId>junit</artifactId> 41 <version>4.13.2</version> 42 </dependency> 43 <dependency> 44 <groupId>junit</groupId> 45 <artifactId>junit</artifactId> 46 <version>4.13.2</version> 47 <scope>test</scope> 48 </dependency> 49 </dependencies> 50 51 52 53</project>
创建实体类(Entity) Goods.java
1package com.imooc.mybatis.entity; 2 3import java.util.List; 4 5public class Goods { 6 private Integer goodsId;//商品编号 7 private String title;//标题 8 private String subTitle;//子标题 9 private Float originalCost;//原始价格 10 private Float currentPrice;//当前价格 11 private Float discount;//折扣率 12 private Integer isFreeDelivery;//是否包邮 ,1-包邮 0-不包邮 13 private Integer categoryId;//分类编号 14 15 public Integer getGoodsId() { 16 return goodsId; 17 } 18 19 public void setGoodsId(Integer goodsId) { 20 this.goodsId = goodsId; 21 } 22 23 public String getTitle() { 24 return title; 25 } 26 27 public void setTitle(String title) { 28 this.title = title; 29 } 30 31 public String getSubTitle() { 32 return subTitle; 33 } 34 35 public void setSubTitle(String subTitle) { 36 this.subTitle = subTitle; 37 } 38 39 public Float getOriginalCost() { 40 return originalCost; 41 } 42 43 public void setOriginalCost(Float originalCost) { 44 this.originalCost = originalCost; 45 } 46 47 public Float getCurrentPrice() { 48 return currentPrice; 49 } 50 51 public void setCurrentPrice(Float currentPrice) { 52 this.currentPrice = currentPrice; 53 } 54 55 public Float getDiscount() { 56 return discount; 57 } 58 59 public void setDiscount(Float discount) { 60 this.discount = discount; 61 } 62 63 public Integer getIsFreeDelivery() { 64 return isFreeDelivery; 65 } 66 67 public void setIsFreeDelivery(Integer isFreeDelivery) { 68 this.isFreeDelivery = isFreeDelivery; 69 } 70 71 public Integer getCategoryId() { 72 return categoryId; 73 } 74 75 public void setCategoryId(Integer categoryId) { 76 this.categoryId = categoryId; 77 } 78 79} 80
用 XML 方式创建映射器 goods.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<mapper namespace="goods"> 6 7 <select id="selectAll" resultType="com.imooc.mybatis.entity.Goods"> 8 select * from t_goods order by goods_id desc limit 10 9 </select> 10 11</mapper>
创建数据库信息文件 db.properties
1driver=com.mysql.cj.jdbc.Driver 2url=jdbc:mysql://localhost:3306/babytun?useUnicode=true&characterEncoding=UTF-8 3username=root 4password=19980617zqqxsc
创建MyBatis的配置文件 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<configuration> 6 <properties resource="db.properties"/> 7 <!--设置成支持驼峰命名--> 8 <settings> 9 <setting name="mapUnderscoreToCamelCase" value="true"/> 10 </settings> 11 <!--设置默认指向的数据库--> 12 <environments default="dev"> 13 <!--配置环境,不同的环境不同的id名字--> 14 <environment id="dev"> 15 <!-- 采用JDBC方式对数据库事务进行commit/rollback --> 16 <transactionManager type="JDBC"/> 17 <!--采用连接池方式管理数据库连接--> 18 <!--<dataSource type="POOLED">--> 19 <dataSource type="POOLED"> 20 <property name="driver" value="${driver}"/> 21 <property name="url" value="${url}"/> 22 <property name="username" value="${username}"/> 23 <property name="password" value="${password}"/> 24 </dataSource> 25 </environment> 26 <environment id="prd"> 27 <!-- 采用JDBC方式对数据库事务进行commit/rollback --> 28 <transactionManager type="JDBC"/> 29 <!--采用连接池方式管理数据库连接--> 30 <dataSource type="POOLED"> 31 <property value="com.mysql.jdbc.Driver" name="driver"/> 32 <property value="jdbc:mysql://192.168.1.155:3306/babytun?useUnicode=true&characterEncoding=UTF-8" 33 name="url"/> 34 <property value="root" name="username"/> 35 <property value="root" name="password"/> 36 </dataSource> 37 </environment> 38 </environments> 39 40 <mappers> 41 <mapper resource="mappers/goods.xml"></mapper> 42 </mappers> 43</configuration>
创建MyBatis的工具类 MyBatisUtils.java
1package com.imooc.mybatis.utils; 2 3import org.apache.ibatis.io.Resources; 4import org.apache.ibatis.session.SqlSession; 5import org.apache.ibatis.session.SqlSessionFactory; 6import org.apache.ibatis.session.SqlSessionFactoryBuilder; 7 8import java.io.IOException; 9import java.io.Reader; 10 11/** 12 * @Auther 徐士成 13 * @Date 2021-06-21 16:47 14 */ 15public class MyBatisUtils { 16 //利用static(静态)属于类不属于对象,且全局唯一 17 private static SqlSessionFactory sqlSessionFactory = null; 18 //利用静态块在初始化类时实例化sqlSessionFactory 19 static { 20 Reader reader = null; 21 try { 22 reader = Resources.getResourceAsReader("mybatis-config.xml"); 23 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 24 } catch (IOException e) { 25 e.printStackTrace(); 26 //初始化错误时,通过抛出异常ExceptionInInitializerError通知调用者 27 throw new ExceptionInInitializerError(e); 28 } 29 } 30 /** 31 * openSession 创建一个新的SqlSession对象 32 * @return SqlSession对象 33 */ 34 public static SqlSession openSession(){ 35 return sqlSessionFactory.openSession(); 36 } 37 38 /** 39 * 释放一个有效的SqlSession对象 40 * @param session 准备释放SqlSession对象 41 */ 42 public static void closeSession(SqlSession session){ 43 if(session != null){ 44 session.close(); 45 } 46 } 47 48} 49
通过Junit依赖进行查询测试
1package com.imooc.mabatis; 2 3import com.imooc.mybatis.entity.Goods; 4import com.imooc.mybatis.utils.MyBatisUtils; 5import org.apache.ibatis.io.Resources; 6import org.apache.ibatis.session.SqlSession; 7import org.apache.ibatis.session.SqlSessionFactory; 8import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9import org.junit.Test; 10 11import java.io.IOException; 12import java.io.Reader; 13import java.sql.Connection; 14import java.util.List; 15 16/** 17 * @Auther 徐士成 18 * @Date 2021-06-21 15:13 19 */ 20public class MyBatisTest { 21 @Test 22 public void testSelectGoods(){ 23 SqlSession sqlSession = null; 24 try { 25 sqlSession = MyBatisUtils.openSession(); 26 // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id 27 List<Goods> list = sqlSession.selectList("goods.selectAll"); 28 for (Goods goods : list) { 29 System.out.println(goods.getTitle()); 30 } 31 } catch (Exception e) { 32 throw e; 33 } finally { 34 MyBatisUtils.closeSession(sqlSession); 35 } 36 } 37} 38
数据库goods表创建语句
1create table t_goods 2( 3 goods_id int auto_increment comment '商品编号' 4 primary key, 5 title varchar(128) not null comment '商品名称', 6 sub_title varchar(256) null comment '子标题', 7 original_cost float not null comment '原价', 8 current_price float not null comment '折后价', 9 discount float not null comment '折扣(0~1)', 10 is_free_delivery int not null comment '是否包邮', 11 category_id int default 0 not null 12)
执行结果
![[_8T2ILY8@F20Q@UCIG]TK
