Mybatis(二)CRUD通过注解方式

安装

如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

我的version版本是3.5.3

接着导入MySQL

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.18</version>			
</dependency>		

导入单元测试Junit

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>			
</dependency>		

maven项目中配置JDK1.8的插件

<build>
       <plugins>
           <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-compiler-plugin</artifactId>
             <configuration>
               <source>1.8</source>
               <target>1.8</target>
               <encoding>utf-8</encoding>
             </configuration>
           </plugin>
       </plugins>
   </build>

在数据库中创建表

use test;
CREATE TABLE category_ (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(32) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

maven 项目结构图

在这里插入图片描述

数据库配置文件db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
username=root
password=root

mybatis的配置文件 mybatis.cfg.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"></properties>
	<!--  类型别名
	自动扫描com.how2java.pojo下的类型,
	使得在后续配置文件Category.xml中使用resultType的时候,可以直接使用Category,
	而不必写全pojo.Category
	-->
	<typeAliases>
		<package name="pojo"/>
	</typeAliases>
	<!-- 默认使用的环境 ID -->
	<environments default="development">
	<!--每个 environment 元素定义的环境 ID  -->
		<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)定义 SQL 映射语句了。告诉 MyBatis 到哪里去找到这些语句 -->
	<mappers>
	<!--映射文件的位置  -->
	<!-- 将包内的映射器接口实现全部注册为映射器 -->
		<package name="dao"/>
	</mappers>
</configuration>

创建实体类Category

package pojo;

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;
	}
}

创建映射器类CategoryDAO

package dao;

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 pojo.Category;

/**
 * @author 86182
 * @date: 2020年1月14日下午11:47:16
 * @verion:1.0
 * @description:
 */
public interface CategoryDAO {
	@Select("select * from category_")
	public List<Category>findAll();
	@Select("select * from category_ where id=#{id}")
	public Category getOne(int id);
	@Insert("insert into category_ values (null,#{name})")
	public int save(Category c);
	@Update("update category_ set name=#{name} where id=#{id}")
	public int update(Category c);
	@Delete("delete from category_ where id=#{id}")
	public int deleteOne(int id);
	@Delete("delete from category_ ")
	public void deleteAll();
}

测试数据

package test;

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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import dao.CategoryDAO;
import pojo.Category;

/**
 * @author 86182
 * @date: 2020年1月14日下午11:48:32
 * @verion:1.0
 * @description:
 */
public class TestCase {
	SqlSession ss;
	SqlSessionFactory sf;

	@Before
	public void before() throws IOException {
		// 读取mybatis-cfg.xml文件
		String resource = "mybatis.cfg.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 初始化mybatis,创建SqlSessionFactory类的实例
		sf = new SqlSessionFactoryBuilder().build(inputStream);
		// 创建Session实例
		ss = sf.openSession();
	}

	/*
	 * 查询所有的
	 */
	@Test
	public void findAll() {
		// 获得映射器mapper接口的代理对象
		CategoryDAO dao = ss.getMapper(CategoryDAO.class);
		List<Category> list = dao.findAll();
		for (Category category : list) {
			System.out.println(category.getName());
		}
	}

	/*
	 * 获取指定的
	 */
	@Test
	public void getOne() {
		CategoryDAO dao = ss.getMapper(CategoryDAO.class);
		Category list = dao.getOne(2);
		System.out.println(list.getId() + "," + list.getName());
	}

	/*
	 * 新增数据
	 */
	@Test
	public void save() {
		CategoryDAO dao = ss.getMapper(CategoryDAO.class);
		Category c = new Category();
		c.setName("分类2");
		int save = dao.save(c);
		System.out.println(save);
	}

	/*
	 * 修改数据
	 */
	@Test
	public void update() {
		CategoryDAO dao = ss.getMapper(CategoryDAO.class);
		Category c = dao.getOne(2);
		c.setName("分类2-1");
		int update = dao.update(c);
		System.out.println(update);
	}

	/*
	 * 删除一条数据
	 */
	@Test
	public void deleteOne() {
		CategoryDAO dao = ss.getMapper(CategoryDAO.class);
		int delete = dao.deleteOne(2);
		System.out.println(delete);
	}

	/*
	 * 所有数据
	 */
	@Test
	public void deleteAll() {
		CategoryDAO dao = ss.getMapper(CategoryDAO.class);
		dao.deleteAll();
	}

	@After
	public void after() {
		// 提交事务
		ss.commit();
		// 关闭Session
		ss.close();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值