商品的类别
一、步骤
1.引入相关依赖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.zjd</groupId>
<artifactId>Part4</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
2.导入数据库数据
1、新建数据库mybatis
CREATE DATABASE mybatis;
2、在mybatis数据库下创建表product
create table product(
id int primary key auto_increment,
goodsname varchar(20) not null ,
price int not null ,
typeid int not null
);
3、在product表中插入数据
insert into product(id, goodsname, price, typeid) VALUES
(1,'电视机',5000,1),
(2,'冰箱',4000,2),
(3,'空调',3000,2),
(4,'洗衣机',2000,4);
4、在mybatis数据库下创建表category
create table category(
id int primary key auto_increment,
typename varchar(20) not null
);
5、在category表中插入数据
insert into category(id, typename) VALUES
(1,'黑色电视'),
(2,'白色电视');
3.创建连接数据库配置文件db.properties
# MySQL的版本在8.0之下的,
mysql.driver=com.mysql.jdbc.Driver
# MySQL的版本在8.0之上的,
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root
4.创建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="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<package name="com.zjd.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zjd/mapper/CategoryMapper.xml"/>
</mappers>
</configuration>
5.创建product的实体类Product.java
package com.zjd.pojo;
public class Product {
private int id;
private String goodsname;
private int price;
private int typeid;
@Override
public String toString() {
return "Product{" +
"id=" + id +
", goodsname='" + goodsname + '\'' +
", price=" + price +
", typeid=" + typeid +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoodsname() {
return goodsname;
}
public void setGoodsname(String goodsname) {
this.goodsname = goodsname;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getTypeid() {
return typeid;
}
public void setTypeid(int typeid) {
this.typeid = typeid;
}
}
6.创建category的实体类Category.java
package com.zjd.pojo;
import java.util.List;
public class Category {
private int id;
private String typename;
private List<Product> product;
@Override
public String toString() {
return "Category{" +
"id=" + id +
", typename='" + typename + '\'' +
", product=" + product +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
7.创建Category.java的映射文件CategoryMapper.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="com.zjd.pojo.Category">
<select id="findProductWithCategory" parameterType="Integer"
resultMap="ProductWithCategoryResult">
SELECT c.*,p.id as typeid,p.goodsname,p.price
from category c,product p
WHERE c.id=p.typeid
and c.id=#{id}
</select>
<resultMap type="com.zjd.pojo.Category"
id="ProductWithCategoryResult">
<id property="id" column="id"/>
<result property="typename" column="typename"/>
<collection property="product" ofType="com.zjd.pojo.Product">
<id property="id" column="typeid"/>
<result property="goodsname" column="goodsname"/>
<result property="price" column="price"/>
</collection>
</resultMap>
</mapper>
8.将映射文件加载到mybatis-config.xml中
<!-- 上图我已加载过 -->
<mappers>
<mapper resource="com/zjd/mapper/CategoryMapper.xml"/>
</mappers>
9.创建MyBatis的工具类MyBatisUtils.java
package com.zjd.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;
public class MyBatisUtils {
public static SqlSessionFactory sqlSession=null;
static {
try {
Reader reader= Resources.getResourceAsReader("mybatis-config.xml");
sqlSession=new SqlSessionFactoryBuilder().build(reader);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sqlSession.openSession();
}
}
9.创建测试类CategoryTest.java测试运行
package Test;
import com.zjd.pojo.Category;
import com.zjd.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CategoryTest {
SqlSession session=null;
@Before
public void Before(){
session= MyBatisUtils.getSession();
}
@Test
public void findProductWithCategory(){
Category category=session.selectOne("com.zjd.pojo.Category.findProductWithCategory",2);
System.out.println(category);
}
@After
public void After(){
session.commit();
session.close();
}
}
二、项目结构
注意:这个项目文件里,除了我们上述的这类文件之外,还有一个log4j.properties文件,这个文件是方便大家查看sql语句运行的情况,下面是它的配置代码(配置时,需要现在pom.xml文件中引入jar包)
1、引入jar包:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、配置代码:
#全局日志配置
log4j.rootLogger=DEBUG,Console
#控制台输出配置
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#日志输出级别
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG