从JDBC连接池到Mybatis(Mybatis进阶篇五——注解开发)

九:Mybatis注解开发

pojo
package com.mybatisssss.pojo;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class Item {

    private Long id;			//商品编号
    private String title;		//标题
    private String sellPoint;	//买点
    private Long price;	//价格
    private Integer num;		//数量
    private String barcode;		//条形码
    private String image;		//图片
    private Long cid;			//外键,详情ID
    private Integer status;		//状态 1:正常,2下架
    private Date created;		//创建时间
    private Date updated;		//修改时间
    private String testdated;

    private ItemCat itemCat;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getSellPoint() {
        return sellPoint;
    }
    public void setSellPoint(String sellPoint) {
        this.sellPoint = sellPoint;
    }
    public Long getPrice() {
        return price;
    }
    public void setPrice(Long price) {
        this.price = price;
    }
    public Integer getNum() {
        return num;
    }
    public void setNum(Integer num) {
        this.num = num;
    }
    public String getBarcode() {
        return barcode;
    }
    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    public Long getCid() {
        return cid;
    }
    public void setCid(Long cid) {
        this.cid = cid;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    public Date getUpdated() {
        return updated;
    }
    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    public String getTestdated() {
        return testdated;
    }

    public void setTestdated(String testdated) {
        this.testdated = testdated;
    }

    public ItemCat getItemCat() {
        return itemCat;
    }

    public void setItemCat(ItemCat itemCat) {
        this.itemCat = itemCat;
    }

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", sellPoint='" + sellPoint + '\'' +
                ", price=" + price +
                ", num=" + num +
                ", barcode='" + barcode + '\'' +
                ", image='" + image + '\'' +
                ", cid=" + cid +
                ", status=" + status +
                ", created=" + created +
                ", updated=" + updated +
                ", testdated='" + testdated + '\'' +
                ", itemCat=" + itemCat +
                '}';
    }
}
package com.mybatisssss.pojo;

import java.util.Date;
import java.util.List;

public class ItemCat {
    private Long id;
    private Long parentId;
    private String name;
    private Integer status;
    private Integer sortOrder;
    private Integer isParent;
    private Date created;
    private Date updated;

    private List<Item> item;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getSortOrder() {
        return sortOrder;
    }

    public void setSortOrder(Integer sortOrder) {
        this.sortOrder = sortOrder;
    }

    public Integer getIsParent() {
        return isParent;
    }

    public void setIsParent(Integer isParent) {
        this.isParent = isParent;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    @Override
    public String toString() {
        return "ItemCat{" +
                "id=" + id +
                ", parentId=" + parentId +
                ", name='" + name + '\'' +
                ", status=" + status +
                ", sortOrder=" + sortOrder +
                ", isParent=" + isParent +
                ", created=" + created +
                ", updated=" + updated +
                ", item=" + item +
                '}';
    }
}
dao
package com.mybatisssss.dao;

import com.mybatisssss.pojo.Item;
import com.mybatisssss.pojo.ItemCat;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface ItemMapper {

    //新增注解
    @Insert("INSERT INTO tb_item VALUE (#{id},#{title},#{sellPoint},#{price}," +
            "#{num},#{barcode},#{image},#{cid},#{status},#{created},#{updated},#{testdated})")
    public Integer save(Item item);

    //修改注解
    @Update("UPDATE tb_item SET title = #{title},sell_point = #{sellPoint},price = #{price}," +
            "num = #{num},barcode = #{barcode},image = #{image},cid = #{cid},status = #{status}" +
            " WHERE id = #{id}")
    public Integer update(Item item);

    //删除注解
    @Delete("DELETE FROM tb_item WHERE id = #{id}")
    public Integer delete(Long id);

    //查询注解,单表条件查询
    @Select("SELECT * FROM tb_item WHERE id = #{id}")
    public Item getItembyId(Long id);

    //查询注解,查询全部返回集合
    @Select("SELECT * FROM tb_item")
    public List<Item> getItemAll();

    //查询注解,根据cid返回结果集合
    @Select("SELECT * FROM tb_item WHERE cid = #{id}")
    public List<Item> getItemByCid(Long id);

    /**
     * 多表查询:
     * 一对一 注解开发
     * 方式一
     */
    @Select("SELECT *,ti.id as iid,tic.id as icid FROM tb_item ti " +
            "INNER JOIN tb_item_cat tic ON ti.cid = tic.id")
    @Results({
            @Result(column = "iid",property = "id"),
            @Result(column = "title",property = "title"),
            @Result(column = "sell_point",property = "sellPoint"),
            @Result(column = "price",property = "price"),
            @Result(column = "num",property = "num"),
            @Result(column = "barcode",property = "barcode"),
            @Result(column = "image",property = "image"),
            @Result(column = "cid",property = "cid"),
            @Result(column = "status",property = "status"),
            @Result(column = "created",property = "created"),
            @Result(column = "updated",property = "updated"),
            @Result(column = "testdated",property = "testdated"),

            @Result(column = "icid",property = "itemCat.id"),
            @Result(column = "parent_id",property = "itemCat.parentId"),
            @Result(column = "name",property = "itemCat.name"),
            @Result(column = "status",property = "itemCat.status"),
            @Result(column = "sort_order",property = "itemCat.sortOrder"),
            @Result(column = "is_parent",property = "itemCat.isParent"),
    })
    public List<Item> findAll01();

    /**
     * 多表查询:
     * 一对一 注解开发
     * 方式二
     */
    @Select("SELECT * FROM tb_item")
    @Results({
            @Result(column = "iid",property = "id"),
            @Result(column = "title",property = "title"),
            @Result(column = "sell_point",property = "sellPoint"),
            @Result(column = "price",property = "price"),
            @Result(column = "num",property = "num"),
            @Result(column = "barcode",property = "barcode"),
            @Result(column = "image",property = "image"),
            @Result(column = "cid",property = "cid"),
            @Result(column = "status",property = "status"),
            @Result(column = "created",property = "created"),
            @Result(column = "updated",property = "updated"),
            @Result(column = "testdated",property = "testdated"),
            @Result(
                    property = "itemCat",  //要封装的属性名称
                    column = "cid",         //关联字段
                    javaType = ItemCat.class,  //要封装的实体类型
                    //select属性 代表查询哪个接口的方法
                    one = @One(select = "com.mybatisssss.dao.ItemCatMapper.getItemCatbyId")
            )
    })
    public List<Item> findAll02();
}
package com.mybatisssss.dao;

import com.mybatisssss.pojo.ItemCat;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface ItemCatMapper {

    //查询注解,单表条件查询
    @Select("SELECT * FROM tb_item_cat WHERE id = #{id}")
    public ItemCat getItemCatbyId(Long id);

    /**
     * 多表查询:
     * 一对多 注解开发
     */
    @Select("select * from tb_item_cat WHERE id = #{id}")
    @Results({
            @Result(column = "icid",property = "id"),
            @Result(column = "parent_id",property = "parentId"),
            @Result(column = "name",property = "name"),
            @Result(column = "status",property = "status"),
            @Result(column = "sort_order",property = "sortOrder"),
            @Result(column = "is_parent",property = "isParent"),
            @Result(
                    property = "item",  //要封装的属性名称
                    column = "id",         //关联字段
                    javaType = List.class,  //要封装的实体类型
                    many = @Many(select = "com.mybatisssss.dao.ItemMapper.getItemByCid")
            )
    })
    public List<ItemCat> findAll(Long id);
}
sqlMapperConfig.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标签,加载外部properties标签 -->
    <properties resource="jdbc.properties"></properties>

