文章目录
- products.sql
- pom.xml
- mybatis-config.xml
- ProductsMapper.xml
- Products.java
- PhoneDto.java
- ProductsMapper.java
- DButil.java
- ProductsMapperTest
products.sql
create table products
(product_id int auto_increment comment '产品ID'primary key,product_name varchar(100) null comment '产品名称',brand varchar(50) null comment '品牌',price decimal(10, 2) null comment '价格',color varchar(20) null comment '颜色',storage_capacity varchar(10) null comment '存储容量',description text null comment '描述'
)comment '手机产品表';
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.aistat</groupId><artifactId>mybatis_tech</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.0.31</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.15</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.14.8</version><scope>provided</scope></dependency></dependencies></project>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/><setting name="logImpl" value="STDOUT_LOGGING"/></settings><typeAliases><package name="com.aistart.tech.pojo"/></typeAliases>
<environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatisdb"/><property name="username" value="root"/><property name="password" value="root"/><property name="poolMaximumActiveConnections" value="1"/></dataSource></environment><environment id="testdevelopment"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper class="com.aistart.tech.mapper.ProductsMapper"/></mappers>
</configuration>
ProductsMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aistart.tech.mapper.ProductsMapper"><sql id="all">product_id, product_name, brand, price, color, storage_capacity, description</sql><resultMap id="selectOneMap" type="com.aistart.tech.dto.PhoneDto"><result column="product_name" property="name"></result><result column="price" property="jg"></result></resultMap><sql id="select">select <include refid="all"></include> from productswhere</sql><select id="selectOneMap" resultMap="selectOneMap"><include refid="select"></include>product_id = 1;</select><select id="selectOneByNameAndPrice" resultType="Products"><include refid="select"></include>product_name = #{productName}andprice > #{price}</select><insert id="insertOne" parameterType="Products" ><selectKey keyProperty="productId" keyColumn="product_id" resultType="int" order="AFTER">select last_insert_id();</selectKey>insert into products (product_name,color,price)values (#{productName},#{color},#{price})</insert><delete id="deleteOneById">delete from products where product_id = #{askdksad}</delete><update id="updateProductName" parameterType="Products">update products set product_name = #{productName} where product_id = #{productId}</update><select id="selectOneById" parameterType="int" resultType="com.aistart.tech.pojo.Products">/*参数名一个时虽然可以随便写,但是不推荐*/select<include refid="all"></include>from products where product_id = #{productId}/*默认调用了get函数,利用反射,根据get+param()的形式找函数并且执行*/</select><select id="selectAll" resultType="com.aistart.tech.pojo.Products">select<include refid="all"></include>from products</select><select id="selectOneBynName" resultType="Products"><include refid="select"></include>product_name = #{name}</select>
</mapper>
Products.java
package com.aistart.tech.pojo;import lombok.*;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Products {private Integer productId;private String productName;private String brand;private Double price;private String color;private String storageCapacity;private String description;}
PhoneDto.java
package com.aistart.tech.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class PhoneDto {private String name;private Double jg;
}
ProductsMapper.java
package com.aistart.tech.mapper;import com.aistart.tech.dto.PhoneDto;
import com.aistart.tech.pojo.Products;
import org.apache.ibatis.annotations.*;public interface ProductsMapper {public int insertOne(Products products);public Products selectOneById(int num);@Select("select * from products where product_name = #{name}")public Products selectOneByName(String name);
public Products selectOneByNameAndPrice(@Param("productName") String productName,@Param("price") double price);@Results({@Result(property = "name", column = "product_name"),@Result(property = "jg", column = "price")})@Select("select product_name,price from products where product_name = #{productName}")public PhoneDto selectDtoByName(@Param("productName") String productName);
}
DButil.java
package com.aistart.tech.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.InputStream;public class DButil {private static SqlSessionFactory sqlSessionFactory = null;private static SqlSessionFactory sqlSessionFactoryTest = null;static {
try {InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {throw new RuntimeException(e);}}public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();}public static void close(SqlSession session){session.close();}}
ProductsMapperTest
package com.aistart.tech.mapper;import com.aistart.tech.pojo.Products;
import com.aistart.tech.utils.DButil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import static org.junit.Assert.*;public class ProductsMapperTest {@Testpublic void selectOneById() {SqlSession sqlSession = null;try {sqlSession = DButil.getSqlSession();ProductsMapper mapper = sqlSession.getMapper(ProductsMapper.class);Products products = mapper.selectOneById(2);System.out.println(products);}catch (Exception e){e.printStackTrace();}finally {sqlSession.close();}}@Testpublic void selectOneByNameAndPrice() {SqlSession sqlSession = null;try {sqlSession = DButil.getSqlSession();ProductsMapper mapper = sqlSession.getMapper(ProductsMapper.class);Products products = mapper.selectOneByNameAndPrice("小米",0);System.out.println(products);}catch (Exception e){e.printStackTrace();}}@Testpublic void selectOneByName() {SqlSession sqlSession = DButil.getSqlSession();ProductsMapper mapper = sqlSession.getMapper(ProductsMapper.class);System.out.println(mapper.selectOneByName("小米"));sqlSession.close();}@Testpublic void selectDtoByName() {SqlSession sqlSession = DButil.getSqlSession();ProductsMapper mapper = sqlSession.getMapper(ProductsMapper.class);System.out.println(mapper.selectDtoByName("小米"));sqlSession.close();}
}