使用mybatis框架完成数据库中的CRUD(使用工具类)


mybatis框架的核心配置文件:创建一个名为resource的资源文件夹 ,用来存放配置文件


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">
<!-- 
	完成一个mybatis-config.xml的文件
		-> 作用:配置连接数据库的所有需要的环境
			必须连接到所有要使用的映射文件(ProductMapper.xml)
 -->

<!--configuration 根目录  -->
<configuration>
	<!--  引入(关联)db.properties文件 -->
	<properties resource="db.properties"></properties>
	<!-- 环境们:很多环境     default:表示默认使用哪一个环境-->
	<environments default="development">
		<!-- 单个环境:一个环境       id:表示这个环境的名称-->
		<environment id="development">
			<!-- transactionManager:事务管理器 (使用的JDBC事务管理器)-->
			<transactionManager type="JDBC"></transactionManager>
			<!-- MyBatis自帶POOLED连接池(数据源) -->
			<dataSource type="POOLED">
				<property name="driver" value="${db_driverClassname}" />
				<property name="url" value="${db_url}" />
				<property name="username" value="${db_username}" />
				<property name="password" value="${db_password}" />
			</dataSource>
		</environment>
	</environments>
	
	<!-- resource:表示 核心配置文件(mybatis-config.xml)必须与所有的对象映射文件(ProductMapper.xml)关联!!!! -->
	<mappers>
		<mapper resource="cn/itsource/domain/ProductMapper.xml" />
	</mappers>
</configuration>

db.properties文件:

db_driverClassname=com.mysql.jdbc.Driver
db_url=jdbc:mysql://localhost:3306/test666
db_username=root
db_password=admin

查看mybatis运行日志所需配置文件:文件名为:log4j.properties

log4j.rootLogger=ERROR, stdout
#log4j.rootLogger=NONE
log4j.logger.cn.itsource=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout



domain包域对象:

package cn.itsource.domain;

/**
 *   域对象
 * */
public class Product {
	
	/**
	 *  商品id
	 * */
	private	Long id;
	/**
	 *  商品名称
	 * */
	private String productName;
	/**
	 *  商品品牌
	 * */
	private String brand;
	/**
	 *  商品供应商
	 * */
	private String supplier;
	/**
	 *  商品零售价
	 * */
	private Double salePrice;
	/**
	 *  商品成本价
	 * */
	private Double costPrice;
	/**
	 * 商品折扣
	 * */
	private Double cutoff;
	/**
	 *  商品分类编号
	 * */
	private Long dir_id;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getProductName() {
		return productName;
	}
	public void setProductName(String productName) {
		this.productName = productName;
	}
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public String getSupplier() {
		return supplier;
	}
	public void setSupplier(String supplier) {
		this.supplier = supplier;
	}
	public Double getSalePrice() {
		return salePrice;
	}
	public void setSalePrice(Double salePrice) {
		this.salePrice = salePrice;
	}
	public Double getCostPrice() {
		return costPrice;
	}
	public void setCostPrice(Double costPrice) {
		this.costPrice = costPrice;
	}
	public Double getCutoff() {
		return cutoff;
	}
	public void setCutoff(Double cutoff) {
		this.cutoff = cutoff;
	}
	public Long getDir_id() {
		return dir_id;
	}
	public void setDir_id(Long dir_id) {
		this.dir_id = dir_id;
	}
	@Override
	public String toString() {
		return "Product [id=" + id + ", productName=" + productName + ", brand=" + brand + ", supplier=" + supplier
				+ ", salePrice=" + salePrice + ", costPrice=" + costPrice + ", cutoff=" + cutoff + ", dir_id=" + dir_id
				+ "]";
	}
	
}


配置对象关系映射文件(ProductMapper.xml):用来写sql语句

<?xml version="1.0" encoding="UTF-8"?>

