mybatis注解

这篇博客详细介绍了如何使用MyBatis进行CRUD操作,以及处理一对多、多对一和多对多的关系。通过实例展示了在数据库和Java项目中设置MyBatis配置,创建实体类、映射文件和接口,并进行测试,最终得到了预期的查询结果。
摘要由CSDN通过智能技术生成

mybatis的CRUD

1.创建数据库

// 分类表
    CREATE TABLE category_ (
        id int(11) NOT NULL AUTO_INCREMENT    PRIMARY KEY ,
        name varchar(32) DEFAULT NULL
    ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

    INSERT INTO category_ VALUES (null,'category1');
    INSERT INTO category_ VALUES (null,'category2');

2.新建java项目

3.创建lib,导入jar包,新建mybatis的配置文件mybayis-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>
    <typeAliases>
        <package name="com.how2java.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/mybatis?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
        <mapper class="com.how2java.mapper.CategoryMapper"/>
    </mappers>
</configuration>

4.新建实体类

package com.how2java.pojo;

/**
 * @author lenovo
 */
public class Category {
   private int id;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   
}

5.创建实体类的映射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.how2java.pojo">
   <insert id="addCategory" parameterType="Category" >
      insert into mybatis.category_ ( name ) values (#{name})
   </insert>

   <delete id="deleteCategory" parameterType="Category" >
      delete from mybatis.category_ where id= #{id}
   </delete>

   <select id="getCategory" parameterType="_int" resultType="Category">
      select * from   mybatis.category_  where id= #{id}
   </select>

   <update id="updateCategory" parameterType="Category" >
      update mybatis.category_ set name=#{name} where id=#{id}
   </update>
   <select id="listCategory" resultType="Category">
      select * from   mybatis.category_
   </select>
</mapper>

6.创建接口

package com.how2java.mapper;
 
import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.how2java.pojo.Category;
 
/**
 * @author lenovo
 */
public interface CategoryMapper {
 
    @Insert(" insert into category_ ( name ) values (#{name}) ")  
    public int add(Category category);  
       
    @Delete(" delete from category_ where id= #{id} ")  
    public void delete(int id);  
       
    @Select("select * from category_ where id= #{id} ")  
    public Category get(int id);  
     
    @Update("update category_ set name=#{name} where id=#{id} ")  
    public int update(Category category);   
       
    @Select(" select * from category_ ")  
    public List<Category> list();  
}

7.创建测试类

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

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 com.how2java.mapper.CategoryMapper;
import com.how2java.pojo.Category;

/**注解实现CRUD
 * @author lenovo
 */
public class MybatisTest {

    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        CategoryMapper mapper = session.getMapper(CategoryMapper.class);

//        add(mapper);
//        delete(mapper);
//        get(mapper);
//        update(mapper);
        listAll(mapper);

        session.commit();
        session.close();

    }

    private static void update(CategoryMapper mapper) {
        Category c= mapper.get(8);
        c.setName("修改了的Category");
        mapper.update(c);
        listAll(mapper);
    }

    private static void get(CategoryMapper mapper) {
        Category c= mapper.get(8);
        System.out.println(c.getName());
    }

    private static void delete(CategoryMapper mapper) {
        mapper.delete(2);
        listAll(mapper);
    }

    private static void add(CategoryMapper mapper) {
        Category c = new Category();
        c.setName("新增加的Category");
        mapper.add(c);
        listAll(mapper);
    }

    private static void listAll(CategoryMapper mapper) {
        List<Category> cs = mapper.list();
        for (Category c : cs) {
            System.out.println(c.getName());
        }
    }
}

8.运行测试类

结果:

category1
category2

mybatis的一对多

1.创建数据库:mybatis

// 分类表
    CREATE TABLE category_ (
        id int(11) NOT NULL AUTO_INCREMENT    PRIMARY KEY ,
    name varchar(32) DEFAULT NULL
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
//   产品表
    create table product_(
        id int NOT NULL AUTO_INCREMENT PRIMARY KEY ,
        name varchar(30)  DEFAULT NULL,
        price float  DEFAULT 0,
        cid int 
        )AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
//                新增2条分类数据,id分别是1,2
//                新增6条产品数据,分别关联上述2条分类数据
        INSERT INTO category_ VALUES (1,'category1');
        INSERT INTO category_ VALUES (2,'category2');
     
        INSERT INTO product_ VALUES (1,'product a', 88.88, 1);
        INSERT INTO product_ VALUES (2,'product b', 88.88, 1);
        INSERT INTO product_ VALUES (3,'product c', 88.88, 1);
        INSERT INTO product_ VALUES (4,'product x', 88.88, 2);
        INSERT INTO product_ VALUES (5,'product y', 88.88, 2);
        INSERT INTO product_ VALUES (6,'product z', 88.88, 2);

2.创建java项目

3.新建lib,引入库,并新建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>
    <typeAliases>
      <package name="com.how2java.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/mybatis?characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
        <mapper class="com.how2java.mapper.CategoryMapper"/>  
        <mapper class="com.how2java.mapper.ProductMapper"/>  
    </mappers>
</configuration>

4.创建产品类Product 和类别类Category

package com.how2java.pojo;
 
/**
 * @author lenovo
 */
public class Product {
    private int id;
    private String name;
    private float price;

   public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + "
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值