    <!-- default="developement":指定默认的环境名称-->
    <environments default="developement">
        <!-- id="developement":指定当前环境的名称-->
        <environment id="developement">
            <!-- type="JDBC":指事务管理类型是JDBC-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- type="POOLED":指定当前数据源类型是连接池 -->
            <dataSource type="POOLED">
                <!-- 数据源配置的基本参数 -->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--加载映射文件
    <mappers>
        <mapper resource="mapper/ItemMapper.xml"></mapper>
    </mappers> -->

    <!-- 加载映射关系 注解开发-->
    <mappers>
        <package name="com.mybatisssss.dao"/>
    </mappers>

</configuration>
jdbc.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jtdb-small
user=root
password=123456
test
package com.mybatisssss.test;

import com.mybatisssss.dao.ItemMapper;
import com.mybatisssss.pojo.Item;
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.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class mybatisTest {
    ItemMapper mapper;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(ItemMapper.class);

    }

    @Test
    public  void fun00(){
        Item item = mapper.getItembyId(875724L);
        System.out.println(item);
    }

    @Test
    public  void fun01(){
        List<Item> all = mapper.getItemAll();
        for (Item item : all) {
            System.out.println(item);
        }
    }

    @Test
    public  void fun02(){
        Item item = new Item();
        item.setId(123L);
        item.setTitle("测试");
        item.setSellPoint("测试");
        item.setPrice(100L);
        item.setNum(123);
        item.setBarcode("测试");
        item.setImage("测试");
        item.setCid(123L);
        item.setStatus(123);
        item.setCreated(new Date());
        item.setUpdated(new Date());
        item.setTestdated("123");
        Integer save = mapper.save(item);
        System.out.println(save);
    }

    @Test
    public  void fun03(){
        Item item = new Item();
        item.setId(123L);
        item.setTitle("测试2");
        item.setSellPoint("测试2");
        item.setPrice(100L);
        item.setNum(123);
        item.setBarcode("测试2");
        item.setImage("测试2");
        item.setCid(123L);
        item.setStatus(123);
        Integer update = mapper.update(item);
        System.out.println(update);
    }

    @Test
    public  void fun04(){
        List<Item> all = mapper.findAll01();
        for (Item item : all) {
            System.out.println(item);
        }
    }

    @Test
    public  void fun05(){
        List<Item> all = mapper.findAll02();
        for (Item item : all) {
            System.out.println(item);
        }
    }

}
package com.mybatisssss.test;

import com.mybatisssss.dao.ItemCatMapper;
import com.mybatisssss.dao.ItemMapper;
import com.mybatisssss.pojo.Item;
import com.mybatisssss.pojo.ItemCat;
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.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class mybatisTest00 {
    ItemCatMapper mapper;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(ItemCatMapper.class);

    }

    @Test
    public  void fun00(){
        List<ItemCat> all = mapper.findAll(560L);
        for (ItemCat cat : all) {
            System.out.println(cat);
        }
    }
}

本文只是个人学习内容整理的笔记,如有侵权,即联系870013269@qq.com删除

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值