架构设计
1661
具体操作
项目结构
引入项目依赖 pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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>com.imooc</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <repositories> <repository> <id>aliyun</id> <name>aliyun</name> <url>https://maven.aliyun.com/repository/public</url> </repository> </repositories> <!--引入MyBaties依赖--> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!--导入MySQL JDBC驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies> </project>
创建实体类(Entity) Goods.java
package com.imooc.mybatis.entity; import java.util.List; public class Goods { private Integer goodsId;//商品编号 private String title;//标题 private String subTitle;//子标题 private Float originalCost;//原始价格 private Float currentPrice;//当前价格 private Float discount;//折扣率 private Integer isFreeDelivery;//是否包邮 ,1-包邮 0-不包邮 private Integer categoryId;//分类编号 public Integer getGoodsId() { return goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubTitle() { return subTitle; } public void setSubTitle(String subTitle) { this.subTitle = subTitle; } public Float getOriginalCost() { return originalCost; } public void setOriginalCost(Float originalCost) { this.originalCost = originalCost; } public Float getCurrentPrice() { return currentPrice; } public void setCurrentPrice(Float currentPrice) { this.currentPrice = currentPrice; } public Float getDiscount() { return discount; } public void setDiscount(Float discount) { this.discount = discount; } public Integer getIsFreeDelivery() { return isFreeDelivery; } public void setIsFreeDelivery(Integer isFreeDelivery) { this.isFreeDelivery = isFreeDelivery; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } }
用 XML 方式创建映射器 goods.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="goods"> <select id="selectAll" resultType="com.imooc.mybatis.entity.Goods"> select * from t_goods order by goods_id desc limit 10 </select> </mapper>
创建数据库信息文件 db.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/babytun?useUnicode=true&characterEncoding=UTF-8 username=root password=19980617zqqxsc
创建MyBatis的配置文件 mybatis-config.xml
<?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="db.properties"/> <!--设置成支持驼峰命名--> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--设置默认指向的数据库--> <environments default="dev"> <!--配置环境,不同的环境不同的id名字--> <environment id="dev"> <!-- 采用JDBC方式对数据库事务进行commit/rollback --> <transactionManager type="JDBC"/> <!--采用连接池方式管理数据库连接--> <!--<dataSource type="POOLED">--> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> <environment id="prd"> <!-- 采用JDBC方式对数据库事务进行commit/rollback --> <transactionManager type="JDBC"/> <!--采用连接池方式管理数据库连接--> <dataSource type="POOLED"> <property value="com.mysql.jdbc.Driver" name="driver"/> <property value="jdbc:mysql://192.168.1.155:3306/babytun?useUnicode=true&characterEncoding=UTF-8" name="url"/> <property value="root" name="username"/> <property value="root" name="password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/goods.xml"></mapper> </mappers> </configuration>
创建MyBatis的工具类 MyBatisUtils.java
package com.imooc.mybatis.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.Reader; /** * @Auther 徐士成 * @Date 2021-06-21 16:47 */ public class MyBatisUtils { //利用static(静态)属于类不属于对象,且全局唯一 private static SqlSessionFactory sqlSessionFactory = null; //利用静态块在初始化类时实例化sqlSessionFactory static { Reader reader = null; try { reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); //初始化错误时,通过抛出异常ExceptionInInitializerError通知调用者 throw new ExceptionInInitializerError(e); } } /** * openSession 创建一个新的SqlSession对象 * @return SqlSession对象 */ public static SqlSession openSession(){ return sqlSessionFactory.openSession(); } /** * 释放一个有效的SqlSession对象 * @param session 准备释放SqlSession对象 */ public static void closeSession(SqlSession session){ if(session != null){ session.close(); } } }
通过Junit依赖进行查询测试
package com.imooc.mabatis; import com.imooc.mybatis.entity.Goods; import com.imooc.mybatis.utils.MyBatisUtils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.util.List; /** * @Auther 徐士成 * @Date 2021-06-21 15:13 */ public class MyBatisTest { @Test public void testSelectGoods(){ SqlSession sqlSession = null; try { sqlSession = MyBatisUtils.openSession(); // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id List<Goods> list = sqlSession.selectList("goods.selectAll"); for (Goods goods : list) { System.out.println(goods.getTitle()); } } catch (Exception e) { throw e; } finally { MyBatisUtils.closeSession(sqlSession); } } }
数据库goods表创建语句
create table t_goods ( goods_id int auto_increment comment '商品编号' primary key, title varchar(128) not null comment '商品名称', sub_title varchar(256) null comment '子标题', original_cost float not null comment '原价', current_price float not null comment '折后价', discount float not null comment '折扣(0~1)', is_free_delivery int not null comment '是否包邮', category_id int default 0 not null )
执行结果
![[_8T2ILY8@F20Q@UCIG]TK