MyBatis 注解开发

1、实体类

​ 创建和数据库表相对应的实体类。

  • Cake
    在这里插入图片描述
public class Cake {
    private Long id;
    private Long categoryId;
    private String name;
    private Integer level;
    private Integer price;     // 价格,整型,以分为单位存储
    private byte[] smallImg;   // 图片(二进制数据)
    private Date createTime;
    private Date updateTime;
    
    // 各属性的 set 和 get 方法
    ...
}
  • Category
    在这里插入图片描述
public class Category {
    private Long id;
    private String name;
    private Date createTime;
    private Date updateTime;

    // 各属性的 set 和 get 方法
    ...
}

2、配置文件

  • MyBatis 根配置文件
<?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="jdbc.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>
    </environments>

    <mappers>
        <!-- package 配置该包下的接口自动注入持久化操作 -->
        <package name="com.moc.cake_mall.mapper"/>
    </mappers>
</configuration>
  • jdbc 源配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/cake?useUnicode=true&characterEncoding=UTF-8
username=root
password=root

3、持久化映射接口

  • CakeMapper
public interface CakeMapper {
    // 分页查询
    @Select("select * from cake order by create_time desc limit #{skip}, #{size}")
    // @Result 注解 ==》 该注解是将表字段与实体属性相匹配的一种方式
    @Results({
                // id = true 表示该字段为主键
                @Result(id = true, column = "id", property = "id"),
                @Result(column = "category_id", property = "categoryId"),
                @Result(column = "name", property = "name"),
                @Result(column = "level", property = "level"),
                @Result(column = "price", property = "price"),
                @Result(column = "create_time", property = "createTime"),
                @Result(column = "update_time", property = "updateTime")
            })
    List<Cake> getCakes(Integer skip, Integer size);


    // 根据分类分页查询
    @Select("select id, category_id categoryId, name, level, price, " + 
            "create_time createTime, update_time updateTime" + 
            "from cake where category_id = #{categoryId}" + 
            "order by create_time desc limit #{skip}, #{size}")
    // @Param 注解 ==》 给参数命名,参数命名后就能根据名字得到参数值 #{categoryId} ,
    // 每个需要传入SQL语句的值,都需要加注解
    List<Cake> getCakesByCategoryId(@Param("categoryId") Long categoryId, @Param("skip") Integer skip, @Param("size") Integer size);


    // 根据分类ID进行数量的统计
    @Select("select count(*) from cake where category_id = #{categoryId}")
    int countCakesByCategoryId(@Param("categoryId") Long categoryId);

    
    // 保存信息
    // 只有一个参数的时候 cake.xxx 中的 cake 可以省略
    @Insert("insert into cake(category_id, name, level, " + 
            "price, small_img, create_time, update_time) " +
            "value (#{cake.categoryId}, #{cake.name}, " + 
            "#{cake.level}, #{cake.price}, #{cake.smallImg}, " +
            "#{cake.createTime}, #{cake.updateTime})")
    void addCake(@Param("cake") Cake cake);

    
    // 查询蛋糕图片信息
    // select * from 表名 for update: 把查询出来的数据进行加锁控制,别人就无法查询更新
    @Select("select small_img smallImg from cake where id = #{id} for update")
    Cake getImg(@Param("id") Long id);
}
  • CategoryMapper
public interface CategoryMapper {
    // 查询全部
    // @Select 注解 ==》 查询数据库,如果存在别名使用别名与实体类属性匹配
    @Select("select id, name, create_time createTime, update_time updateTime from category")
    List<Category> getCategories();


    // 根据ID删除某一具体
    // @Delete 注解 ==》 数据库删除操作,#{id} 与参数 id 名称保持一致,从中获取值
    @Delete("delete from category where id = #{id}")
    void deleteById(Long id);


    // 插入蛋糕分类信息
    // @Insert 注解 ==》 数据库添加行,从参数对象的属性中取值
    @Insert("insert into category(name, create_time, update_time)" +
            "values(#{name}, #{createTime}, #{updateTime}")
    void addCategory(Category category);
}

4、MyBatis 工具类

​ 主要用于获取 SQLSession 实例。

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            String resource = "config.xml";
            reader = Resources.getResourceAsReader(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
}

5、服务类

​ 针对具体的持久化接口类实现其更具体的业务操作。

  • CakeService
public class CakeService {
    // 根据分类 ID 查询商品信息(分页的内容)
    public List<Cake> getCakesByCategoryId(Long categoryId, Integer page, Integer size) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            return mapper.getCakesByCategoryId(categoryId, (page - 1) * size, size);
        } finally {
            sqlSession.close();
        }
    }

    // 增添业务数据操作
    public void addCake(Cake cake) {
        Date now = new Date();
        cake.setCreateTime(now);
        cake.setUpdateTime(now);
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            mapper.addCake(cake);
            sqlSession.commit();  // 注意这里需要提交
        } finally {
            sqlSession.close();
        }
    }

    // 指定的业务查询操作
    public int countCakesByCategoryId(Long categoryId) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            return mapper.countCakesByCategoryId(categoryId);
        } finally {
            sqlSession.close();
        }
    }

    // 指定的业务查询操作
    public Cake getCakeImg(Long id) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
            return mapper.getImg(id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return null;
    }
}
  • CategoryService
public class CategoryService {
    // 指定的业务查询操作
    public List<Category> getCategories() {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CategoryMapper mapper = sqlSession.getMapper(CategoryMapper.class);
            return mapper.getCategories();
        } finally {
            sqlSession.close();
        }
    }

    // 增添业务数据操作
    public void addCategory(Category category) {
        Date now = new Date();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            CategoryMapper mapper = sqlSession.getMapper(CategoryMapper.class);
            mapper.addCategory(category);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}

6、应用层

​ 这里是在 Servlet 中使用持久化操作。

public class CakeServlet extends HttpServlet {
    private CakeService cakeService;
    private CategoryService categoryService;

    @Override
    public void init() throws ServletException {
        super.init();
        cakeService = new CakeService();
        categoryService = new CategoryService();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		...
		List<Cake> cakes = cakeService.getCakesByCategoryId(categoryId, 1, 5000);
		List<Category> categories = categoryService.getCategories();
		cakeService.addCake(cake);
		categoryService.addCategory(category);
		int count = cakeService.countCakesByCategoryId(categoryId);
		Cake cake = cakeService.getCakeImg(Long.valueOf(idStr));
		...
    }

    @Override
    public void destroy() {
        super.destroy();
        cakeService = null;
        categoryService = null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值