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


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


mybatis-config.xml的文件:







	
	
	
	
		
		
			
			
			
			
				
				
				
				
			
		
	
	
	
	
		
	

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语句




 



	
	
	
	
	
	
	
	
		insert into product (productName,dir_id,salePrice,supplier,brand,cutoff,costPrice)
		values(#{productName},#{dir_id},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})
	
	
	
	
		delete from product where id = #{id}
	
	
	
		update product set productName=#{productName},dir_id=#{dir_id},
		salePrice=#{salePrice},supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice}
		where id = #{id}
	
	

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 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 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 queryAll() {
		
		List 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;
	}

}




你可能感兴趣的:(使用mybatis框架完成数据库中的CRUD(使用工具类))