<!-- 完成一个对象关系映射文件 -> 
	作用:一个对象的所有SQL都应该写在这个映射文件中 这个文件一般和我们的domain写在同一个包里面,取名为 
	-> domain的名称+Mapper.xml -->
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace:命名空间(每个Mapper必须有命名空间) -->
<mapper namespace="cn.itsource.domain.ProductMapper">
	<!-- 
	    select:它里面写查询语句
	    id:查询语句的唯一标识(名称不能重复)
	    	如何在 java代码中找到sql语句?  命名空间+id 
	    		例子:cn.itsource.domain.ProductMapper.select
	    parameterType:传入的参数类型。 除了MyBatis支持的类型,其它的类型都通通使用全限定名
	    resultType:返回的每一条数据的结果类型(结果类型写权限定名称 ) 查询功能使用
	 -->
	<select id="selectOne" parameterType="Long" resultType="cn.itsource.domain.Product">
		select * from product where id = #{id}
	</select>
	
	<!-- resultType:表示返回的数据类型   -->
	<select id="selectAll"  resultType="cn.itsource.domain.Product">
		select * from Product 
	</select>
	
	<!--parameterType :表示传入参数(Product)。
			useGeneratedKeys:是否需要获取主键
			keyColumn:主键在数据库中的名称(不写的话默认名称和keyProperty一致)
			keyProperty:对象中的属性(代表主键的那个属性)
	  -->
	<insert id="save"  parameterType="cn.itsource.domain.Product" 
		useGeneratedKeys="true" keyColumn="id"  keyProperty="id">
		insert into product (productName,dir_id,salePrice,supplier,brand,cutoff,costPrice)
		values(#{productName},#{dir_id},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})
	</insert>
	
	<!-- parameterType:接收参数没有写权限顶名称,使用的别名(简写) -->
	<delete id="delete"  parameterType="long">
		delete from product where id = #{id}
	</delete>
	
	<update id="update"  parameterType="cn.itsource.domain.Product">
		update product set productName=#{productName},dir_id=#{dir_id},
		salePrice=#{salePrice},supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice}
		where id = #{id}
	</update>
	
</mapper>

dao层接口类:

package cn.itsource.dao;

import java.util.List;

import cn.itsource.domain.Product;

/**
 *  完成商品的增删改查
 * */
public interface IProductDao {
	
	/**
	 *  添加商品
	 * */
	void save(Product obj);
	
	/**
	 *  修改商品信息
	 * */
	void update(Product obj);
	
	/**
	 *  删除商品
	 * */
	void delete(Long id);
	
	/**
	 *  查询单条商品信息
	 * */
	Product queryOne(Long id);
	
	/**
	 *  查询所有商品信息
	 * */
	List<Product> queryAll();
}

测试类:

package cn.itsource.dao;

import java.util.List;

import org.junit.Test;

import cn.itsource.dao.impl.ProductDaoImpl;
import cn.itsource.domain.Product;

/**
 *  测试类
 * */
public class ProductDaoTest {

	IProductDao dao = new ProductDaoImpl();
	
	@Test
	public void testSave() {
		Product product = dao.queryOne(4L);
		product.setProductName("苹果10");
		product.setSalePrice(8000D);
		dao.save(product);
		
	}

	@Test
	public void testUpdate() {
		Product product = dao.queryOne(10L);
		product.setProductName("小米7777");
		dao.update(product);
	}

	@Test
	public void testDelete() {
		dao.delete(20L);
	}

	@Test
	public void testQueryOne() {
		Product p = dao.queryOne(3L);
		System.out.println(p);
		
	}

	@Test
	public void testQueryAll() {
		List<Product> ps = dao.queryAll();
		for (Product product : ps) {
			System.out.println(product);
		}
	}

}

工具类:

package cn.itsource.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public enum MyBatisUtil {
	
	/**
	 *    MyBatis三大核心对象特点:
	 *    SqlSessionFactoryBuilder——创建了SqlSessionFactory后,这个类就不需要存在了
	 * 	  SqlSessionFactory——被创建,SqlSessionFactory应该在你的应用执行期间都存在
	 * 	  SqlSession——每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能被共享,也是线程不安全的
	 * */
	
	INSTANCE;
	
	//SqlSessionFactory只需要一个
	private static SqlSessionFactory factory;
	
	/**
	 *  把factory放在静态代码块中的原因?
	 *  	因为factory只需要创建一个,而静态代码块中的代码只会执行一次
	 * */
	static{
		try {
			//创建一个SqlSession工厂对象,读取我们的核心配置文件
			factory = new SqlSessionFactoryBuilder().build(Resources
					.getResourceAsStream("mybatis-config.xml"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *  直接返回一个SqlSession对象
	 * */
	public SqlSession openSession(){
		//通过SqlSessionFactory创建SqlSession对象
		return factory.openSession();
	}
}


实现类:

package cn.itsource.dao.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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 cn.itsource.dao.IProductDao;
import cn.itsource.domain.Product;
import cn.itsource.util.MyBatisUtil;

public class ProductDaoImpl implements IProductDao {

			
	@Override
	public void save(Product obj) {
		//通过MyBatisUtil工具类获取SqlSession
		SqlSession session = MyBatisUtil.INSTANCE.openSession();
		try {
			//通过session直接执行sql语句
			session.insert("cn.itsource.domain.ProductMapper.save", obj);
			//提交事务
			session.commit();
		} catch (Exception e) {
			session.rollback();
			e.printStackTrace();
		}finally {
			session.close();
		}
	}

	@Override
	public void update(Product obj) {
		//通过工具类获取SqlSession对象
		SqlSession session = MyBatisUtil.INSTANCE.openSession();
		try {
			//通过session直接执行sql语句
			session.update("cn.itsource.domain.ProductMapper.update", obj);
			//提交事务
			session.commit();
		} catch (Exception e) {
			session.rollback();
			e.printStackTrace();
		}finally {
			session.close();
		}
		
	}

	@Override
	public void delete(Long id) {
		//通过工具类获取SqlSession对象
		SqlSession session = MyBatisUtil.INSTANCE.openSession();
		try {
			//通过session直接执行sql语句
			session.delete("cn.itsource.domain.ProductMapper.delete", id);
			//提交事务
			session.commit();
		} catch (Exception e) {
			session.rollback();
			e.printStackTrace();
		}finally {
			session.close();
		}

	}

	@Override
	public Product queryOne(Long id) {
		Product p = null;
		//通过工具类获取SqlSession对象
		SqlSession session = MyBatisUtil.INSTANCE.openSession();
		try {
			//通过session直接执行sql语句 ,返回结果
			p = session.selectOne("cn.itsource.domain.ProductMapper.selectOne", id);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
		return p;
	}

	@Override
	public List<Product> queryAll() {
		
		List<Product> ps = new ArrayList<>();
		//通过工具类获取SqlSession对象
		SqlSession session = MyBatisUtil.INSTANCE.openSession();
		try {
			//通过session直接执行sql语句,返回结果
			ps = session.selectList("cn.itsource.domain.ProductMapper.selectAll");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
		return ps;
	}

}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值